php curl 與 file_get_contents

最後更新: 2024-03-05

目錄


Curl

 

Simple

<?php
  // return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close()
  $ch = curl_init();

  // 設定擷取的URL網址
  curl_setopt($ch, CURLOPT_URL, "https://datahunter.org/");

  // 執行
  curl_exec($ch);

  // 關閉CURL連線
  curl_close($ch)
?>

Complex

<?php
    $url = "https://x.x.x";
    
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3); //times out after 4s
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
    curl_setopt($ch, CURLOPT_POST, 1);
    
    echo "START : $url<br>\n";
    $result=curl_exec ($ch);
    $errno = curl_errno($ch);
    $errstr = curl_error($ch);
    echo "ErrNo: $errno $errstr<br>";
    echo "END<br>\n";
    
    curl_close ($ch);
    echo "result='".nl2br(htmlspecialchars($result))."'";
?>

CURLOPT_HEADER     TRUE to include the header in the output.

 


file_get_contents

 

Simple

<?php
  echo file_get_contents("https://datahunter.org");
?>

* 它的 timeout 由 php.ini 的 default_socket_timeout 設定, Default 是 60.
   如果速度係 1MByte, 那只能下載到 60 MB

Complex

<?php
  $arrContextOptions=array(
    "ssl"=>array(
        "cafile" => "/etc/pki/tls/cert.pem",
        "verify_peer"=> true,
        "verify_peer_name"=> true,
    ),
  );
  echo file_get_contents("https://datahunter.org", 
                          FALSE, 
                          stream_context_create($arrContextOptions) );
?>

 * allow_self_signed boolean

 


 

 

 

Creative Commons license icon Creative Commons license icon