JSON post method in php - php

I don't get what do I do wrong when I try to get my values from post method from angular to php, it seems that everything is correct but then I am not able to see any values to postman/return the correctly.
this is my php method with all my attempts:
public function created()
{
$json = file_get_contents('php://input');
$json_string_in_array = array($json);
$json_array =json_decode($json_string_in_array[0]);
var_dump($json_string_in_array);
var_dump($json_array);
//return $json_array;
// $data = json_decode(file_get_contents('php://input'), true);
// $data = json_encode(file_get_contents("php://input"));
// $request = json_decode($data);
// var_dump($data);
// return $data;
// return $request;
// $json = file_get_contents('php://input');
//$obj = json_decode($json);
// get the raw POST data
// $rawData = file_get_contents("php://input");
// this returns null if not valid json
// return response()->json($rawData);
// DatabaseModel::DatabaseModel($json_array);
}
what I am trying to do is get that data and then send it to DatabaseModel in order to add it to database.

First you header, content-type, should be application/json. Are you manually setting the headers in angular? I am pretty sure angular will detect (or at least it is the default) the content type if its not set so in your case it would be application/json
<?php
$json = file_get_contents('php://input');
$request = json_decode($json);
$name = $request->name;
$email = $request->email;
# etc
?>

Related

How to modify post response in php

How to modify this response
$url = "https://example.com";
$data = "{\"phone_number\":\"18868768"};
$len = strlen($data);
$headers = array();
$otp = request($url, $data, $headers);
the response is
{"status":0,"msg":"not Found"}
I want to modify to this :
{"status":1,"msg":"Found"}
I'll assume you're saving your response to a $response variable. You need to convert the JSON to an array to manipulate it, then convert it back to JSON. So to change it you would do:
$response = json_decode($response, true);
$response['status'] = 1;
$response['msg'] = 'Found';
$response = json_encode($response);
That being said, you really shouldn't be encoding your initial JSON in string form. Do this instead:
$data = json_encode([
'phone_number' => 18868768
]);

JSON: Update base64 string using url JSON

I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.

Get incoming webhook of woocommerce

I'm trying to receive a JSON of a woocommerce webhook in a tracker.php to manipulate the content, but something is wrong because it doesn't save anything in $_SESSION. This is my code ....
(!isset($_SESSION))? session_start() : null;
if($json = json_decode(file_get_contents("php://input"), true)) {
$data = json_decode($json, true);
$_SESSION["json"] = $data;
} else {
var_dump($_SESSION["json"]);
}
tested the webhook with http://requestbin.fullcontact.com/ and received the content. here a capture
issue is in this line
$data = json_decode($json, true);
here $json is array and jsondecode expect string.
here is code which will work.
(!isset($_SESSION))? session_start() : null;
if($json = json_decode(file_get_contents("php://input"), true)) {
//this seection will execute if you post data.
$_SESSION["json"] = $json;
} else {
//this will execute if you do not post data
var_dump($_SESSION["json"]);
}

Parse JSON with PHP

I am sending data from my iOS app to my server in json format. Here is the format.
{
"email" : "email",
"password" : "password"
}
How can I get these variables in PHP? I actually want to get the parameters like that
$json = $_POST['jsondata'];
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
If I can't get the data like this, please tell me how should I send the data so that the backend can accept my data?
Try below
Method 1:
$json = file_get_contents( 'php://input' ); // RECEIVE INPUT JSON STRING
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
Method 2:
fopen(DOCROOT."json.txt","w+");
file_put_contents("json.txt", $_POST);
$recoreds = file_get_contents('json.txt', true);
$json_a=json_decode($recoreds, true);

Using php for http requests

I am very new to PHP, and need to use an HTTP Request to download a URL that is external to my server. That URL is a PHP function that returns JSON code which I have decode. Any suggestions?
I have tried basic code:
<?php
//Code for forming the url (which I'm sure is correct)
$url = ...
$response = fopen($url,"x+");
$response = json_decode($response);
echo $response;
?>
//javascript in a seperate file that calls the php code
var response = xmlhttp.responseText;
alert(response);
Try this:
<?php
$url = 'YOUR_URL_HERE';
$data = file_get_contents( $url ); // it is a JSON response as per your statement.
$data= json_decode($data);
print_r($data); // now, it's a normal array.
?>
You may use fopen if config allows, or cURL or fsockopen functions to do that
You could use:
$json_str = file_get_contents($url);
$json = json_decode($json_str, true);
Couldn't you use file_get_contents? E.g.
<?php
$url = "YOUR_URL";
$json = file_get_contents($url);
// handle the data
$data = json_decode($json, TRUE);
var_dump($data); // example
?>
If you are doing a lot of requests you can try using a http class like Buzz which will Help clean up your code https://github.com/kriswallsmith/Buzz

Categories