我正在使用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;
您多次提到$_SERVER
是空的,但我怀疑您并没有真正测试它:
print_r($_SERVER);
不管怎样,style.php
脚本都假设存在某些全局变量(即$database
和$connection
)。如果你真的发布了完整的脚本,你永远不会定义它们。
您还提到:
将忽略在style.php文件之外分配的任何其他变量。
当然。PHP就是这样工作的:每个脚本都是独立的。值得庆幸的是,style.php
不会从运行在同一服务器上的任何其他随机脚本中挑选变量。
我的建议是:
启用完整错误报告。很明显,您没有看到通知,可能还有警告和错误。
单独测试脚本。在浏览器中加载
http://example.com/include/version-3/css/style.php
并查看生成的代码,而不可能依赖于HTML中显示的样式。
您可以检查URI是否与某些字符匹配
if (strpos($_SERVER['REQUEST_URI'], 'this') !== FALSE ){
$style = "blue";
} else {
$style = "red";
}
如果您正在使用的文件实际上是另一个文件中的include,那么这将特别有用。
我相信问题不是你所描述的。只要通过http访问style.php
,就会设置$_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
...
}
这样,即使有不止一个结果,也会有成功。