duanran6441 2019-08-02 10:32
浏览 50

PHP Curl - 在下载之前检查来自URLA或B的响应

I'm looking to read a URL from one of two servers.

Using CURL I want to see if a URL exists and can be read form server A, if it available read the URL to a variable.

If it's not available from the same on URL b. If that is available read the URL to a variable..

If that isn't available set the variable to ''

This is what I have so far..

$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 );

Can some one advise how to do this ? Thanks

I've come up with a possible fix.

<?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;
    } 
}


?>
  • 写回答

1条回答 默认 最新

  • drwu24647 2019-08-02 10:41
    关注

    May it will help you:

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

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致