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.
- Add the parameters to the URL after
?
:?param1=value1¶m2=value2
. You can usehttp_build_query()
to convert an associative array to URL query parameters. - Yes, just put
https:
in the URL. - 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
Problems with Secure Bind to Active Directory Using PHP
Upload File with PHP and Save Path to SQL
PHP Xpath - Find Element with a Value and Also Get Elements Before and After Element
How to Read the Query String in PHP and HTML
Selecting Rows Where a Field Is Null Using PHP Pdo Prepared Statements and MySQL
Model->Save() Not Working in Yii2
Google Recaptcha - Keep Getting 'Incorrect-Captcha-Sol'
Date Function to Display All Dates Between Two Dates
Differencebetween Crc32 and Crc32B
Where to Use MySQL_Real_Escape_String to Prevent SQL Injection
PHP - Hide Url (Get) Parameters
No Mail Received in Inbox with Xampp 1.8.0, Mercurymail and Mail()
Alternative to MySQLi_Fetch_All Needed