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
]);
Related
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.
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
?>
I'm trying to send a post request that header is json and the response also is json. What i have tried so far. This always return a status code 400. what i'm doing wrong?Thanks
private function requestPOST($url,$data)
{
App::uses('HttpSocket', 'Network/Http');
App::uses('Json', 'Utility');
$this->layout = 'default';
$this->autoRender = true;
$HttpSocket = new HttpSocket();
$jsonData = json_encode($data);
$request = array('header' => array('Content-Type' => 'application/json'));
debug($url);
$response = $HttpSocket->post($url, $jsonData, $request);
debug($response->code);
//$this->render('index');
$jsonString = json_decode($response['body'], true);
debug($jsonString);
return $jsonString;
}
I have solved myself. I was doing twice json_encode of the $data.
When I try to post values to .net REST web service using post method.It will hit the service but the values are not getting posted.
I am using IIS server and here is my PHP code. If I use get method then values are getting post but not with POST.
function curl_post_call($url,$data){
$headers = array(
'Accept:application/json',
'Content-Type:application/json',
);
$handle = curl_init();
curl_setopt($handle,CURLOPT_URL,$url);
curl_setopt($handle,CURLOPT_HTTPHEADER,$headers);
curl_setopt($handle,CURLOPT_RETURNTRANSFER,true);
curl_setopt($handle,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($handle,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($handle,CURLOPT_POST,true);
curl_setopt($handle,CURLOPT_POSTFIELDS,$data);
$response = curl_exec($handle);
//print_r($response);
$code = curl_getinfo($handle,CURLINFO_HTTP_CODE);
print_r($code);
return $response;
}
$url = 'http://LHBLREGL003/PayMentRESTService/PayMentService.svc/SaveCVAuditTrail';
$dataArray['ChartID'] = 'chart';
$dataArray['OldValue'] = 'ol';
$data = json_encode($dataArray);
$result = curl_post_call($url,$data);
print_r($result);
SERVER Method written in .net Here is the code
public int SaveCVAuditTrail(List<CVAuditTrailBLDTO> lstCVAuditTrail)
{
int result = 1;
return result;
}
Any suggestions please ?
Http post return data with invalid characters
$url = 'https://sandbox.itunes.apple.com/verifyReceipt';
$params = array('receipt-data' => 'receipt data');
$params = json_encode($params);
my code is
$client = new Client();
$client->setUri($url);
$client->setMethod('POST');
$client->setRawBody($params);
$client->setHeaders(array(
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
));
$client->setAdapter(new Curl());
$response = $client->send();
$res = $response->getContent();
my out put is this
����
if any one know about this please help me.
You have to decode JSON response from the body like this:
var_dump(json_decode($response->getBody(), true));
Then you will get an array with proper response :)
e.g.:
array(1) { ["status"]=> int(21002) }