簡體   English   中英

PHP Curl-下載前檢查URLA或B的響應

[英]PHP Curl - check for response from URLA or B before downloading

我正在尋找從兩個服務器之一讀取URL。

使用CURL,我想查看URL是否存在,並且可以從服務器A讀取,如果可用,則將URL讀取到變量。

如果無法通過URL b上的相同名稱獲得。 如果可用,則將URL讀取到變量。

如果不可用,請將變量設置為“

這是我到目前為止所擁有的..

$url='http://test.com/ip.php';
$urltwo='http://example.com/ip.php';

$ch = curl_init($url);
$timeout=1;

curl_setopt($ch, CURLOPT_NOBODY, true);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == '200') {
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
}


var_dump( $output );

有人可以建議這樣做嗎? 謝謝

我想出了一個可能的解決方法。

<?php

$ip = '';
$server = checkURL('http://servera.com/ip.php');
if ($server)  {
    $ip = $server;
} else {
    $server = checkURL('http://serverbcom/ip.php');
    if ($server) $ip = $server;
}



function checkURL($url) {
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $ch = curl_init($url);
    $data = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpCode == '200') {
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        return $output;
    } 
}


?>

可能會幫助您:

$file_headers = @get_headers($ch);
if(!$file_headers || strpos($headers[0], '404 Not Found'))
    $exists = false;
else $exists = true;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM