Send query to json from php - php

I am trying to send a url from a php page to a json page in the format
"http://myserver.com/login?q={"myid":"phill","password":"mypass"}"
. If I paste this into a browser address it works correctly. I have tried HttpRequest and cURL with no success. Can you suggest how this may be achieved?.
<?php
$yourJSONEncodedData = array('userid' => "phill", 'password' => "mypassword");
$url = "http://myserver.com/login?q=".json_encode($yourJSONEncodedData);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$output = curl_exec($curl);
curl_close($curl);
var_dump($output);
$response = json_decode($output,true);
echo $response;
?>
I am expecting "{}" to be returned to the php program.

I don't know why you are sending parameter in json format? You can send parameters in query string and get all the values in json page.

Make use of json_encode() in PHP.
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
The above example will output: {"a":1,"b":2,"c":3,"d":4,"e":5}
Posting the JSON data using cURL (Something like this)
$url="http://myserver.com/login?q=".$yourJSONEncodedData;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$output = curl_exec($curl);
curl_close($curl);
var_dump($output);
That's all i can suggest without seeing your code.

Related

php curl v python request send file

I am trying to send a file with php curl, trying to replicate the following python request:
requests.post( f'{url}/sample', data={"forced": True}, files={'sample': open(filepath, 'rb')}, verify=verify_ssl )
Below is my attempt to do the same request using php curl, I however always get an error 400, 'missing sample':
$post = array(
'files'=>array(
'sample'=> file_get_contents($_FILES['file']['tmp_name']),
),
'data'=>array(
'forced'=>TRUE,
),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.'/sample');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // Skip SSL Verification
$result = curl_exec ($ch);
curl_close ($ch);
What am I doing wrong here ?
That Python request appears to be multipart/form-data and not a JSON request like the PHP example.
To upload a file with curl, see the CURLFile class.
I think it should look like this:
<?php
$sample = new \CURLFile($_FILES['file']['tmp_name']);
$post = [
'forced' => true,
'sample' => $sample,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.'/sample');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
curl_close($ch);

PHP code on curl

THis code is not showing up the google home page. Please point out the error in it.
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.google.com.kw");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
print $result;
?>
Remember that if your response is string-based; curl automatically encodes the response in utf8. So it might be necessary to decode the String to get what you want. Otherwise, your code is OK but here is another variant:
<?php
$serviceURL = "https://www.google.com.kw";
$curl = curl_init();
$settings = array(
CURLOPT_URL => $serviceURL,
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($curl, $settings);
$response = curl_exec($curl);
$response = utf8_decode ( $response ); // <== DECODES THE UTF8 ENCODED STRING.
if(curl_errno($curl)){
var_dump( curl_error($curl) );
exit;
}
print($response);
curl_close($curl);
Try This :
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.google.co.in");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip,deflate'));
curl_setopt($curl,CURLOPT_ENCODING, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($curl);
print $result;

using curlto send POST request always outputs the result

I'm using curl to send a port request without printing the result using this code
$data = array('username' => 'username', 'password' => 'password');
$url = 'http://urlhere';
$ch = curl_init($url);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// or use this line curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
I've used 1 and true for the last line of code but it always prints the result on the webpage. How to execute curl without outputting the result?
must work as i am using same code in my daily projects and getting back data without getting printed
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

PHP Json API server not working

I am trying to test client server with php and json. I am trying curl json request to an api url, and its seems it works.
Here is client code :
$data = array('id' => 2, 'something' => 4);
$content = json_encode($data);
$url = 'http://localhost/json.api.php';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$response = json_decode($result);
echo "<pre>";
var_dump($response);
curl_close($curl);
But, how can i get this request on server (on json.api.php) and parse it do something and then return json to requester client.
you can use $HTTP_RAW_POST_DATA to get the request

POST JSON with PHP cURL

I have the following php code
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
curl_setopt($ch, CURLOPT_POST, 1);
But I don't understand why is not working . The API that I'm posting the JSON to says that the parameters were not received . Is there anything wrong in my code ? I think the whole trick is on the JSON parameters... I'm not sure how to send them as I couldn't see any "nave->value" pair with the http analyzer as it usually appears in simple forms ... just that JSON code without any "name".
You can try as follows.
Basically if we have a array of data then it should be json encoded using php json_encode. And you should also add content-type in header which can be defined in curl as curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$data = array("country"=>"US","states"=>array("MHASASAS"=>"MH","XYZABABA"=>"XYZ"));
$postdata = json_encode($data);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
you can use this and replace with
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
use this
$Parameters = array(
'MerchantCode' => $MerchantCode,
'PriceValue' => $amount,
'ReturnUrl' => $callback,
'InvoiceNumber' => $resnum,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($Parameters));
If:you use post method,you should know that:
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
#see http://php.net/manual/en/function.curl-setopt.php
So:you can do like this:
$ar_form = array('name'=>'PHPJungle','age'=>66,'gender'=>'male');
$poststr = http_build_query($ar_form ); # important
$options[CURLOPT_HTTPGET] = false;
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $poststr ; //default type:application/x-www-from-urlencoded
curl_setopt_array ( $ch, $options );
# #todo your other codes
This is my class I have used for a long time.The class is based on PHP cURL.
It supports GET/POST,HTTP/HTTPS.
#see https://github.com/phpjungle/iHttp/
You can post a json data with curl like so:
Using Command Prompt:
curl -X POST -H "Content-Type: application/json" -d '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}' $url
Using PHP:
$data = array("folderId"=>"1","parameters"=>array("amount"=>3,"ascending"=>false,"offset"=>0,"sort"=>"date"));
$postdata = json_encode($data);
OR
$postdata = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
You haven't set the content type, so the post data is being sent as form data. Try setting the content type to application/json.
If that doesn't work, try wrapping the json string with an array.
$link = "http://test.domain/myquery";
$json = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
$postdata = json_decode($json);
echo openurl($link, $postdata);
This works as json decode converts a json string into array.
function openurl($url, $postvars = "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
return $content;
}
if your API endpoint using body for send request using json data may be you can use Guzzle the doc is here doc.
use GuzzleHttp\Client;
$client = new Client();
$request = $this->client->post($url,array(
'content-type' => 'application/json'
),array());
$request->setBody($json_data);
$response = $request->send();
return $response;
hope this work.
You can do it make by steps:
$data = array(
'folderId'=>"1","parameters"=>array(
"amount"=>"3","ascending"=>false,"offset"=>0,"sort"=>"date"
)
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result,true);
I don't know if you need the header. I think that by default it is already application/x-www-form-urlencode
If it doesn't work, try changing the $data values in array. Think it helps. :)
I'm not sure, that this is the solution but this works for me when posting json, change the json from
'{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}'
to
"{'folderId':'1','parameters':{'amount':3,'ascending':false,'offset':0,'sort':'date'}}"
The only change i made was the double quotes are now on the outside, that works for me but I'm obviously posting to a different server
Only other help I could offer is to download a network debugging tool such as Fiddler or Charles proxy and monitor the requests sent/received, it could be a case that something else is wrong in your code.
Hope i helped :)
first of all
please check the curl http status code
$http_code= curl_get_info($exec_res,CURL_HTTP_CODE);
then modify this request header set with post header API server add a recorder to log those request info.

Categories