如果有人在 URL 的末尾添加一个十六进制值,我想这样做,我可以向他们显示某个页面。
例如,假设我有colors.com,我想要它,所以如果有人想访问colors.com/FF0000,它会在页面上显示那个十六进制。是否可以从 URL 中获取并显示它,尽管我希望它只是十六进制值。
删除某些字母和特殊字符,这样别人就不能只使用文本。
希望这是有道理的。
您需要使用 Web 服务器的 URL 重写来匹配看起来像十六进制颜色(6 个字母 AF 和数字 0-9)的模式并进行相应的路由。
Apache mod_rewrite 示例以静默方式重写example.com/AA00FF
为example.com/index.php?color=AA00FF
:
RewriteEngine On
# [A-Fa-f0-9]{6} matches six letters A-F and digits 0-9.
RewriteRule ^([A-Fa-f0-9]{6})$ index.php?color=$1 [L]
在您的 PHP 脚本index.php
中,从$_GET['color']
. 您还需要在 PHP 中为该正则表达式验证它。否则,您将面临 XSS 攻击的风险:
// You MUST validate it in PHP as well, to avoid XSS attacks when you insert it into HTML
if (preg_match('/^[A-Z0-9]{6}$/i', $_GET['color'])) {
// ok to use
}
else {
// Invalid hex color value. Don't use it!
}
我并不是说这是一个好主意,但是要设置主体颜色,您可以这样做:
// Last warning: DON'T DO THIS UNLESS YOU HAVE VALIDATED WITH THE REGEX ABOVE!
echo "<body style='background-color: #{$_GET['color']}'>";
假设服务器将 URL 映射到您的脚本,您可以从$_SERVER['REQUEST_URI']
.
您可以使用简单的正则表达式确保它是十六进制 rgb 颜色。
有可能抓住它是的。这需要:
.htaccess 文件,类似这样的文件,位于 colors.com 的根文件夹中:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
包含以下内容的 index.php 文件:
// Get color from PATH_INFO in url.
$color = substr($_SERVER['PATH_INFO'], 1);
// If color is not a valid color hex code.
if(!preg_match('/^[a-fA-F0-9]{6}$/i', $color)){
die("NOT VALID");
}
echo $color; // Prints 00FFFF if url is color.com/00FFFF