2012-04-30 29 views
1

我正在使用一些Javascript和PHP來獲取瀏覽器視口並根據訪問者的瀏覽器/設備動態地提供合適的佈局。我index.php文件是這樣的:PHP如何顯示普通URL

<!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或純JavaScript解決方案會做

(沒有的jQuery或MooTools的或任何這樣的庫討好,因爲這是在我的整個網站只有JavaScript函數,它不會作出任何意義,裝載50至100圖書館的KB剛剛完成這項任務小)

請幫

+0

您的腳本不會導致無限循環嗎?編輯:不,它不! :) – Amberlamps

+0

曾聽說過[媒體查詢](http://www.css3.info/preview/media-queries/)? – kapa

+0

如果您想查看哪種訪問者正在查看您的頁面,可以查看[wurfl](http://wurfl.sourceforge.net/)。 – Zombaya

回答

0

您應該能夠使用的.htaccess重寫URL(代碼不包括公共資源的類型和循環的index.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']; 
    } 
} 
+0

請參閱編輯,擴展我的答案 – Ing