Get Request from PHP Using File_Get_Contents with Parameters

GET Request from PHP using file_get_contents with parameters

The content option is used with POST and PUT requests. For GET you can just append it as a query string:

file_get_contents('http://example.com/send.php?'.$getdata, false, $context);

Furthermore, the method defaults to GET so you don't even need to set options, nor create a stream context. So, for this particular situation, you could simply call file_get_contents with the first parameter if you wish.

Using file_get_contents in php to send a GET request

Yes.

  1. Add the parameters to the URL after ?: ?param1=value1¶m2=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');

PHP file_get_contents with var params fails

You do not pass variables but use string now.

Try expand the variables and concatenate to string

$phoneNumber= file_get_contents("https://page.company.test/?app=".$appid."&affiliateid=".$affiliatep."&laNG=en&country=".$countryp."&sav=".$savactive)

See more convinient way with all options in array: GET Request from PHP using file_get_contents with parameters

How to post data in PHP using file_get_contents?

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);

$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...



Related Topics



Leave a reply



Submit