I have simple function in PHP that gives me
HTTP Error 500 (Internal Server Error):
When I comment it, the simple echo does get printed.
Here is the function:
error_reporting(E_ALL);
ini_set('display_errors', '1');
function invokeAuthenticationServiceAPI()
{
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
$data_string = json_decode($json);
echo $data_string;
/*
$ch = curl_init('https://apirestserverdemo/api');
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))
);
$result = curl_exec($ch);
echo $result;
*/
}
I call it in the HTML file like this:
<?php
invokeAuthenticationServiceAPI();
?>
As you can see, I need to send it to rest api server. But it does fail only on the string to json formatting.
I have two questions:
Maybe I have done something that php doesn't like. Ok, but can I get some kind of error message and not "Error 500 (Internal Server Error)"?
What am I doing wrong?
You should check the web-server error log for the details of the error, but judging by the code you have posted, the problem is probably that there are spaces before the end of the heredoc JSON; and the first time you use JSON it should not be quoted.
You should use this:
$json = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON; // no spaces before JSON;
instead of this:
$json = <<<"JSON"
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
Although personally I would generate an array or object in php and use json_encode to generate the correct output.
Remove double quotes around JSON and remove extra spaces which invalidate the PHP heredoc syntax
$json = <<<"JSON"
should be
$json = <<<JSON
Like
<?php
$str = <<<JSON
{
"auth":
{
"username":"foo",
"password":"bar"
}
}
JSON;
echo $str;
?>
If you have a 500 Internal Server Error you almost certainly have a fatal error in PHP. Depending on your code you may find the error in your error logs or you may have to debug your code using for example xdebug.
You don't need quotes around JSON. Other than that there's nothing immediately wrong with your code. However you should generate JSON using json_encode.
Related
I'm sending some data with the fetch API to a translate.php file, here is my JS code:
const translation = {
word: 'Hello'
};
fetch('http://yandex.local/translate.php', {
method: 'POST',
body: JSON.stringify(translation),
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
return res.text();
}).then(text => {
console.log(text);
})
Here is how I try to get the data on the translate.php:
$postData = json_decode(file_get_contents("php://input"), true);
$word = $postData['word'];
Here is my cURL request:
$word = $postData['word'];
$curl = curl_init();
$request = '{
"texts": "Hello",
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
curl_setopt($curl, CURLOPT_URL, 'https://translate.api.cloud.yandex.net/translate/v2/translate');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Api-Key 123456",
"Content-Type: application/json"
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$err = curl_error($curl);
if($err) {
echo 'Curl Error: ' . $err;
} else {
$response = json_decode($result, true);
print_r($response['translations']['0']['text']);
}
curl_close($curl);
When I'm runing this code I get the translation of Hello in russian which is Привет. But if I replace "Hello" in the request object by $word I got the error: Trying to access array offset on value of type null
Here is the way I rewrite the request object:
$request = '{
"texts": $word,
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
When I check the XHR of my translate.php all seems ok, I have a status 200 and the request payload shows my data. Also the word "hello" displays correctly in the console of my index.php
Don't ever create JSON strings by hand (i.e. I mean by hard-coding the JSON text directly into a string variable). It can lead to all kinds of syntax issues accidentally.
Please replace
$request = '{
"texts": "Hello",
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
with
$requestObj = array(
"texts" => $word,
"targetLanguageCode" => "ru",
"sourceLanguageCode" => "en"
);
$request = json_encode($requestObj);
This will produce a more reliable output, and also include the $word variable correctly.
P.S. Your actual issue was that in PHP, variables are not interpolated inside a string unless that string is double-quoted (see the manual). Your $request string is single-quoted.
Therefore $word inside your $request string was not changed into "Hello" but left as the literal string "$word". And also since you removed the quotes around it, when the remote server tries to parse that it will not be valid JSON, because a text variable in JSON must have quotes around it. This is exactly the kind of slip-up which is easy to make, and why I say not to build your JSON by hand!
Your version would output
{"texts":$word,"targetLanguageCode":"ru","sourceLanguageCode":"en"}
whereas my version will (correctly) output:
{"texts":"Hello","targetLanguageCode":"ru","sourceLanguageCode":"en"}
(Of course I should add, given the comment thread above, that regardless of my changes, none of this will ever work unless you send a correct POST request to translate.php containing the relevant data to populate $word in the first place.)
I have tried to get data from this source, which is school detail on my country. but when i get the response, i cannot decode my response and it say Null. Idk why, but when i try to copy and paste my response result to hardcode, it can be decoded. why ?
i have tried all possible way to solve this, nothing work.
this is my code :
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'http://jendela.data.kemdikbud.go.id/api/index.php/Csekolah/detailSekolahGET?mst_kode_wilayah=026700');
$response = $res->getBody()->getContents();
$result = json_decode($response); // this return NULL
//But when i going to return the $response, it show the response.
return $response;
I expect to access the data or maybe just decode my code, and it will help me a lot.
FYI, I'am using Guzzle 6 and Laravel 5.7 to work with this.
i hope someone can try too access it to and help me.
or maybe if you want to test it you can use Curl Ways :
$param = 'index.php/Csekolah/detailSekolahGET?mst_kode_wilayah=026700';
$url='http://jendela.data.kemdikbud.go.id/api/'.$param;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
return $response;
The json_decode document says:
NULL is returned if the json cannot be decoded or if the encoded data
is deeper than the recursion limit.
You can use json_last_error or json_last_error_msg function to determine the problem.
I can't get the whole response, it's timeout and terminated.
Remove the line return $response;
and try the following code:
$enc = mb_detect_encoding($response);
if($enc == 'UTF-8') {
$response = preg_replace('/[^(\x20-\x7F)]*/','', $response);
}
echo "<pre>";
print_r(json_decode($response,true));
Per the documentation:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit
Source: json_decode
Some debugging tips:
Make sure all the characters fall within utf8
Specify a depth value(higher than the default)
Make use of json_last_error see: json_last_error
If debugging tip 1 happens to be the cause of the issue, see if you can limit the return to not include the offending characters.
I am trying to send from a php code running on a nginx server a get request to another remote django server. I am expecting to get data in REST API using serializer.
First if I open this link in my local browser:
http://192.168.2.0:8000/myapp/documents/
I will get:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": "000e3588-9544-4df6-a589-cc0166242b5b",
"docfile": "/media/documents/2017/06/30/DSC03623.JPG"
},
{
"id": "3dc6be9f-8659-41d8-8282-b64662032da6",
"docfile": "/media/documents/2017/06/30/DSC03611_9KWbftQ.JPG"
},
{
"id": "28eacb2d-0798-46e9-b63e-10ff704482ce",
"docfile": "/media/documents/2017/06/30/DSC03555.JPG"
}
]
and this is exactly the info I want to get when i run my php code.
This is what I was working on, the commented parts are previous failed attempts:
<?php
echo "<h1>I am here</h1>";
$url = "http://192.168.2.0:8000/myapp";
/*$body = http_parse_message(http_get($url))->body;
$body = http_get($url);
echo $body;*/
/*$client = new Client($url);
$request = $client->newRequest('/documents/');
$response = $request->getResponse();
echo $response->getParsedResponse();*/
$r = new HttpRequest('http://192.168.2.0:8000/myapp/documents/', HttpRequest::METH_GET);
$r->send();
echo $r->getResponseCode();
if ($r->getResponseCode() == 200)
{
echo "<h2>we get 200 response</h2>";
}
?>
non of the above 3 attempts printed anything except the first echo
I am here
Ok, finally this is the code that worked for me:
<?php
$ch = curl_init('http://192.168.2.0:8000/myapp/documents/');
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
?>
it needs cUrl to work.
cUrl usual enabled in php. To double check
run this code as a script:
<?php
phpinfo();
?>
search in in the results if cUrl is working.
I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
Now the question:
How can I process the json response format of moodle system? Any idea would be great.
[UPDATE]:
I have used another approach via curl and changed in php.ini following lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice: Trying to get property of non-object. Here is the updated code:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};
I've researched everywhere and cannot figure this out.
I am writing a test cUrl request to test my REST service:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
This works fine and the request is accepted by my service and $_Post is populated as required, with two variables, order and data. Data has the encoded JSON object. And when I print out $_Post['data'] it shows:
{"products":{"product1":"abc","product2":"pass"}}
Which is exactly what is expected and identical to what was sent in.
When I try to decode this, json_decode() returns nothing!
If I create a new string and manually type that string, json_decode() works fine!
I've tried:
strip_tags() to remove any tags that might have been added in the http post
utf8_encode() to encode the string to the required utf 8
addslashes() to add slashes before the quotes
Nothing works.
Any ideas why json_decode() is not working after a string is received from an http post message?
Below is the relevant part of my processing of the request for reference:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
Turns out that when JSON is sent by cURL inside the post parameters & quot; replaces the "as part of the message encoding. I'm not sure why the preg_replace() function I tried didn't work, but using html_entity_decode() removed the " and made the JSON decode-able.
old:
$return_obj->setData(json_decode($data['data']));
new:
$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);
try it im curious if it works.