使用PHP自动形成url的最佳方法?

时间:2011-10-07 08:22:04

标签: php

问题标题可能有点误导,但我想不出更好的方式来表达它。

确保PHP应用程序可以在任意数量的环境中运行(就超链接而言......)创建URL的最佳方法是什么?

我在应用程序根目录中的index.php引用了一个处理所有请求的base.php(控制器)文件。

所以我一直在使用:

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

这是正确的方法,还是有更好的方法?这是有效的,因为每个请求都来自index.php文件......

2 个答案:

答案 0 :(得分:2)

这应该可行,或者只是使用相对路径。

您还可以实施其他方法,例如,您可以将超链接设为:

// 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为您提供基本域引用,动态到托管脚本的任何位置,然后您可以创建链接:$site_domain."/cleanurl/";

cleanurl”是指您要加载的网页的基于上下文的引用(例如“新闻”,如www.mydomain.com/news /)。

然后,您可以使用.htaccess和Apache mod_rewrite来处理这些URL随后指向的位置:

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

因为相对路径是从.htaccess中的根目录使用的,所以一旦设置,您就不需要进行更改。

另一个好处是你最终会得到“干净”,“可读”的链接 - 如果你移动脚本与文件结构相关的位置,你就不必去寻找链接到它们的所有脚本单独编辑链接 - 您只需更改.htaccess中的一行。

答案 1 :(得分:0)

我不知道这是否也是正确的方法,但我倾向于在我的代码中指定$ link_path和$ file_path,然后我将这些用于页面上的链接并分别包含/ require。

通过这种方式,我知道它总会像我期望的那样工作

$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');

这样它对我来说很灵活,特别是如果我使用mod_rewrite来重写URL

相关问题