我试图获得用户输入的网站标题。PHP - 从用户网站输入获取网站标题
文本输入:用户输入的网站链接通过AJAX发送到服务器。 用户可以输入任何东西:一个实际存在的链接,或只是一个字,或者很奇怪像“po392#* @ 8”
这是我的PHP脚本的部分:
// Make sure the url is on another host
if(substr($url, 0, 7) !== "http://" AND substr($url, 0, 8) !== "https://") {
$url = "http://".$url;
}
// Extra confirmation for security
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
// Make sure there is a dot in the url
if (strpos($url, '.') !== false) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
// Retrieve title if no title is entered
if($title == "" AND $urlIsValid == "1") {
function get_http_response_code($theURL) {
$headers = get_headers($theURL);
if($headers) {
return substr($headers[0], 9, 3);
} else {
return 'error';
}
}
if(get_http_response_code($url) != "200") {
$urlIsValid = "0";
} else {
$file = file_get_contents($url);
$res = preg_match("/<title>(.*)<\/title>/siU", $file, $title_matches);
if($res === 1) {
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
$title = addslashes($title);
}
// If title is still empty, make title the url
if($title == "") {
$title = $url;
}
}
}
但是,此脚本中仍然存在错误。
完全如果输入现有的网址为“https://www.youtube.com/watch?v=eB1HfI-nIRg”当一个不存在的页面输入为“https://www.youtube.com/watch?v=NON-EXISTING”,但它当用户进入类似“Twitter的行不通它工作。 com'(没有http)或类似'yikes'的东西。
我试图从字面上寄托都:卷曲的DomDocument ...
的问题是,在输入无效的链接时,Ajax调用永远不会完成(它使加载),而应该$ urlIsValid =“0”每当发生错误时。
我希望有人能帮助你 - 很感激。
弥敦道
对TRUE;返回FALSE什么? –
也许'preg_match'“尖叫”当'$ file'为'false'时,显示警告,(可能的)ajax响应不再是JSON,那么JS错误和加载不会再被停止? –
@PedroLobito我更喜欢在ajax调用中返回字符串,但是你可以只读'0'为假,'1'为真。我在学。 – Nathan