A TinyURL PHP page |
Written by Harry Fairhead | |||||
Sunday, 05 July 2009 | |||||
Page 3 of 4
Getting the current URL in PHPThe first task is to obtain the URL of the site, i.e the http://yoursite part of the tiny URL. This should be easy in PHP using just the $_SERVER function to retrieve standard variables but, as with browsers, web servers do things differently and it is remarkably difficult to write code that will return the current URL irrespective of its format and the server. The simplest solution is use the Joomla framework. To do this we have to load and initialise it. The simplest way to do this is to open the index.php file in the root of the Joomla installation and copy the initial lines into a new file called tinyURL.php: <?php This is the first few lines of index.php with the comments removed - you can leave them in if you want to. Next we need to retrieve the current URL and this is most easily done using the JURI object (look up its definition on the Joomla documentation site): $uri =& JURI::getInstance(); Notice that the object already exists as it is always created during initialisation and all we have to do is to use the static method getInstance. Next we retrieve the query part of the URL i.e. which should hopefully be something like id=45: $Q=$uri->getQuery(); The standard PHP parse_str method can be used to split the query into name value pairs. This creates and array indexed by the name and storing the value. That is, if the query string is id=45 then the array contains array['id'] set to 45 - it’s a very neat way of doing the job: parse_str($Q,$output); Now we can check that the URL is in tiny URL format and has an id=45 type name value pair: $id=$output['id']; You can, of course provide any error message that you think is suitable but I think it's best not to be too helpful unless you want users scanning your site by id number manually. <ASIN:1590599063> |
|||||
Last Updated ( Monday, 06 July 2009 ) |