Laravel 和共享主机 CURL 不工作

Laravel and shared hosting CURL not working

我正在将我的 Laravel 应用程序部署到 Godaddy 的共享主机,仅用于测试目的(以便我可以在域中共享它)用于生产我将使用更好的解决方案。

在我的本地主机中,一切正常,但在主机中 CURL 不工作。实际上,这个 CURL

function setUrl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, public_path().'/cookies/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, public_path().'/cookies/cookies.txt');
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
} 

这不起作用。当我在主机中检查我的 cookies.txt 文件时,它总是空的,实际上我尝试将它移动到 public,另一个文件夹和任何地方,但它没有得到编辑,它总是空的。它在我的本地主机上运行良好,但由于某种原因它不想在托管中运行。

有没有人知道如何解决这个问题?

如果有帮助,我是我的curinfo

"content_type" => null
  "http_code" => 0
  "header_size" => 0
  "request_size" => 0
  "filetime" => -1
  "ssl_verify_result" => 0
  "redirect_count" => 0
  "total_time" => 0.200232
  "namelookup_time" => 4.8E-5
  "connect_time" => 0.0
  "pretransfer_time" => 0.0
  "size_upload" => 0.0
  "size_download" => 0.0
  "speed_download" => 0.0
  "speed_upload" => 0.0
  "download_content_length" => -1.0
  "upload_content_length" => -1.0
  "starttransfer_time" => 0.0
  "redirect_time" => 0.0
  "redirect_url" => ""
  "primary_ip" => ""
  "certinfo" => []
  "primary_port" => 0
  "local_ip" => ""
  "local_port" => 0
]

很可能是您被 GoDaddy 防火墙阻止了。我在共享网络主机上无数次看到同样的内容。您可能应该投资 VPS(在 ramnode 上它们就像每月 3.5 美元......),但您也犯了一些错误,即您忽略了 curl_setopt 给出的任何错误,它 returns bool(false) 失败,你的代码完全忽略了。尝试改用这个:

function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' .  curl_errno ($ch) .' curl_error: '.curl_error($ch) );
    }
    return true;
}

但是,在调试 curl 时,您应该始终启用 CURLOPT_VERBOSE 并获取详细日志,这在调试 curl 代码时通常非常有用,例如

function setUrl($url) {
    $debugfileh=tmpfile();
    $ch = curl_init();
    try{
    ecurl_setopt($ch, CURLOPT_URL, $url);
    ecurl_setopt($ch, CURLOPT_VERBOSE, 1);
    ecurl_setopt($ch, CURLOPT_STDERR, $debugfileh);
    ecurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    ecurl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    ecurl_setopt($ch, CURLOPT_COOKIEJAR, public_path().'/cookies/cookies.txt');
    ecurl_setopt($ch, CURLOPT_COOKIEFILE, public_path().'/cookies/cookies.txt');
    $buffer = curl_exec($ch);
    return $buffer;
    }finally{
    var_dump('curl verbose log:',file_get_contents(stream_get_meta_data($debugfileh)['uri']));
    fclose($debugfileh);
    curl_close($ch);
    }
}