我試圖獲得用戶輸入的網站標題。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