Send GET request with PHP.

This is a beginner’s tutorial on how to send a simple HTTP GET request with PHP. To send GET requests via PHP, there are two different ways to go about doing it.

file_get_contents

The first method involves using the function file_get_contents. This easy-to-use function has been present since PHP version 4.3.0 and its purpose is to “read an entire file into a string.” In this case, the file in question is a URL that we will be accessing via GET. Take a look at the following sample code:

When supplied with a URL, file_get_contents will retrieve the contents of the URL using a HTTP GET request.

If you need to attach a query string / GET parameters, then you can simply add them onto the end of the URL like so:

In the code above, I set the query string parameters id and name.

Unfortunately, the drawback of using file_get_contents is that you can’t retrieve HTTP response codes and error handling is extremely basic.

cURL

To retrieve HTTP response codes and other header information, you can use the cURL library. By default, cURL uses GET requests:

In the code above, we:

  1. Initialized cURL using the curl_init function.
  2. We set the URL that we wanted to GET using the CURLOPT_URL parameter.
  3. We set the CURLOPT_RETURNTRANSFER option to true so that the contents of the URL isn’t automatically printed out onto the page (instead, it is returned as a string by the curl_exec function).
  4. We set the CURLOPT_FOLLOWLOCATION to true because we want to follow any redirects that the site tells us to follow. If you want to ignore header redirects, then simply remove the line in question or set the option to false.
  5. We executed the GET request using curl_exec.
  6. We closed our cURL handle.
  7. Finally, we printed the contents of the URL out onto the page.

cURL is the best option to use if you want more control over your HTTP requests. Not only does it have better error handling, it also allows you to use cookies, set referrer information and set custom user agents, etc.

Comments

comments