那好吧。出于学习安全性的目的,我将使用一些示例代码编写此答案,以便您知道将来如何安全地做这类事情。
首先,让我们写一个小表格:
<form method="POST" action="your_php_file.php" accept-charset="utf-8">
<input type="url" name="company_website" id="company_website" value="" />
<input type="submit" value="Update website" />
</form>
现在让我们开始基于此编写我们的 PHP 文件。首先,我们需要确保用户提交的是新数据而不是空字符串:
if(isset($_POST['company_website']) && !empty($_POST['company_website'])){
接下来我们将编写一个检查字符串是否为网站的函数:
function isWebsite($url){
要查看字符串是否与网站匹配,我们将使用正则表达式。正则表达式可能非常复杂,所以在这个答案的最后,我会发布一个链接来了解更多关于它们的信息。
$pattern = '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';
现在让我们编写一个简单的 if 语句,它返回 true 或 false。为简单起见,此语句将变量$url(包含用户数据)与上述$pattern 中的正则表达式模式进行比较。如果$url 包含有效的网站,它将返回 true,否则返回 false。
if(preg_match($pattern, $url)){
return true;
} else {
return false;
}
}
接下来我们将编写一个函数,在用户发送的数据前添加“http://”:
function addHttp($url){
$url = "http://". $url;
return $url;
}
现在我们的功能已经完成,我们要做的就是使用它们。首先我们会检查用户是否已经发送了一个有效的网站:
if(isWebsite($_POST['company_website'])){
//The website is valid, so you can safely add it your database here
} else {
//The website is not valid, but the user might simply have forgotten
//to add http:// in front of it. So lets do it for him:
$website = addHttp($_POST['company_website']);
//Still we can't be sure if it's a valid website. It might be a string
//that will try to mess with your database. So lets verify it again:
if(isWebsite($website)){
//The website is now valid, so you can safely add it your database here
} else {
//The website is still not valid, so we need to return an error
//to your user:
echo "It seems you didn't enter a valid website. Please try again!";
exit;
}
}
}
您可能已经注意到,我们的代码中有两个地方需要编写相同的代码来插入数据库中的所有内容。您也可以为此使用函数:
function addToDatabase($url){
//Write your code to add everything to database here. $url will contain the website
}
所以完整的代码如下:
<?php
if(isset($_POST['company_website']) && !empty($_POST['company_website'])){
function isWebsite($url){
$pattern = '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';
if(preg_match($pattern, $url)){
return true;
} else {
return false;
}
}
function addHttp($url){
$url = "http://". $url;
return $url;
}
function addToDatabase($url){
//Write your code to add everything to database here. $url will contain the website
}
if(isWebsite($_POST['company_website'])){
addToDatabase($_POST['company_website']);
} else {
//The website is not valid, try adding 'http://'
$website = addHttp($_POST['company_website']);
if(isWebsite($website)){
addToDatabase($website);
} else {
//The website is still not valid, return error
echo "It seems you didn't enter a valid website. Please try again!";
exit;
}
}
}
?>
我应该补充一点,只是盲目地将网站添加到您的数据库中可能仍然不安全。为了使其绝对安全,您需要将PDO() 或MySQLi() 与Prepared Statements 结合使用。但是在这个答案中解释这一点会将其变成一本书。所以一定要了解它!
最后,我承诺提供一个资源来了解更多关于正则表达式的信息。最好和最安全的资源来自 PHP 官方网站本身。你可以在这里找到它:PHP: Pattern Syntax