A TinyURL PHP page
Written by Harry Fairhead   
Sunday, 05 July 2009
Article Index
A TinyURL PHP page
Joomla
Tiny URL PHP
Building the new URL

Getting the current URL in PHP

The 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
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );
define( 'DS', DIRECTORY_SEPARATOR );
if (file_exists( JPATH_BASE . DS .
'configuration.php' ) &&
(filesize( JPATH_BASE . DS .
'configuration.php' ) > 10) &&
file_exists( JPATH_BASE . DS .
'index.php' ))
{
if (file_exists( JPATH_BASE . DS .
 'installation'))
{
$cmd = 'mv '. JPATH_BASE .
DS . 'installation '.
 JPATH_BASE . DS .
'installation-old';
system("$cmd", $out);
}
}
require_once ( JPATH_BASE .DS.
'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.
'includes'.DS.'framework.php' );
JDEBUG ? $_PROFILER->
mark( 'afterLoad' ): null;
$mainframe =
& JFactory::getApplication('site');
$mainframe->initialise();

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'];
if(!is_numeric($id)) exit('URL not valid');

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 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.