开发者

Best way of forming url's automatically with PHP?

The question title is probably a bit misleading, but I can't think of a better way to phrase it.

To ensure a PHP app开发者_如何学编程lication will run on any number of environments (as far as hyperlinks are concerned...) what is the best way to create the URL's?

My index.php in the root of the application references a base.php (controller) file that handles all requests.

So I've been using:

$_SERVER['DOCUMENT_ROOT'] . "/url/to/file/i/want.php";

Is this the correct way to do it, or is there a better way? This works since every request originates from the index.php file...


That should work OK, or simply use relative paths.

You can also implement alternative approaches, for example you could have your hyperlinks as:

// this part could be established in a shared header/include/global variable for your scripts
$site_domain = 'http';
if ($_SERVER["HTTPS"] == "on") {$site[url][full] .= "s";}
$site_domain  .= "://";
$site_domain =$site_domain .$_SERVER['SERVER_NAME'];

// you would then have links in your scripts coded as: $site_domain."/cleanurl/

$site_domain gives you the base domain reference, dynamic to wherever the scripts are hosted, you can then make your links: $site_domain."/cleanurl/";

Where 'cleanurl' is a context based reference to the page you wish to load (e.g. 'news', as in www.mydomain.com/news/).

You can then use .htaccess and Apache mod_rewrite to handle where these URLs subsequently point:

RewriteEngine On
RewriteRule ^cleanurl/$ /url/to/file/i/want.php [NC,L]

Because relative paths are used from the root directory in .htaccess, once setup, you should never need to make changes.

Another bonus of this is you also end up with 'clean', 'readable' links - and if you move where scripts are located in relation to your file structure, you dont have to go though all scripts that link to them and edit the links individually- you only have to change a single line in your .htaccess.


I don't know if this is the right way either, but I tend to specify a $link_path and a $file_path in my code, I then use these for links on the page and includes/requires respectively.

This way I know that it will always work as I expect it to

$link_path = './';
$file_path = './';

// Show a link
echo '<a href="' . $link_path . 'my_file.php">Go to my_file.php</a>';

// Include a file
require_once($file_path . 'my_file.php');

This way it makes it flexible for me, especially if I'm using mod_rewrite to rewrite URLs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜