我已经构建了我的网站的URL,如Stack Overflow URL.我的网址如下.
http://www.example.com/1255544/this-is-the-url-text
在此URL中,1255544是id,而this-the-url-text是URL标题文本,两者都存储在数据库中.我注意到Stack Overflow URL在id的基础上工作.假设这是一个Stack Overflow URL
https://stackoverflow.com/questions/15679171/new-way-to-prevent-xss-attacks
在此URL中,15679171是帖子的ID.当我将此id更改为15706581而未触及new-way-prevent-prevent-xss-attacks并按Enter键时,URL会自动更改为以下URL:
https://stackoverflow.com/questions/15706581/simplecursoradapter-does-not-load- external-sqlite-database-id-error
https://stackoverflow.com/questions/15679171/new-way-to-preve
它会自动更正URL,如下所示:
https://stackoverflow.com/questions/15679171/new-way-to-prevent-xss-attacks
这意味着基于id 15679171从数据库中检索数据,并根据id附加相关的URL标题文本new-way-prevent-prevent-xss-attacks.
我也想这样做.但问题是,我不明白,如果有人更改了URL的ID,标题文本应该自动更改.我该怎么做呢?
我想到了以下几点:
$url_id = $_GET["id"]; $url_txt = $_GET["url_txt"]; $qry = "SELECT * FROM mytable WHERE url_id = '{$url_id}' LIMIT 1"; $data = MysqL_query($qry); $data_set = MysqL_fetch_array($data); if($url_txt== $data_set["url_txt"]) { // proceed further } else { $rebuilt_url = "http://www.example.com/" . $url_id . "/" . $data_set["url_txt"]; header("Location: {$rebuilt_url}") // Redirect to this URL }
你的代码看起来很不错,在我的Stack Overflow答案中,我也提出了类似的方法.但是,我建议只做一个小的改进.代替:
header("Location: {$rebuilt_url}");
你应该做:
header ('HTTP/1.1 301 Moved Permanently'); header("Location: {$rebuilt_url}");
这将使浏览器积极地缓存这些URL,并且每次都不会执行代码和SQL查询.
还检查:
> .htaccess if URL is bad do something
> .htaccess rewrite friendly URLs