我正在处理一个Symfony 2项目,我正在制作一个自定义约束来检查是否存在url。我四处查看,发现了这个:
如何通过PHP检查URL是否存在?
问题是,如果我尝试一个完全随机的地址,比如www.flskkhfkhsdf.com
,它会给我一个警告,并停止我的代码。还有别的办法吗?
警告:
警告:get_headers((:php_network_getaddresses:getaddrinfo失败:目前还不知道这样的宿主。
这是我的代码:
<?php
namespace AdminBundle'Validator'Constraints;
use Symfony'Component'Validator'Constraint;
use Symfony'Component'Validator'ConstraintValidator;
Class ContrainteUrlExistValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
$file_headers = get_headers($value);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation();
}
}
}
我不知道Symfony特定的解决方案,我会给你一些核心PHP函数。
gethostbyname就是你所需要的。在有效的主机名上,它将返回ip地址。对于不存在的主机名,它将返回未修改的主机名。
所以你可以做一些类似的事情
if (gethostbyname($hostname) == $hostname) {
$this->context->buildViolation...
}
当然,您必须从给定的URL中提取基本主机名,但您可以使用parse_URL:来实现这一点
$hostname = parse_url($url, PHP_URL_HOST)
当然,您必须首先验证URL,但您可以使用filter_var:进行验证
if ( ! filter_var($url, FILTER_VALIDATE_URL)) {
// URL not valid
}
EDIT:完整代码
完整的代码或多或少可以是这样的:
public function validate($value, Constraint $constraint)
{
if ( ! filter_var($value, FILTER_VALIDATE_URL)) {
$this->failValidation();
return;
}
$hostname = parse_url($value, PHP_URL_HOST);
if (empty($hostname)) {
$this->failValidation();
return;
}
if (gethostbyname($hostname) == $hostname) {
$this->failValidation();
return;
}
}
protected function failValidation($value, Constraint $constraint)
{
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation();
}
您可以使用任何HTTP客户端库,如Guzzle或Buzz来访问URL。如果出现任何错误,这些库将抛出异常。
使用HTTP方法"HEAD"来避免下载整个页面。
我找到了一个有效的解决方案:
<?php
namespace AdminBundle'Validator'Constraints;
use Symfony'Component'Validator'Constraint;
use Symfony'Component'Validator'ConstraintValidator;
Class ContrainteUrlExistValidator extends ConstraintValidator
{
public function validate($url, Constraint $constraint)
{
//Vérifie si l'url peut être vide
if(empty($url)&&$constraint->peutEtreVide)
{
return;
}
//Pattern pour trouver les url qui commence par http:// ou https://
$pattern='/^(https?:'/'/)/';
//Valide l'url et s'assure le preg_match a trouvé un match
if(filter_var($url, FILTER_VALIDATE_URL)&&!empty(preg_match($pattern, $url, $matches)))
{
//Trouve l'host
$hostname=parse_url($url, PHP_URL_HOST);
//Tente de trouver l'adresse IP de l'host
if (gethostbyname($hostname) !== $hostname)
{
//Cherche les données de l'entête
$headers=get_headers($url);
//Tente de trouver une erreur 404
if(!strpos($headers[0], '404'))
{
return;
}
}
}
//Crée une erreur
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $url)
->addViolation();
}
}