0

我正在使用 PHP/MySQL 使用动态 css (style.php) 来设置 Web 应用程序的样式。

MySQL 值由 URL 确定:

$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

if($url == "this") $style = "blue";
else( $style = "red"; )

我似乎遇到的问题是 style.php 使用:

header('Content-type: text/css');

这会导致 $url 等于:“http://”,同时忽略 style.php 文件之外分配的任何其他变量。

有谁知道如何让这些 $_SERVER (和其他)变量工作?

这是完整的代码

$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // current URL

$key = true;

while($key){

mysql_select_db($database, $connection);
$query_rsTheme = "
SELECT      s.name, s.url, t.name as theme, t.colour, t.hover 
FROM        db_site as s
INNER JOIN  db_theme.theme as t ON t.name = s.theme
WHERE       s.url = '$url'";
$rsTheme = mysql_query($query_rsTheme, $connection) or die(mysql_error());
$row_rsTheme = mysql_fetch_assoc($rsTheme);
$totalRows_rsTheme = mysql_num_rows($rsTheme);

if($totalRows_rsTheme == 1){ // sucessful match
    $key = false;

    $site = $row_rsTheme['name'];
    $theme = $row_rsTheme['theme'];
    $default_state = $row_rsTheme['colour'];
    $hover_state = $row_rsTheme['hover'];
}

$tokens = explode('/', $url);
$remove = $tokens[sizeof($tokens)-2]."/";
$url = substr($url, 0, strpos($url, $remove));
}

header('Content-type: text/css');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

$stylesheet = 'style.css';

$content = preg_replace('/\$([\w]+)/e','$0',@file_get_contents($stylesheet));

echo $content;
4

3 回答 3

1

您多次提到它$_SERVER是空的,但我怀疑您并没有真正测试它:

print_r($_SERVER);

不管怎样,您的style.php脚本假定存在某些全局变量(即$databaseand $connection)。如果你真的发布了完整的脚本,你永远不会定义它们。

您还提到:

在 style.php 文件之外分配的任何其他变量都将被忽略。

当然。这就是 PHP 的工作方式:每个脚本都是独立的。值得庆幸的是,style.php不会从在同一服务器上运行的任何其他随机脚本中选择变量。

我的建议是:

  1. 启用完整的错误报告。很明显,您没有看到通知以及可能的警告和错误。

  2. 单独测试脚本。http://example.com/include/version-3/css/style.php在浏览器中加载并查看生成的代码,而不是可能依赖于 HTML 中显示的样式。

于 2013-08-12T09:01:10.607 回答
0

我相信问题不是你所描述的。只要style.php是通过http访问的,那么$_SERVER变量就会被设置。

但是,您描述的代码中存在一些语法错误

if($url == "this") $style = "blue";
else( $style = "red"; )  // Incorrect syntax

正确的写法是:

if ($url == "this") { // $url will _never_ be "this"
    $style = "blue";
} else {
    $style = "red";
}

编辑:评估 MySQL 结果时有一些时髦的代码:

$row_rsTheme = mysql_fetch_assoc($rsTheme);
$totalRows_rsTheme = mysql_num_rows($rsTheme);

if($totalRows_rsTheme == 1){ // sucessful match, but ONLY if there's only one row
    ...
}

您应该将其替换为:

if($row_rsTheme = mysql_fetch_assoc($rsTheme)){ // sucessful match
    ...
}

这样,即使有多个结果,也会成功。

于 2013-08-12T08:39:11.723 回答
0

您可以检查 URI 是否与某些字符匹配

if (strpos($_SERVER['REQUEST_URI'], 'this') !== FALSE ){
    $style = "blue";
} else {
    $style = "red";
}

如果您使用的文件实际上是另一个文件的包含,这将特别有用。

于 2013-08-12T08:55:13.357 回答