How do I send a GET request with a header from PHP?

后端 未结 1 1159
轻奢々
轻奢々 2021-01-26 13:54

Call me out if this is a duplicate question, but this is starting to get ridiculous. I want to, with PHP:

 GET http://www.example.com/hello.xyz

相关标签:
1条回答
  • 2021-01-26 14:31

    You may use file_get_contents if you don't want to use curl but not sure about speed but it's php's built in function where curl is not. When talking about speed then I think whatever you use for a remote request, the speed/performance will depend on the network connection speed more than the function/library and maybe there is a bit different among these (curl/file_get_contents/fsockopen) but I think it'll be a very little (1-2 %) and you can't catch the difference, it'll seem almost same.

    $opts = array(
      'http'=>array(
          'method'=>"GET",
          'header'=>"X-Header-Name: $foobar"
    ));
    $context = stream_context_create($opts);
    $data = file_get_contents('http://www.example.com/hello.xyz', false, $context);
    f($data) {
        // do something with data
    }
    

    Also, if you want to use curl then you may use this

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Header-Name: $foobar"));
    curl_setopt($ch, CURLOPT_URL, "http://www.example.com/hello.xyz");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    if ($curl_errno == 0) {
        // $data received in $data
    }
    

    Also, check this answer, it may help you to decide.

    0 讨论(0)
提交回复
热议问题