【发布时间】:2017-10-01 09:13:33
【问题描述】:
我正在尝试获取属于关联区域的干净 URL,其中干净的 url 函数应用于 $_GET 变量。我有两页,第一页是 District.php,它具有指向相关地区的链接,使用此功能生成干净的 URL。以下是 District.php 页面的代码:-
<?php
$remove[] = " ";
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
$string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
return $string;
}
include($_SERVER['DOCUMENT_ROOT'].'/database-path.php');
$district = str_replace('-',' ',$_GET['district']);
$state = str_replace('-',' ',$_GET['state']);
$sql="SELECT * FROM table_name WHERE district='$district' AND state='$state'";
$result = mysqli_query($con,$sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$district = $row['district'];
$locality = $row['locality'];
$state = $row['state'];
$iso = $row['iso'];
}
?>
在同一地区页面上,以下代码用于生成相关地区的干净 URL:-
<a href=\"/".str_replace($remove, "-", clean(strtolower($row['locality'])))."-".$row['id']."\">" . $row["locality"]. "</a>
上面的代码在地区页面上以“locality-page-url-with-decoded-id-number”的方式生成所有地区页面的URL。
下面是 locality.php 的代码,我在其中尝试将相同的干净函数应用于 $_GET 变量以获得干净的 URL
<?php
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
$string = preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
return $string;
}
include($_SERVER['DOCUMENT_ROOT'].'/database-path.php');
$locality = clean($_GET['locality']);
$localID = base64_decode($_GET['id']) ;
$sql="SELECT * FROM table_name WHERE locality='$locality' AND id='$localID'";
$result = mysqli_query($con,$sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$locality = $row['locality'];
$content = $row['content'];
$district = $row['district'];
$state = $row['state'];
$iso = $row['fld_iso'];
}
}
?>
htacces 代码:-
RewriteRule ^([^/]*)-([^/]*)$ locality.php?locality=$1&id=$2 [L]
现在我面临的问题是 $locality = clean($_GET['locality']); 在这里不起作用并返回错误 404。它没有得到清除的位置值。当我使用字段中可用的所有字符从 $_GET 变量中删除 clean 函数后手动尝试相同的操作时,它工作正常。有什么方法可以使用 ID 作为主要变量,以便在页面的 URL 中获取具有位置的干净值的行值?
【问题讨论】:
-
你能提供一个你试图让它工作的示例网址吗?
-
@vnt 在地区页面上生成的示例 URL 是:-
http://domainname.com/text-text-text-Mjk2这是一个干净的 URL。相同的未清理版本是:-http://domainname.com/text.-&-text-text-Mjk2 -
-
我从您的代码中看不到任何问题,除了 .htaccess。正如你所说,它应该是
RewriteRule ^([^/]*)-([^/]*)$ locality.php?locality=$1&id=$2 [L],第二个文件是locality.php -
@vnt 对不起,我在问这个问题时很抱歉。文件名已经是 htaccess 中的 locality.php 并且它不起作用。这就是为什么在从位置页面删除 clean 功能后,未清理版本的 URL 可以正常工作的原因。我会解决这个问题。感谢您指出这一点。