Grabbing HEX from URL - PHP


Grabbing HEX from URL - PHP

如果有人在URL末尾添加十六进制值,我可以向他们显示某个页面。

例如,假设我有colors.com,我会喜欢它,所以如果有人想访问colors.com/FF0000,它会在页面上显示十六进制。是否可以从URL中获取并显示它,尽管我希望它只是十六进制值。

删除某些字母和特殊字符,这样某人就不能只使用文本了。

希望这是有道理的。

您需要使用web服务器的URL重写来匹配看起来像十六进制颜色(6个字母A-F和数字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颜色。

可以用yes获取它。这需要:

.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