View Full Version : PHP to find the current URL?

03-01-2007, 12:58 PM
I need a simple bit of code for the following.

I'm testing a site offline at http://localhost/sites/examplesite/index.php

This problem is that I have to use full URL's in every link, I can't just do <a href="page.php">Page</a>.

So there's a problem when I come to upload to the server since all the links will point to localhost.

I tried:

<a href="<?php $_SERVER['PHP_SELF']; ?>/index.php" >Home</a>

That code only finds the domain name and not the subfolders it's in. I don't know much PHP, but I need something simple like that if it's possible so that the links will work when I upload it.

03-01-2007, 01:37 PM
Why do you have to use full URLs?

03-01-2007, 01:44 PM
Probably because their include files and he's on a dev environment.

I usually have a global configuration file that I use to hold this type of info...

//more stuff...

Then in my code...

<a href="<?=SITE_PATH?>/index.php">Home</a>

03-01-2007, 01:51 PM
I use a switch in the config file so I only have to change a single var for the same result:

$config['env'] = 'local' // or test or live

// site root
switch ( $config['env'] ){

case 'live':
$config['root'] = 'http://www.someDomain.com.au/';
case 'test':
$config['root'] = 'http://test.server.net.au/~userName/';
case 'local':
$config['root'] = 'http://localhost/userName/public_html/';

03-01-2007, 02:29 PM
Thanks guys, those work :)

03-01-2007, 06:35 PM
Hey mate,

This is how I've solved that issue. Works well for me

// This function gets the current directory name and splits it up into an array seperated by the '/' character
function current_dir(){
$var_dirfind = explode('/', dirname($_SERVER['PHP_SELF']));
return($var_dirfind); // The return() statement immediately ends execution of the current function, and returns its argument as the value of the function call.
/* return end($var_dirfind); This statement immediately ends execution of the current function, and returns the LAST array value to the function call.

I use the return end() option to give me just the current file name. perhaps there's an easier method, I haven't found it yet though...

$dir_now = current_dir(); // and throw that array into a variable to call from later

// Then to call all or bits of that out you can do the following:

print_r ($dir_now); // shows the full array
echo $dir_now[1]; // shows the array [1] value

Have fun!

03-02-2007, 05:08 AM
another simple one is
<a href="<?php $_SERVER['REQUEST_URI']; ?>/index.php" >Home</a>
if u must have the full url