【问题标题】:How to run url in php script and get response?如何在 php 脚本中运行 url 并获得响应?
【发布时间】:2016-09-29 07:10:49
【问题描述】:

我有这样的记录,

-------------------------------------------------
id_detail  |        id_url          |  id_name  |
-------------------------------------------------
   43454   |  xyz.com/xxx/yyyy.jpg  |   yyyyy   |
   43674   |  xyz.com/zzzz/ddd.jpg  |   rrrr    |
   48884   |  xyz.com/aaaa/eee.jpg  |   mmmm    |
   ....
   ....
   49994   |  xyz.com/cccc/fff.jpg  |   uuuu    |
-------------------------------------------------

现在我需要在 while 循环中运行这个 url,如果图像加载,那么我必须将 respose 存储为 NO,如果 url 返回 404,那么我必须存储 YES。有人可以帮我吗?请告诉我如何在 php 或 curl 中获取运行 url 并获得响应。

对不起,如果我的问题是基本的,我试图在谷歌上得到一些想法,但在这里找不到这样的帖子。在此先感谢

【问题讨论】:

标签: php curl php-curl


【解决方案1】:

您可以使用 curl,并且由于您的情况,您必须使用 curl_setopt($ch, CURLOPT_HEADER, true); 获取 http 标头,如果您不需要图像,您可以防止使用 curl_setopt($ch, CURLOPT_NOBODY, true); 获取正文。设置此选项后,您会得到如下响应:

HTTP/1.1 200 OK Date: Thu, 29 Sep 2016 15:17:34 GMT Server: Apache Last-Modified: Sun, 15 Nov 2015 06:45:21 GMT Accept-Ranges: bytes Content-Length: 50822 Content-Type: image/png Age: 423 Expires: Wed, 05 Oct 2016 06:06:51 GMT 

如果状态码为 200,如上所示,则存在,但如果状态码 404,则不存在。

最后的代码是这样的:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"xyz.com/xxx/yyyy.jpg");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);
curl_close ($ch);
echo $server_output;

您必须读取 $server_output 的第一个字符('HTTP/1.1 200 OK' = 存在)或('HTTP/1.1 404 Not Found' = 不存在)

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 2011-07-17
    • 2014-07-30
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    相关资源
    最近更新 更多