[英]Using parse_url in php, how do we check whether input is a url or just a string
Here's my code 这是我的代码
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="text"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$url = $_POST['text'];
$parse = parse_url($url);
echo $parse['host'];
}
?>
I am using parse_url to get the host name to be outputted when somebody inputs the url, now if I try to enter some garbage input, it gives an error: "Undefined index: host" , I want to know how do we check whether its a valid url or just a string before echoing the output of parse_url function 我正在使用parse_url来获取有人输入URL时要输出的主机名,现在,如果我尝试输入一些垃圾输入,则会出现错误:“ Undefined index:host”,我想知道我们如何检查其名称一个有效的URL或只是一个字符串,然后回显parse_url函数的输出
You can check to see if host is defined: 您可以检查是否定义了主机:
echo isset($parse['host']) ? $parse['host'] : 'Invalid input';
Or, you can create a regex to check to see if the string you're passing to parse_url is correctly formatted. 或者,您可以创建一个正则表达式来检查传递给parse_url的字符串的格式是否正确。 This is a bit harder, but can be done. 这有点困难,但是可以做到。 See: Parse URL with Regex using PHP or PHP url validation + detection 请参阅: 使用PHP或PHP URL验证+检测 使用Regex解析URL
Use Regular Expression 使用正则表达式
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="text"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
$url = $_POST['text'];
define('REGEX_URL','/http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/');
if(preg_match(REGEX_URL, $url, $url)) {
echo "<a href=\"{$url[0]}\">{$url[0]}</a>";
} else {
echo "<p>No Match Found</p>";
}
}
?>
parse_url() will return false if the variable could not be parsed as url. 如果无法将变量解析为url,则parse_url()将返回false。 Checking the parse_url() result for !== false would let you know that the string has been successfully parsed by the function and thus is a valid url. 如果检查parse_url()结果是否为!== false,则会使您知道该字符串已被函数成功解析,因此是有效的url。
$parse = parse_url($url);
if($parse !== false)
{
echo 'valid url';
if(isset($parse['host'])) echo $parse['host'];
}
After that, it's up to you to figure out what exactly you mean with "valid url". 之后,由您自己确定“有效网址”的确切含义。 PHP's parse_url function will be able to parse a string that's nothing more than eg just a path. PHP的parse_url函数将能够解析仅是路径的字符串。 Depending upon your given problem/context, you may feel that a "valid url" consists out of at least scheme+host, or in a different context, only a relative path (without host) might also be valid. 根据给定的问题/上下文,您可能会认为“有效url”至少由scheme + host组成,或者在不同的上下文中,只有相对路径(无主机)也可能有效。 Adding those checks in yourself - just checking if the key is present in the parsed array - could look like: 将这些检查添加到您自己中-仅检查键是否存在于已解析的数组中-可能类似于:
$parse = parse_url($url);
if($parse !== false)
{
if(isset($parse['scheme']) && isset($parse['host']))
{
echo 'valid url';
echo $parse['host'];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.