i have a device that send POST data to my server.
so print_r($_POST) is empty, i can see the data only when i run this
$content = file_get_contents('php://input');
var_dump($content);
//or i can use: print_r($content);
i save those to a file and result are some json and BINARY DATA (CHECK IMAGE)
if i add code like this json_decode($content,true); i dont see anything
so how can i decode binary or what can i do to decode the json and also see what data is send in binary?
If you want to decode binary data inPHP, try the following:
<?php
$binarydata = "\x04\x00\xa0\x00";
$data = unpack('C*', $binarydata);
var_dump($data);
output:
array (size=4)
1 => int 4
2 => int 0
3 => int 160
4 => int 0
Load your contents from file_get_contents('php://input') to $binarydata and you will get an array of values. You can then apply some logic to extract JSON string and process it.
Related
I want to decode my user id(already encoded ) using vinkla hashids
$user_id= "1"; // I encoded this
$en_user_id = Hashids::encode($user_id); // I got 'ND'
$dec_user_id = Hashids::decode($en_user_id); // It is not decoding
I want to decode ND to get original ID
when I try to decode I got this
ErrorException
htmlspecialchars() expects parameter 1 to be string, array given
I'm trying to get PHP returned array from Ajax.
Here is my Ajax call:
And my PHP code is this:
Query is running perfectly.
I have tried to get values like alert(data[0].program_title) in ajax success. But it also returns Undefined.
How can I fix this issue?
In your PHP code:
//remove
return $data
//change with
echo json_encode($data);
Just before flushing the data back to the stream (returning), convert your data ($data variable in this case) to JSON string using json_encode and add the proper content-type application/json using header function.
However, the best practice is to provide some metadata to your data included in your transfer, like the size of data and count of elements in data and if paginated, which page the data refers to and what the maximum available pages and maximum element size of a page are.
Here's a sample body structure for a more robust data transfer:
$response = [
'page' => 0, // e.g.
'count' => count($data),
'data' => $data,
'max_page' => 3, // e.g.
'item_per_page' => 15, // e.g.
'status_code' => 200, // e.g.
];
header ( "Content-Type: application\/json", true , 200);
return json_encode(
$response
, JSON_INVALID_UTF8_SUBSTITUTE
| JSON_NUMERIC_CHECK
| JSON_PRESERVE_ZERO_FRACTION
| JSON_UNESCAPED_LINE_TERMINATORS
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
Try this:
$data = [];
if ($numRows>0) {
while($row=$result->fetch_assoc()) {
$data[] = $row;
}
}
Replace return with echo and add json_encode
echo json_encode($data);
I am posting data from Vb.net client to a PHP rest api but for some reason the json_decode is not working on the passed string.
The code to post to the server is :
Dim payload As String = "{""key"":""Test"",""bookings"":" & txtUpload.Text & "}"
Dim request As WebRequest = WebRequest.Create(String.Format(baseAPIImportUrl))
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim byteArray() As Byte = Encoding.UTF8.GetBytes(payload)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse
' Display the status.
MessageBox.Show(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream
' Open the stream using a StreamReader for easy access.
Dim reader As StreamReader = New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd
' Display the content.
' Console.WriteLine(responseFromServer)
MessageBox.Show(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
The values that are being passed :
{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }
On the PHP side I do :
$bookings = $_POST->bookings
$data = json_decode($bookings,true);
$total = count($data['booking']);
The $total should show 1 as there is 1 item in the booking array but it always is shows 0
$_POST->bookings - this is your problem. -> is the object access operator, but in PHP, $_POST is not an object but an array.
If you were submitting this value as part of form data, you would normally access it via array syntax (e.g. $_POST['bookings']), but from your VB code, you're actually posting the JSON string as the POST body itself.
In PHP, you can access the raw POST body like this:
$bookings = file_get_contents('php://input');
The rest of your code should then work as usual.
Edit: actually, you've got a typo in there as well. Try
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
There is a json array there also. Try this.
<?php
$data='{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }';
$data = json_decode($data,true);
echo '<pre>';
print_r($data);
$total = count($data['bookings']['booking']);
echo $total;
$data = json_decode($bookings,true);
Here as per the php documentation sencond argument in json_decode function denotes whether return output as an object or as an array
argument 2 = true ( will return array )
argument 2 = false ( will return object , it is the default value)
The json_decode produces the following array
Array
(
[key] => 91a1522Test
[bookings] => Array
(
[booking] => Array
(
[0] => Array
(
[ClassId] => 4
[ClassName] => THOASC
[YearWeek] => 1751
)
)
)
)
Hence it should be accessed like count($data['bookings']['booking'])
I have a JSON-String like
{"aaa":"foo", "bbb":"bar", "ccc":"hello", "ddd":"world"}
Actually I recive this string via $_GET. It is base64 encoded and if I decode it I have this string.
So further is want to use this in PHP as an object. For this is do
$data = json_decode( base64_decode( $_GET['data'] ) );
but $data is NULL all the time. If I do
echo base64_decode( $_GET['data'] );
Then the valid JSON-String is printed as expacted.
What am I doing wrong ?
I have tried to call the base64_encode before but same result...
Check json_last_error() and see what error the JSON parser encountered. If you encounter 5 then it is very likely that your JSON data contains unencoded UTF-8 sequences. You should always use a JSON-encoding library for handling data export to json.
See http://php.net/manual/en/function.json-last-error.php for a list of what errors you can handle with json_last_error (There is a INT to definition name table in the user comments)
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
I am stuck a long time with trying to send a JSON from javascript to a PHP script : the sending is fine (I can see the JSON in fiddler) yet I receive nothing in the PHP script :
javascript:
var person = {
name: 'yoel',
age: 28
};
xmlhttp.open("POST","http://localhost:8888/statisticsdb.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(person));
php :
echo 'trying to print ' . var_dump($_POST["name"]);
I would expect obviously to see SOMETHING but var_dump returns nothing. Help would be much appreciated!
try:
$data = json_decode(file_get_contents('php://input'));
var_dump($data->name);
the reason for this is, that the body of your POST-request is:
{"name":"yoel","age":28}
though, php expects something like (ref):
name=yoel&age=28
The json string can not be parsed properly, and thus $_POST will be empty.
$_POST holds value decoded from request having Content-Type application/x-www-form-urlencoded, i.e. it parses:
param1=value1¶m2=value2
into:
array( 'param1' => 'value1', 'param2' => 'value2')
If you send data in json format, you have to json_decode it from the raw php input:
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
And you'll have a PHP object filled with your json stuff.
Add this:
xmlhttp.setRequestHeader("Content-length", JSON.stringify(person).length);