I am trying to pass a json data as param for cURL POST. However, I am stuck at grabbing it and saving it on db.
cURL file:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl
test_curl file:
$order_info = $_POST; // this seems to not returning anything
//SAVE TO DB... saving empty...
What did I miss? Weew....
You are sending the data as raw JSON in the body, it will not populate the $_POST variable.
You need to do one of two things:
You can change the content type to one that will populate the $_POST array
You can read the raw body data.
I would recommend option two if you have control over both ends of the communication, as it will keep the request body size to a minimum and save bandwidth over time. (Edit: I didn't really emphasize here that the amount of bandwidth it will save is negligible, only a few bytes per request, this would only be a valid concern is very high traffic environments. However I still recommend option two because it is the cleanest way)
In your test_curl file, do this:
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
$postedJson = json_decode($rawData);
var_dump($postedJson);
If you want to populate the $_POST variable, you will need to change the way you send the data to the server:
$data = array (
'name' => 'Hagrid',
'age' => '36'
);
$bodyData = array (
'json' => json_encode($data)
);
$bodyStr = http_build_query($bodyData);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($bodyStr)
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);
$result = curl_exec($ch);
The raw, undecoded JSON will now be available in $_POST['json'].
Use following php function for posting data using php curl function in x-www-form-urlencoded format.
<?php
$bodyData = http_build_query($data); //for x-www-form-urlencoded
?>
Related
I'm trying to get the data from pull service in PHP while i"m calling the end point in postman I'm getting the output
but while I'm trying to call using PHP I'm getting the 500
i have attaching the PHP code please guide me where I'm doing wrong
//API Url
$url = 'https://abc.xyz/vlet?Info=';
//The JSON data.
$jsonData =
array(
'NAME' => 'anish',
'Key' => 'vQOgCmDgxxdw',
'authToken' => 'xswSgsG8Dtz05Rfhfzr83t25',
'work_date' => '2020-07-07'
);
//print_r( $jsonData); exit;
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
$full_url = $url.$jsonDataEncoded ;
//echo $full_url ;
$result1 = file_get_contents($full_url);
print_r( $result1);
//Initiate cURL.
$curl = curl_init();
$ch = curl_setopt($curl, CURLOPT_URL, $full_url);
//$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
print_r($result);
My CSV has a single column with 40000 phone numbers
The following code read the CSV column and is fast
$dataArray = csvstring_to_array( file_get_contents('test.csv'));
My CURL code looks like this
$ch = curl_init();
$data = http_build_query($dataArray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataArray);
curl_setopt($ch, CURLOPT_URL, "https://api.theblacklist.click/standard/api/v1/bulkLookup/key/[APIKEY]/response/json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
The JSON parameters expected by the API look like the following. I am stuck about how to pass the "phones":[ and then pass the CSV Data array as a parameter to the curl/API?
curl -XGET ''
-H 'Content-Type: application/json'
-d'
{
"phones":[
"15555558353",
"15555555555",
"15555552740",
"15555552741",
"15555552738"
]
}'
It seems the API server expect JSON-formatted data to be passed as POST body
$dataArray = csvstring_to_array(file_get_contents('test.csv'));
$jsonString = json_encode(['phones' => array_values($dataArray)]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
everyone, i am requesting data from some other website but I am unable to request through curl it shows error 500 but when I do the same request through chrome RESTED extension it shows me output
$url = "XXXXXXXXXXX";
// what post fields?
$fields = array(
'roll_number' => '123456',
'full_name' => 'aaaaaa',
'mother_name' => 'bbbbbbb',
'_token' => 'xxxxxxxxxxxxxxxx'
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Request should be by post method and data should be JSON encoded or URL encoded I have tried both but none of them worked
Not sure if this is the cause, but shouldn't your HTTPHEADER be application/json? Also, you're not encoding the data as JSON - you might need to change $postvars = http_build_query($fields); to $postvars = json_encode($fields);
I'd also take a look at https://lornajane.net/posts/2011/posting-json-data-with-php-curl
I have created a file on bluehost server test.php and used this file send curl request from another server ( godaddy ).
$url = 'http://dev.testserver.com/test.php';
$data_string = json_encode($fields);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS,$data_string );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
How to capture posted data on test.php and process it ?
I am trying with $_POST but its showing blank.
The question is close to this one How to send raw POST data with cURL? (PHP)
I've slightly modified your client code to follow recommendations:
<?php
$fields = ['a' => 'aaaa', 'b' => 'bbbb'];
$url = 'http://localhost/test.php';
$data_string = json_encode($fields);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, urlencode($data_string));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$curl_response = curl_exec($curl);
echo 'Response: '.$curl_response.PHP_EOL;
I do urlencode for the sent data and set headers.
The logic how to read data is explained in the question How to get body of a POST in php? I made a simple test.php file with the following code
<?php
$body = file_get_contents('php://input');
if (!empty($body)) {
$data = json_decode(urldecode($body), true);
var_export($data);
}
We read the data, decode it and parse JSON.
As one might expect the test output from the client script is the following
$ php client.php
Response: array (
'a' => 'aaaa',
'b' => 'bbbb',
)
Try to replace this, direct send array not json
curl_setopt($curl, CURLOPT_POSTFIELDS,$data_string );
With
curl_setopt($curl, CURLOPT_POSTFIELDS,$fields );
Check this : http://php.net/manual/en/function.curl-setopt.php
This question already has answers here:
How to properly send and receive XML using curl?
(2 answers)
Closed 9 years ago.
I have fetched data from server using this code, `$server = 'LOCALHOST:9000';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}`
Now I have to do reverse, how to send the data into server using php? curl method is the only way or is there any other method to do the same. Give me some example.
Sending/Receiving using cURL is the exact same thing. cURL is based on sending data to an given URL and possibly receiving a response. Let's take a simple example of getting a user and sending a user.
Getting a user would be
$data = array(
'user_id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/getUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
getUser.php does nothing more than search for a user and return the data found.
$response would possibly contain data of the user, perhaps just a text-response containing the name. A serialized PHP array, an XML response with a full user profile.. etc.
Inserting/Sending data
$data = array(
'user_name' => 'Joshua',
'user_email' => 'my#email.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/addUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
addUser.php performs some validation of the fields and if validated inserts a user in the database
$response in this case does not contain the userdata (however: it's a possibility), but more likely the $response contains a result. An ok textresponse, a json/xml response or perhaps a '200 OK' header response
It's all basically the same. There is no difference in getting/sending data using cURL. It's all based on sending a request and in most cases do something with the outcome.