How to make a request to a web page with PHP?

后端 未结 5 1241
感动是毒
感动是毒 2021-01-21 06:57

What i\'m trying to achieve is this:

1st- I want to query a page like google but without filling it\'s search filed manually 2nd- I want to get the result and save it to

5条回答
  •  不知归路
    2021-01-21 07:22

    You should use cURL to do so, not only because it is way faster than file_get_contents, but also because it has many more features. Another reason to use it is that, as Xeoncross correctly mentioned in the comments, file_get_contents may be disabled by your webhost for security reasons.

    A basic example would be this one:

    $curl_handle = curl_init();
    curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
    curl_exec( $curl_handle ); // Execute the request
    curl_close( $curl_handle );
    

    If you need the return data from the request, you need to specify the CURLOPT_RETURNTRANSFER option:

    $curl_handle = curl_init();
    curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
    curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true ); // Fetch the contents too
    $html = curl_exec( $curl_handle ); // Execute the request
    curl_close( $curl_handle );
    

    There are tons of cURL options, for example, you can set a request timeout:

    curl_setopt( $curl_handle, CURLOPT_CONNECTTIMEOUT, 2 ); // 2 second timeout
    

    For a reference of all options see the curl_setopt() reference.

提交回复
热议问题