从输入 url 过滤域

我需要在保存到数据库表之前检查输入值。


我有一个域,我想检查 url 字段中插入的链接。如果 url 使用列表验证中的域之一,则为 true 否则为 false。


前任。


$urls = array('domain.com','domain2.com','domain3.com');

在 url 字段中将放置链接 ex (domain2.com/priflie/1234 OR domain.com/profile/4321)


我试过这个,但没有用


if (in_array($url, $urls)) 

{

// error code here

 }


忽然笑
浏览 179回答 1
1回答

偶然的你

您需要从 URL 解析域。请参阅此答案以获取解释 - Parsing Domain From URL In PHP<?php$url = 'http://example.com/index.html';$parse = parse_url($url);$domain = $parse['host'];$domains = array('example.com','example2.com','example3.com');if (in_array($domain, $domains)) {&nbsp; &nbsp; ...}编辑- 不是 100% 确定这里的要求,但听起来你想要一个返回布尔值的函数。只需要检查 url 是否属于列表中的域。如果是,则写入数据库,否则返回错误/**&nbsp;* Returns a boolean indicating if the given URL is in a list of valid domains.&nbsp;* @param string $url&nbsp;* @return bool&nbsp;*/function validDomain($url){&nbsp; &nbsp; $parse = parse_url($url);&nbsp; &nbsp; $domain = $parse['host'];&nbsp; &nbsp; $validDomains = array('example.com', 'example2.com', 'example3.com');&nbsp; &nbsp; return in_array($domain, $validDomains);}if (validDomain('http://example.com/index.html')) {&nbsp; &nbsp; // Insert into DB.} else {&nbsp; &nbsp; // Handle your error.}
打开App,查看更多内容
随时随地看视频慕课网APP