Archive

Posts Tagged ‘uri’

Getting The Current URI In PHP

April 15th, 2008 No comments

The $_SERVER superglobal array contains lots of information about the current page location. You can print this off in full using the following line of code.

echo '<pre>'.print_r($_SERVER,true).'</pre>';

Although this array doesn’t have the full URI we can piece together the current URI using bits of the $_SERVER array. The following function does this and returns a full URI.

function currentUri(){
 $uri = 'http';
 if(isset($_SERVER['HTTPS'])){
  if($_SERVER['HTTPS'] == 'on'){
   $uri .= 's';
  };
 };
 $uri .= '://';
 if($_SERVER['SERVER_PORT'] != '80'){
  $uri .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
 }else{
  $uri .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
 };
 return $uri;
}

You can use this function like this:

echo currentUri();

Categories: PHP Tags: , , , , , ,

Creating A URI Slug With PHP

March 28th, 2008 No comments

The use of mod_rewrite on a site can have a powerful effect on search engine positioning, but to do it properly you will need to create a "slug" for each page. A slug is a lowercase alphanumeric version of the page title, with any spaces removed.

To get a slug you will need to use a function to turn a readable page title into a string that can be used as part of a URI.

This function is taken from Bramus and his excellent article about creating a post slug, and it does the job very nicely.

function fixForUri($string){
 $slug = trim($string); // trim the string
 $slug= preg_replace('/[^a-zA-Z0-9 -]/','',$slug ); // only take alphanumerical characters, but keep the spaces and dashes too...
 $slug= str_replace(' ','-', $slug); // replace spaces by dashes
 $slug= strtolower($slug); // make it lowercase
 return $slug;
}

To use the function just pass your page title (and it can be as messy as you like) into the function and capture the output.

$string = '"I\'ve got a lovely *bunch* of coconuts!"';
echo fixForUri($string);

UPDATE:

I recently found a bug in this function where any trailing spaces where converted into hyphens and used as part of the slug. To stop this I have added a call to trim() in order to prevent this from happening.

Categories: PHP Strings Tags: , , , , ,