简体   繁体   中英

Using file_get_contents in php to send a GET request

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

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');

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM