Curl request works in Rested chrome extension but not in php - php

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

Related

How to Pass json Dtat in query param in php for pull service

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);

JSON not showing image from this

my code wont show the screenshot header('Content-Type:image/png');
$url = 'https://www.google.com/';
//API Url
$url2 = 'http://api.site:port/screenshot';
//Initiate cURL.
$ch = curl_init($url2);
//The JSON data.
$jsonData = array(
'url' => $url
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//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);
curl_close($ch);
i have tested on postman this shows correct just not on php/json any ideas?

I get an authentication error with a json post

I am trying to authenticate, the result of my request is returned incorrectly.
Request Model
Method: Post, Endpoint: /api/authenticate, Header Variables:
[{"key":"Content-Type","value":"application/json","enabled":true}],
Body Parameters: username: string, password: string,
authenticationType: string
Sample Request
POST /api/authenticate
Host: mpop-sit.hepsiburada.com
Content-Type: application/json
{
"username": "xyz_dev",
"password": "XYZ_dev123!",
"authenticationType": "INTEGRATOR"
}
Request i sent
$url = 'https://mpop-sit.hepsiburada.com//api/authenticate';
$ch = curl_init($url);
$header = array(
'Content-Type: application/json',
'Authorization: Bearer '. base64_encode('xyz_dev:XYZ_dev123!:INTEGRATOR'),
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
$return=json_decode($result,true);
print_r($return);
This is the result of the query returned and the error I received.
Where do you think I might be making a mistake?
Array ( [timestamp] => 2020-02-07T09:01:47.426+0000 [status] => 500
[error] => Internal Server Error [exception] =>
io.jsonwebtoken.MalformedJwtException [message] => JWT strings must
contain exactly 2 period characters. Found: 0 [path] =>
//api/authenticate )
Do you need the authentication header for this endpoint?
Because what the sample request wants you to send the parameters in the request body like this:
$post = [
'username' => 'xyz_dev',
'password' => 'XYZ_dev123!',
'authenticationType' => 'INTEGRATOR'
];
$url = 'https://mpop-sit.hepsiburada.com//api/authenticate';
$ch = curl_init($url);
$header = array('Content-Type: application/json');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
$return=json_decode($result,true);
print_r($return);
So no need fot the Authentication: Bearer ... header, it would also be created differently.
This should work fine! I get access denied error, so, that means codes works fine.
Note you might need to change http_build_query($fields) to $fields
$url = "https://mpop-sit.hepsiburada.com/api/authenticate/";
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$fields = array(
"username" => "xyz_dev",
"password" => "XYZ_dev123!"
);
$header = array(
'Content-Type: application/json',
'Authorization' => 'Bearer ' . $token,
);
//open curl connection
$ch = curl_init();
//set the url, fields, vars
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); // SSL false if not required
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); //False if not required
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute fields
$result = curl_exec($ch);
//return result echo $result; if you need
echo curl_error($ch);
//close curl connection
curl_close($ch);
Please let me know if it works!
UPDATE : if you want to use ssl which is saving you from hacks.
Follow steps in this answer to activate ssl : https://stackoverflow.com/a/59919558/12232340
2 slashes here, so it does not work:
$url = 'https://mpop-sit.hepsiburada.com//api/authenticate';

POST JSON data via CURL and grabbing it

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
?>

How do I make a POST using X-HTTP-Method-Override with a PHP curl request?

I'm working with the Google Translate API and there's the possibility that I could be sending in quite a bit of text to be translated. In this scenerio Google recommends to do the following:
You can also use POST to invoke the API if you want to send more data
in a single request. The q parameter in the POST body must be less
than 5K characters. To use POST, you must use the
X-HTTP-Method-Override header to tell the Translate API to treat the
request as a GET (use X-HTTP-Method-Override: GET). Google Translate API Documentation
I know how to make a normal POST request with CURL:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
But how do I modify the header to use the X-HTTP-Method-Override?
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET') );
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_HTTPHEADER
An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
Thus,
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
use the CURLOPT_HTTPHEADER option to add a header from a string array
Not enough for me , i need to use http_build_query fo my array post data
my full example :
$param = array(
'key' => 'YOUR_API_KEY_HERE',
'target' => 'en',
'source' => 'fr',
"q" => 'text to translate'
);
$formData = http_build_query($param);
$headers = array( "X-HTTP-Method-Override: GET");
$ch=curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$formData);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite'); //if you have refere domain restriction for your google API KEY
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
$query = curl_exec($ch);
$info = curl_getInfo($ch);
$error = curl_error($ch);
$data = json_decode($query,true);
if (!is_array($data) || !array_key_exists('data', $data)) {
throw new Exception('Unable to find data key');
}
if (!array_key_exists('translations', $data['data'])) {
throw new Exception('Unable to find translations key');
}
if (!is_array($data['data']['translations'])) {
throw new Exception('Expected array for translations');
}
foreach ($data['data']['translations'] as $translation) {
echo $translation['translatedText'];
}
I found this help here https://phpfreelancedeveloper.wordpress.com/2012/06/11/translating-text-using-the-google-translate-api-and-php-json-and-curl/
Hope that helps

Categories