unpack data sent using POST CURL - php

I am trying to receive the data being posted using the curl commands. Data is URLify in order to build http query. The commands for data being sent using curl are :
$data=array(
'product_name' =>'Television',
'price' => 1000,
'quantity' => 10,
'seller' =>'XYZ Traders'
);
$DT=http_build_query($data);
echo($DT);
$url = 'http://localhost/API2/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$DT);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
echo $response_json;
curl_close($ch);
Now how to unpack the values being sent using curl build query. I am trying to get the values sent from curl like this but i don't get the values posted rather it gives me 1's and zero's:
$_product_name=$_POST["product_name"];
$_price=$_POST["price"];
$_quantity=$_POST["quantity"];
$_seller=$_POST["seller"];
echo"data:= "+$_product_name+$_price+$_quantity+$_seller;

Change:
echo"data:= "+$_product_name+$_price+$_quantity+$_seller;
To:
echo "data:= " . $_product_name . $_price . $_quantity . $_seller;
Why? If you use + with strings in PHP, they get interpreted as 0 or 1 and added that way.

Related

sending json via php curl but not getting a response

I am trying to send a json to a url and get a response back. I am creating the json correctly I believe. However when I try to send it via php curl I do not get a response back. The url I am sending it to does populate a response though.
Here is the php:
<?php
$post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);
$transfer = json_encode($post);
$ctrl = curl_init();
curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
curl_setopt($ctrl, CURLOPT_POST, TRUE);
curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ctrl);
curl_close($ctrl);
$response = json_decode($response);
echo $response;
?>
If I were to echo $transfer it would read:
{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
"output":"4"}
}
I would like to echo the response from the url I am sending the json too but instead, I get nothing back. However the url in the curl sequence (https://sample.com/question/add-question.php) does output a json on the webpage:
{"message":"An unknown internal error occured","success":false}
How am I not able to grab this and echo it in my original code snippet? Is it something wrong with my curl method?
Try setting the header to say you are sending JSON...
curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($transfer))
);
For the HTTPS, you may also need...
curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);
You also may try...
curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1);

Data not being received when sent by CURL

I am sending data via post command of curl. data is sent using array but when i receive, it just contains 1 and 0. Could you tell how to receive data that is being posted by curl.
Heres my code for curl.php file: $data array is being posted
<?php
$data=array(
'product_name' =>'Television',
'price' => 1000,
'quantity' => 10,
'seller' =>'XYZ Traders'
);
$url = 'http://localhost/API2/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
echo $response_json;
curl_close($ch);
?>
i am trying to get the posted data from curl in my products.php file using $_POST. But i receive one's and zero's
echo"Got here ";
$_product_name=$_POST["product_name"];
$_price=$_POST["price"];
$_quantity=$_POST["quantity"];
$_seller=$_POST["seller"];
echo"data:= "+$_product_name+$_price+$_quantity+$_seller;
So is it the right way to get data out of array being sent from curl or do i need to loop through array.

PHP request data from HTTPS

First of all, I am new in programming. I want to request specific data from another server (data from MSSQL) and transfer (insert) into my MySQL DB, what's the proper way to gain this purpose?
PURPOSE:
A member from MSSQL side would like to transfer certain amount of
points to MySQL, member could input how much of points they had, once
the points is transfer into MySQL successful, a notify script would
send to MSSQL side for update in their end.
What should be generate on MSSQL end, so that MySQL can get these data for further processing?
For example, I have HTTPS link: https://www.example.com/request-transfer.aspx?id=12345&sym=hello&name=linda
For PHP processing end, how can I use cURL to get these data?
I have below script for test, isn't enough to just use $_GET?
// GET
$id = $_GET['id'];
$sym = $_GET['sym'];
$name = $_GET['name'];
$data = array("id" => $id, "sym" => $sym, "name" => $name);
$data_string = json_encode($data);
$ch = curl_init('http://localhost/test/process.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$input = json_decode($data_string);
echo $input->id.', '.$input->sym.', '.$input->name;
echo $result;
Please advise.
You code looks ok so far, just don't set the headers. They will be set automatically on GET/POST requests. Only on PUT requests you need to specify them.
You could JSON stringify the $_GET array directly. This would allow any parameters to be sent to the remote site. If you want to ensure only valid parameters may be sent, you have done it correct. You just should test if the GET parameter is actually present.
If you do not want repeated long expressions, you could write a short function:
function _GET()
{ $n = func_num_args();
for($i = 0 ; $i<$n ;)
{ $key = func_get_arg($i++);
$array[$key] = isset($_GET[$key]) ? $_GET[$key] : '';
}
return $array;
}
$data_string = json_encode(_GET('id', 'sym', 'name'));

How to send and receive data to/from an API using CURL?

I have to make an API. For this, I will receive the data from the mobile devices as JSON using POST. I have to work with this data and send the response back to the devices also as JSON.
But I don't know how to take the data that I will receive. I have tried to make some tests using CURL to see how can I take this data but the $_POST is always empty. Can you please tell me how to send the data as JSON format to the API using CURL and how can I receive this data so I can work with it and send it back as response?
These are my test files:
curl.php:
//set POST variables
$url = 'http://test.dev/test.php';
$data = array(
'fname' => 'Test',
'lname' => 'TestL',
'test' => array(
'first' => 'TestFirst',
'second' => 'TestSecond'
)
);
//open connection
$ch = curl_init($url);
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
// execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
test.php:
var_dump($_POST);
The response that I get is:
array(0) { }
You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST array is empty. If you want it, you need do the parsing yourself in the test.php:
$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);
same questions: 1 2

Construct a PHP POST request with binary data

I'm trying to construct a PHP POST request that includes some binary data, following on from a previous StackOverflow question. The data is being submitted to this API call: http://www.cyclestreets.net/api/#addphoto
This is my PHP code:
$file = $_FILES['mediaupload'];
$file_field="#$file[tmp_name]";
$fields = array(
'mediaupload'=>$file_field,
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$ch = curl_init();
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);
$response = curl_exec ($ch);
This is what my PHP file outputs:
FIELDS STRING: mediaupload=%40%2Fprivate%2Fvar%2Ftmp%2FphpHjfkRP&username=testing&password=testing&latitude=auto&longitude=auto&datetime=auto&category=cycleparking&metacategory=good&caption=
API RESPONSE: {"request":{"datetime":"1309886656"},"error":{"code":"unknown","message":"The photo was received successfully, but an error occurred while processing it."},"result":{}}
I believe this means that everything else about the request is OK, apart from the format of the binary data. Can anyone tell me what I am doing wrong?
CURL can accept a raw array of key=>value pairs for POST fields. There's no need to do all that urlencode() and http_build_query() stuff. Most likely the # in the array is being mangled into %40, so CURL doesn't see it as a file upload attempt.
$fields = array(
'mediaupload'=>$file_field,
'username'=> $_POST["username"),
etc...
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
The http_build_query function generates a URL encoded query string which means that the "#file.ext" is URL encoded in the output as a string and cURL doesn't know that you're trying to upload a file.
My advice would be not to include the file to upload in the http_build_query call and included manually in the CURLOPT_POSTFIELDS.
$file = $_FILES['mediaupload'];
$file_field="#$file[tmp_name]";
$fields = array(
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, 'mediaupload=' . $file_field . '&' . $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);

Categories