Best way to generate a URL automatically using PHP?

The title of the question is probably a little misleading, but I cannot think of a better way to phrase it.

To ensure that a PHP application runs in any number of environments (as far as hyperlinks are concerned ...), what is the best way to create a URL?

My index.php in the root of the application refers to the base.php (controller) file, which processes all requests.

So, I used:

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

Is this the right way to do this, or is there a better way? This works as each request comes from the index.php file ...

+4
source share
2 answers

This should work fine or just use relative paths.

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

 // 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 a link to the base domain, dynamic wherever the scripts are located, you can make your own links: $site_domain."/cleanurl/";

Where " cleanurl " is a link to the page you want to download (for example, "news", for example, at www.mydomain.com/news/).

You can then use .htaccess and Apache mod_rewrite for processing, where these URLs subsequently indicate:

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

Since relative paths are used from the root directory in .htaccess, you will not need to make any changes after installation.

Another advantage of this is that you also get “clean”, “readable” links - and if you go where the scripts are located relative to your file structure, you don’t have to go, although all the scripts that link to them, and edit the links separately - you only need to change one line in your .htaccess.

+2
source

I don’t know if this is correct either, but I prefer to specify $ link_path and $ file_path in my code, so I use them for links on the page and include / require accordingly.

That way, I know that it will always work, as I expect it to be

 $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 use mod_rewrite to rewrite URLs

0
source

All Articles