Home > other >  Using file_get_contents in php to send a GET request
Using file_get_contents in php to send a GET request

Time:09-08

can I use file_get_contents to send an http request to my host with GET parameters? If yes, I have other 3 questions: Firstly, how? Can I use https instead of http? Can I send them to another host (an external one)? Thx in advance, pls don't blame me if it is stupid

CodePudding user response:

Yes.

  1. Add the parameters to the URL after ?: ?param1=value1&param2=value2. You can use http_build_query() to convert an associative array to URL query parameters.
  2. Yes, just put https: in the URL.
  3. Yes, you can send to any URL.
$result = file_get_contents('https://www.google.com/search?q=words to search for');

CodePudding user response:

file_get_contents is a stream fonction, so you can create a stream context and pass it to this function :

$context = stream_context_create( 
array( 'https' => // or any other protocol
 array( 
 'method' => 'GET', // or post ..
 // any other params you need
)
)
$response = file_get_contents('https://my-api.com/users' . http_build_query($params), false, $context);
  • Related