我运行的是 Windows 7。其中,我运行 Virtualbox 和 Ubuntu。在 Ubuntu 中,我运行 Apache 并使用 PHP codeigniter。为了引用我们的 CSS 和 JS 文件,我们使用以下语法:
<?php echo site_url('css/styles.css'); ?>
在本地查看站点(在 Ubuntu VM 内)时,解析为:
http://localhost/styles.css
所以工作正常。
问题是当我从 Windows 7 中访问该网站时(用于 IE 测试)。要在 Windows 7 中访问该站点,我引用了 VM 的 IP 地址:
http://xx.x.x.x/
这会加载站点,但是,唉,所有 site_url 变量仍然被重写为“localhost”。上述文件显然不存在于我的 Windows 7 的本地主机上。
有没有办法解决这个问题,只需在我的 PHP 文件中硬编码相对链接?
最佳答案
这里有很多选项,从非常简单到疯狂复杂:
简单
$config['base_url'] = 'http://'. $_SERVER['HTTP_HOST'].'/';
这支持:
复杂
$config['base_url'] = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
$config['base_url'] .= '://'. $_SERVER['HTTP_HOST'];
$config['base_url']l .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
这支持:
- http://localhost/
- http://local.mysite:8080/
- http://sub.example.com/
- http://example.com/
- https://example.com/
- http://example.com/sub-directory
可能疯狂
这个非常相似,但可以保持你的 config.php 干净,在 HTTP_HOST 失败时提供后备,为你提供一个在整个站点中使用的常量,并且还可以为你提供从 Web 根目录到 BASEPATH 和 APPPATH 的相对 URI。
将其放入constants.php中:
/*
|--------------------------------------------------------------------------
| Docment root folders
|--------------------------------------------------------------------------
|
| These constants use existing location information to work out web root, etc.
|
*/
// Base URL (keeps this crazy sh*t out of the config.php
if(isset($_SERVER['HTTP_HOST']))
{
$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
$base_url .= '://'. $_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
// Base URI (It's different to base URL!)
$base_uri = parse_url($base_url, PHP_URL_PATH);
if(substr($base_uri, 0, 1) != '/') $base_uri = '/'.$base_uri;
if(substr($base_uri, -1, 1) != '/') $base_uri .= '/';
}
else
{
$base_url = 'http://localhost/';
$base_uri = '/';
}
// Define these values to be used later on
define('BASE_URL', $base_url);
define('BASE_URI', $base_uri);
define('APPPATH_URI', BASE_URI.APPPATH);
// We dont need these variables any more
unset($base_uri, $base_url);
在你的 config.php 中你可以简单地使用:
$config['base_url'] = BASE_URL;
这支持:
- http://localhost/
- http://local.mysite:8080/
- http://sub.example.com/
- http://example.com/
- https://example.com/
- http://example.com/sub-directory
(是的,这与复杂方法的列表相同)。
这应该让您的应用程序几乎可以在您放置的任何地方运行,但到目前为止它还不支持/~userdir URL。
关于php - 解析 php 中的 localhost,以便可以在虚拟机外部查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2550718/