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.
Related
I am trying to add the following data to my database using curl. It insert's the data but the data inserted is blank
Employee Name = Test
Employee Salary = 100
Employee Age = 28
This is my code in inserting the data:
// set post fields
$data["employee_name"] = "test";
$data["employee_salary"] = 1;
$data["employee_age"] = 1;
$ch = curl_init('http://localhost/cloud/v1/employees');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
This is my Function in getting the data :
function insert_employee()
{
global $connection;
$data = json_decode(file_get_contents('php://input'), true);
$employee_name=$data["employee_name"];
$employee_salary=$data["employee_salary"];
$employee_age=$data["employee_age"];
echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'";
if(mysqli_query($connection, $query))
{
$response=array(
'status' => 1,
'status_message' =>'Employee Added Successfully.'
);
}
else
{
$response=array(
'status' => 0,
'status_message' =>'Employee Addition Failed.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
}
Thank you
Replace this line:
$data = json_decode(file_get_contents('php://input'), true);
with:
$data = $_POST;
PHP will take your POSTed data and push it straight into a global $_POST array. No need to play with json_decode (unless you have posted a JSON string) or php://input.
Be aware, however, that blindly trusting posted data, and concatenating posted variables into a SQL statement is a huge security hole! Please look in to prepared statements and input validation.
I am executing a curl request and get a response which returns a json response. Below is the code after the response is sent back.
Response: "Zeros Replaced real token"
{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1
Code Used (For Testing) and accessing property:
$json = json_decode($result);
print_r($json); // Prints the Json Response
$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
$secondtry = $json['token'];
echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
print_r( $secondtry.'<br>');//Nothing Prints at all
I did notice a weird anomaly where it prints a 1 at the end, where as if i do
json_encode($json);
The return response replaces the one at the end of the string with a "true"
Could the "1 or true" at the end be throwing of the json decode?
Maybe I am missing something simple?
As Requested full test code
$url = "https://website.com/restapi.php";
//username of the user who is to logged in.
$userName="adminuser"; //not real user
$fields_string; //global var
$fields = array( //array will have more in the future
'username' => urlencode($userName)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { global $fields_string;
$fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url.'?'.$fields_string.'operation=getchallenge');
curl_setopt($ch,CURLOPT_POST, count($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
json_decode(), by default makes child objects into stdClass objects rather than arrays unless they are explicitly arrays.
Try something like:
$firsttry = $json->result->token;
The var_dump shows you the data type. Since result itself is an object, access its token with -> rather than []
$response = '{"success":true...}'
$json = json_decode($response); //var_dumping this will show you it's an object
echo $json->result->token; // 000000000
I figured out the issue. In the Curl Options I did not have
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Once i put this in #GentelmanMax solution worked for me, but the issue was in the curl response responding directly, where as the return transfer sends back a string that php can work with, which then allowed json_decode()to function as is should. I knew it was something simple.
I have a thank you page with URL that contains variables :
http://vieillemethodecorpsneuf.com/confirmation-achat-1a/?item=1&cbreceipt=VM6JQ6VE&time=1429212702&cbpop=C123FA24&cbaffi=twitpalace&cname=Roberto+Laplante&cemail=roberto%40gmail.com&ccountry=FR&czip=000
I have this GET function to catch the variables :
<?php
$clickbank_name = (isset($_GET['cname'])) ? $_GET['cname'] : '';
$clickbank_email = (isset($_GET['cemail'])) ? $_GET['cemail'] : '';
$clickbank_country = (isset($_GET['ccountry'])) ? $_GET['ccountry'] : '';
$clickbank_zip = (isset($_GET['czip'])) ? $_GET['czip'] : '';
$clickbank_aff = (isset($_GET['cbaffi'])) ? $_GET['cbaffi'] : '';
?>
Now I need to use curl PHP to send the data to that Zapier URL (but with the variables attached to it so it will give me) :
https://zapier.com/hooks/catch/bheq6y/?tag=client&cbaffi=twitpalace&cname=Roberto+Laplante&cemail=roberto%40gmail.com&ccountry=FR&czip=000
ps. I have added a manual tag to the URL
What would be the PHP Curl code to make this work? Need to be behind the scene operation.
I'll give it a shot.
$get_fields = ['tag' => 'client'];
if (isset($_GET['cname'])) $get_fields['cname'] = $_GET['cname'];
if (isset($_GET['cemail'])) $get_fields['cemail'] = $_GET['cemail'];
if (isset($_GET['ccountry'])) $get_fields['ccountry'] = $_GET['ccountry'];
if (isset($_GET['czip'])) $get_fields['czip'] = $_GET['czip'];
if (isset($_GET['cbaffi'])) $get_fields['cbaffi'] = $_GET['cbaffi'];
$encoded = '';
foreach($get_fields as $name => $value){
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
$url = 'https://zapier.com/hooks/catch/bheq6y/?'.rtrim($encoded,'&');
// simple get curl
$output = file_get_contents($url);
// or if you want more control over the request
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
$output = curl_exec($curl);
curl_close($curl);
In this example, we are posting data in parameters to another curl.php page and in curl.php,
i wrote some code to get executed whenever curl.php get called and the result will be sent back to page from where curl.php got a request.
Mechanism : This example is made in PHP using Curl.
First Step : Create curl.php file. That file will be called by another php file by using curl mechanism.
So in curl.php we will get some parameters. We get parameters and do some functionalities. After that when we desire output,
we just encode with json using json_encode() and simple echo.
$post = $_POST;
echo json_encode($post);
Note : index.php will get the data in json format because we are sending back data in json format to index.php
Second Step : we have to create an index.php file. Where we write a logic for executiing a curl with some parameters and then call curl.php and get result from curl.php
$url = 'http://localhost/curl_demo/curl.php'; // This is my targeted file(curl.php) that i want to execute when curl executed
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'id=1&name=sanjay'); // pass parameters to curl.php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$resArr = json_decode($response, true);
curl_close($ch);
print_r($resArr);
Note: The data that we get after curl executed successfully, we will get it in json format. That means we have to decode it using json_decode() in php.
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 am trying to execute a url and getting its response. Following is the code that executes the curl. I want the curl execution to return me a string in $result.
<?php
$fields = array
(
'username'=>urlencode($username),
'pwrd'=>urlencode($pwrd),
'customer_num'=>urlencode($customer_num)
);
$url = 'http://localhost/test200.php';
//open connection
set_time_limit(20);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result; //I want $result to be "Successful"
?>
This is my test200.php on localhost:
<?php
$usernam = $_POST['username'];
$pass = $_POST['pwrd'];
$customer_num = $_POST['customer_num'];
echo "Successful!";
?>
What changes do I make in test200.php? Please help.
You should use the httpcode returned by the curl execution and not rely on a string that is returned
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Here - http://www.webmasterworld.com/forum88/12492.htm
Once the data is sent to test200.php do the appropriate manipulation like insert the posted values into a table and on success
echo "Successful!";
or print the same in your test200.php.. assuming you are doing an insert code in test200.php code would be like
<?php
$qry = "INSERT INTO `your_table` (`field_customer_name`, `field_username`, `field_password`) VALUES ($fields['customer_num'], $fields['username'], some_encrypt_fxn($fields['pwrd']))";
mysql_query($qry);
$err_flag = mysql_error($your_conn_link);
if($err_flag == '') {
echo "Successful!";
}
else {
echo "Failed, Error " . $err_flag;
}
?>
If the purpose of getting "Successful!" is to check if the cURL returns success then i suggest using Prateik's answer of using the returned status code
Somehow a simple print("Successful"); statement in test200.php worked well. The response i get now is as follows: HTTP Code: 0 Array ( [0] => [1] => Successful )