Last active
February 4, 2019 16:29
-
-
Save LB-Digital/4c7c5a83f38de9b9ee879959a89cef8a to your computer and use it in GitHub Desktop.
Sending URL requests (POST/GET) in PHP using curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$url = 'https://example.com/api.json'; | |
$fields = array( | |
'key1'=>urlencode('value 1'), | |
'key2'=>urlencode('value 2'), | |
'key3'=>urlencode('value 3') | |
); | |
//url-ify the data for the POST | |
$fields_string = ""; | |
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } | |
rtrim($fields_string, '&'); | |
//open connection | |
$ch = curl_init(); | |
//set the url, number of POST vars, POST data | |
curl_setopt($ch,CURLOPT_URL, $url); | |
curl_setopt($ch,CURLOPT_POST, count($fields)); | |
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); | |
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); // stop return output | |
//execute post | |
$result = curl_exec($ch); | |
//close connection | |
curl_close($ch); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment