如何解决PHP和htaccess |如果用户尝试直接访问url中的参数值,则重定向到“找不到页面”
我在我的网站上有一个友好的网址:
https://myexample.com/post/10/post-title
我正在尝试做一些拒绝用户直接在参数值中访问的操作。例如,如果用户尝试在上面的url中放置另一个id,则htaccess会将其重定向到404页面。
下面是我的htaccess代码,该代码将我的url获取参数转换为友好的url并像超级按钮一样工作:
RewriteEngine On
RewriteRule ^post/([^/]*)/([^/]*)$ /news?id=$1&title=$2 [L]
在这种情况下,如何改善htaccess的访问权限?
任何帮助,我都会感激。
解决方法
我找到了解决问题的方法,并且效果很好:
我的.htaccess:
RewriteEngine On
RewriteRule ^post/?(.*)/([^/]*)$ /news?id=$1&title=$2 [L]
首先,我实现了一个函数,用于替换news.php上 title 参数上的空格和特殊字符:
function sanitizeString($str) {
$str = preg_replace('/[áàãâä]/ui','a',$str);
$str = preg_replace('/[éèêë]/ui','e',$str);
$str = preg_replace('/[íìîï]/ui','i',$str);
$str = preg_replace('/[óòõôö]/ui','o',$str);
$str = preg_replace('/[úùûü]/ui','u',$str);
$str = preg_replace('/[ç]/ui','c',$str);
$str = preg_replace('/[^a-z0-9]/i','-',$str);
$str = preg_replace('/_+/',$str);
return $str;
}
然后我在news.php上创建了一个脚本,该脚本检查 id 和 title 参数在MySql上是否正确相关:
include 'connection.php';
$stmt = $db -> prepare('SELECT id,title FROM posts WHERE id = ?');
$id = $_GET['id'];
$stmt -> bind_param('i',$id);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($postID,$title);
$stmt -> fetch();
$stmt -> close();
$db -> close();
$postTitle = sanitizeString(trim(strtolower($title)));
if($_GET['id'] != $postID || $_GET['title'] != $postTitle){
header('location: /404.html');
exit();
}else{
echo 'Everything Fine';
}
基本上,根据上面的代码,如果用户尝试操纵URL中的参数,例如 id / 10 /和 title / post-title:
https://myexample.com/post/10/post-title
例如,脚本会将用户重定向到404错误页面或找不到页面或某些自定义页面。
如果有人有更好的方法可以改善这一点,请在此处告知。
希望这个问题可以帮助其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。