[英]php curl_exec() Connection refused when retrieving a remote image
我想用 php 檢索遠程托管圖像。 該圖像存在,我可以使用我的瀏覽器訪問它。 然而 curl_exec() 的結果是空的並且 curl_error() 說:
無法連接到 img107.xooimage.com 端口 80:連接被拒絕
這是我的代碼:
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$image = curl_exec($ch);
if( empty($image) ){
echo("Impossible to retrieve the file !<br>
error: ".curl_error($ch)."<br>");
}
如果我可以用我的瀏覽器打開圖像,那么為什么我使用 curl 時會拒絕連接?
備注:它適用於我自己域中的圖像,但不適用於示例中的外部圖像。
編輯:實際上似乎不是 php 問題,因為我什至無法執行 curl 或來自我網站的主機服務器的 ping:
curl http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png > image.png
Connection Refused
ping http://img107.xooimage.com
ping: unknown host http://img107.xooimage.com
ping http://www.google.com
ping: unknown host http://www.google.com
也許我的托管服務提供商應用了一些限制/防火牆。
閱讀前需要關閉 curl
$ch = curl_init('http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
$image = curl_exec($ch);
if (curl_errno($ch)) {
print_r(curl_error($ch));
die;
}
curl_close($ch);
return $image;
經過測試,以下確實將給定的圖像與腳本一起保存到文件image.png
中,並且是可讀的。 是不是缺少了什么?
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$image = curl_exec($ch);
var_dump($image); // Binary content
$save = fopen('image.png', 'w');
fwrite($save, $image);
fclose($save);
curl_close($ch);
這可能不是一個愉快的結論,最多是一種解決方法,但這是我最終所做的。
我從我的網站數據庫中導出了所有圖像 URL。 我基於此命令創建了一個 bash 腳本:
curl http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png > image.png
使用 curl 從 Internet 保存圖像。 我從我的個人計算機上運行腳本,它與我的網站主機沒有相同的限制。 我可以檢索所有的圖片。
如果您不管理主機上的權利/限制,您可能無法做更多事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.