PHP 如何显示纯 URL

PHP how to display plain URL

本文关键字:URL 显示 何显示 PHP      更新时间:2023-09-26

我正在使用一些Javascript和PHP来获取浏览器视口,并根据访问者的浏览器/设备动态提供合适的布局。我的index.php文件是这样的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  $layoutWidth = $_GET['width'];
      if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
        require_once('layout1.php');
      } else {
         require_once('layout2.php');
      }
} else {
  echo "<script language='javascript'>'n";
  echo "  location.href='"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width='" + document.documentElement.clientWidth;'n";
  echo "</script>'n";
  exit();
}
?>
</body>
</html>

输出网址如下所示:

http://mydomain.com/index.php?&width=1600&height=812

我正在寻找一种使此URL看起来像的方法:

http://mydomain.com/

可以这样做吗?如果是,那又如何呢?

任何PHP或Plain JavaScript解决方案都可以

(请不要使用jQuery或MooTools或任何此类库,因为这是我整个网站中唯一的JavaScript函数,加载50到100 KB的库来完成这个小任务没有任何意义。

请帮忙

你应该能够使用 .htaccess 重写 URL(代码不包括常见的资源类型和索引.php循环):

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*'.png$ [NC]
RewriteCond %{REQUEST_URI} !.*'.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*'.css$ [NC]
RewriteCond %{REQUEST_URI} !.*'.gif$ [NC]
RewriteCond %{REQUEST_URI} !.*'.js$ [NC]
RewriteRule .* http://mydomain.com/

然后使用 $_SERVER["REQUEST_URI"] 访问实际请求的 URI,您可以从中解析高度和宽度值。例如

$height = 0;
$width = 0;
$requestParts = explode('?', $_SERVER['REQUEST_URI']);
$requestParts = explode('&', $requestParts['1']);
foreach ($requestParts as $requestPart) {
    $getVarParts = explode('=', $requestPart);
    if ($getVarParts['0'] == 'height') {
        $height = $getVarParts['1'];
    } else if ($getVarParts['0'] == 'width') {
        $width = $getVavParts['1'];
    }
}