Null values When try to post values to Rest webservice using PHP - php

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 ?

Related

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.

Yii2 request PUT not working properly

I am using a rest api in yii2 with Authorization : Bearer and my update action requires sending data using PUT. I have configured the actionUpdate completely but somehow i am not getting any data in Request PUT.
I found few articles online about problems with Yii2 PUT but could not find out weather there is any solution to that yet or not?
One of the article or issue is github issue and it points to this github issue
Ad if no solution yet than what alternative should i use for Update action.
Here is my actionUpdate code
public function actionUpdate($id)
{
$params = Yii::$app->request->bodyParams;
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id' => Yii::$app->user->id])->one();
if($model !== null){
$model->load($params, '');
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
}
}
}
This is a screenshot of debug screen. See the event_name attribute.
That was screenshot after the execution of $model->load($params,'') line.
I am calling the service like following and not able to Update the data properly. My service works fine through postman.So i guess i am missing something in CURL request.
$service_url = 'http://localhost/site-api/api/web/v1/events/'.$eventDetailDBI->gv ('id');
$curl = curl_init($service_url);
$curl_post_data = array(
"event_name" => $eventDetailDBI->gv ('name'),
);
$header = array();
$header[] = 'Authorization: Bearer 4p9mj82PTl1BWSya7bfpU_Nm';
$header[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
$json = json_decode($curl_response, true);
curl_close($curl);
I am getting correct data in my POST fields and passing correct data but the service doesnt update any data.
Thank you
try this:
public function actionUpdate($id)
{
// this will get what you did send as application/x-www-form-urlencoded params
// note that if you are sending data as query params you can use Yii::$app->request->queryParams instead.
$params = Yii::$app->request->bodyParams;
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id' => Yii::$app->user->id])->one();
if($model !== null){
// This will load data to your safe attribute as defined in your model rules using your default scenario.
$model->load($params, '');
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
/*
you can use Yii::$app->getResponse()->setStatusCode(200) here but no need to do that.
response will be 200 by default as you are returning data.
*/
// yii\rest\Serializer will take care here of encoding model's related attributes.
return [
'status' => 1,
'data' => $model
];
}
else {
// when validation fails. you model instance will hold error messages and response will be auto set to 422.
return $model;
}
}
}

PHP object and methods - does $object->method request data or just store it

I have a query which requests data and returns an array called $result.
class data {
public function __construct ($type) {
$this->type = $type;
}
function set_url($url) {
// Construct URL based on type.
return $this->url;
}
function curl_data($url) {
$url = $this->set_url(); //Run the set_url function to work out the url of the object
$options = array (CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => etc ); // stop after 10 redirects
//Initiatiate the connection
$ch = curl_init ( $url );
curl_setopt_array ( $ch, $options );
//Capture the content
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
$header ['content'] = $content;
return $header ['content'];
}
}
I can then call this data by using:
$object = new data('type1');
$object->curl_data(); //Select the URL, Process the api call, return the content
All works this far. However, when I then decode the json with a similar function inside the data class, I hit an error because I'm requesting too much data from the server.
public function decode_json($response){
//$this->curl_data();
//manipulate the response
$response = json_encode($response,true);
$response = json_decode($response);
return $response;
}
I think this is because my decode function carries out a new curl_data() call - rather than just using the data which has already been retrieved. I've tried using both of the following approaches to call the decode function and am not sure which one broke it / how to make it work.
$object->decode_json($object->curl_data()); //with $decode_json escaping $this->curl_data(); and requesting ($response)
$object->decode_json(); //with decode_json() using $this->curl_data(); and not requiring ($response)
My question is - How does my $object->curl_data(); query actually work and how can I avoid multiplying up the queries by referencing it in a way that re-requests data from the server. This comes to light with JSON queries, but probably also results in serious performance issues if I do it wrong when requesting from my own databases etc.
It seems that the '->' syntax results in extra queries through the method - rather than just storing the data, but if I just store the data in a variable I wouldn't be coding to OOP principles.
maybe this is what you want:
$result1 = $object->curl_data();
$result2 = $object->decode_json($result1);
$result3 = $object->calculate_figures($result1);
do curl_data only once and handle the result with 2 different methods.

Importing quotes into vtiger crm with web services

I need to import quotes into vtiger.
I find out it can be be done using vtiger web services API
I find out the reference manual:
https://wiki.vtiger.com/archives/index.php/vtiger510:Webservice_reference_manual
But i can't find any example PHP script, neither what data fields I need to pass to webservice.php.
Please help, I need some guidance.
I have done something like this, I have a quick and (rather) dirty but working solution:
<?php
function createOffer($account_id,$subject,$offerlanguage, $totalamount,$date_submission,$date_decision,$date_start,$assigned_user_id,$quotestage,$winningchance,$description,$productarray){
global $adb;
$endpointUrl = "[your URL]/webservice.php";
$userName="admin";
$userAccessKey = '[your accesskey]';
$httpc = new HTTP_CLIENT();
//getchallenge request must be a GET request.
$httpc->GET($endpointUrl."?operation=getchallenge&username=".$userName);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
//check for whether the requested operation was successful or not.
if($jsonResponse['success']==false)
//handle the failure case.
die('getchallenge failed:'.$jsonResponse['error']['errorMsg']);
//operation was successful get the token from the reponse.
$challengeToken = $jsonResponse['result']['token'];
//create md5 string concatenating user accesskey from my preference page
//and the challenge token obtained from get challenge result.
$generatedKey = md5($challengeToken.$userAccessKey);
//getchallenge request must be a GET request.
$httpc->post("$endpointUrl",
array('operation'=>'login', 'username'=>$userName, 'accessKey'=>$generatedKey), true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
//handle the failure case.
die('login failed:'.$jsonResponse['error']['errorMsg']);
//login successful extract sessionId and userId from LoginResult to it can used for further calls.
$sessionId = $jsonResponse['result']['sessionName'];
$userId = $jsonResponse['result']['userId'];
$currency_id=1;
$params = array('description'=>$description,'subject'=>$subject,'quotestage'=>$quotestage,'assigned_user_id'=>'2x'.$assigned_user_id,'account_id'=>'3x'.$account_id,'cf_682'=>$offerlanguage,'currency_id'=>'21x'.$currency_id,'taxtype'=>'group','cf_683'=>$date_submission,'cf_684'=>$date_decision,'cf_685'=>$date_start,'cf_766'=>$winningchance);
$urlArgs = "?&total=".$totalamount;
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($params);
//name of the module for which the entry has to be created.
$moduleName = 'Quotes';
//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post($endpointUrl.$urlArgs, $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];
$id=str_replace("13x", "", $id);
echo $id." offer: ".$subject." created for amount ".$totalamount." for customer: ".$account_id." assigned to: ".$assigned_user_id;
return $id;
}
As you see there are a few custom fields too so you can see how I've handled those.
You can call this function like this:
createOffer($account_id, $subject, $offerlanguage, $totalamount, $date_submission, $date_decision, $date_start, $assigned_user_id, $quotestage, $winningchance, $description, $productarray)
Then you need to add the products too, which I've found the easiest via a separate function as there can be more products per quote...
<?php
function createProducts($productarray,$id) {
$counter = 1;
foreach ($productarray as $prod) {
$query ="insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice) values(?,?,?,?,?)";
$qparams = array($id,$prod['prod'],$counter,$prod['pcs'],$prod['price']);
$productadded=$adb->pquery($query,$qparams);
$counter=$counter+1;
}
}
use it like this:
$prodlist = array();
array_push($prodlist,array('prod'=>"prod1",'pcs'=>2,'price'=>1000));
array_push($prodlist,array('prod'=>"prod2",'pcs'=>2,'price'=>100));
createProducts($prodlist,10);
so my logic is like this:
you create the quote with the createOffer function. It returns with the newly created quote's ID
then you build the array of products (I have just the very basic data here) and add that by referencing the quote's ID
Maybe not the most beautiful solution but works.
Maybe you can start like this (according to your reference link).
Manual: https://wiki.vtiger.com/archives/index.php/vtiger510:Webservice_reference_manual
Login: https://wiki.vtiger.com/archives/index.php/vtiger510:Webservice_reference_manual#Login
Pseudo;
<?php
class VTiger_Login
{
private $serviceURL = 'http://vtiger_url/webservice.php?operation=login&username=%s&accessKey=%s';
// A Vtiger username.
private $userName = 'my_username';
// An md5 of the concatenation of the challenge token and the user's webservice access key.
private accessKey = 'my_accesskey';
public function login() {
// Open CURL
$ch = curl_init();
// Set URL as same as on manual
curl_setopt($ch, CURLOPT_URL, sprintf($this->serviceURL, $this->userName, $this->accessKey));
// Need POST according to manual
curl_setopt($ch, CURLOPT_POST, 1);
// Receive server response = TRUE
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Exec CURL
$result = curl_exec($ch);
// Close CURL
curl_close($ch);
/*
$result should be like this according to manual;
LoginResult {
sessionId: String // Unique Identifier for the session
userId: String // The vtiger id for the logged in user
version: String // The version of the webservices api
vtigerVersion: String // The version of the vtiger crm.
}
*/
// From manual: All structural data including response from the api is represented as JSON strings.
$result =# json_decode($result);
// See "Response" on manual
if (null === $result) {
throw new Exception('No response returned from Vtiger server!');
}
// See "ErrorObject" on manual
if (null !== $result->success && false === $result->success) {
throw new Exception('Something went wrong with login operation! errorCode: '.
$result->errorCode .', errorMessage: '. $result->errorMessage);
}
// I think, there is no problem anymore, go with $result after this line...
}
}

retrieve Json information from php file using cURL

ive seen lots of examples and to be honest i am a little confused on the matter.
I have been doing php for only 3 weeks so i am very new to this.
Basically i have wrote a function that asks for a token and a url, then it checks the database to if is exists, if it exists it then will offer a json array. I was wondering how select file and enter the function and retrieve the json data using cURL.
The function i have created is within the http://www.domain.com/api.php
Here is the function code:
function check_api_website($token, $url){
$token = trim(htmlentities($token));
$safetoken = mysql_real_escape_string($token);
$url = trim(htmlentities($url));
$safeurl = mysql_real_escape_string($url);
$checkwebsite = "SELECT message,islive FROM websitetokens WHERE url='".$safeurl."' AND token='".$safetoken."'";
$checkwebsite_result = mysql_query($checkwebsite) OR die();
$numberofrows = mysql_num_rows($checkwebsite_result);
if($numberofrows > 0){
$website = mysql_fetch_array($checkwebsite_result);
$message = stripslashes($website["message"]);
$islive = stripslashes($website["islive"]);
json_encode(array(
'message' => $message,
'islive' => $islive,
));
$date = date('Y-m-d');
$time = gmdate('H:i');
$loginwebsite = "UPDATE websitetokens SET loggedin='".$date."',time='".$time."' WHERE url='".$safeurl."' AND token='".$safetoken."'";
$loginwebsite_result = mysql_query($loginwebsite) OR die();
} else {
json_encode(array(
'message' => '',
'islive' => '1',
));
}
}
As you can see the json_encode is there and that is what i am wanting to retrieve.
If you could please explain a little also would help my learning.
Thanks for the help in advance :)
A simple request with cUrl to retrieve and parse JSON data would look like this:
function get_json($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($resultCode == 200) {
return json_decode($data);
} else {
return false;
}
}
You can place this method in your code and simply call it like this:
$json = get_json('http://www.example.com');
Good to see you're aware SQL injections and escaping the input. However, some PHP configurations might have the so called 'magic quotes' enabled, which escapes quotes on any input parameters with slashes.
If those slashes aren't stripped before calling mysql_real_escape_string, the resulting string will be double escaped. You can use a method like this to make sure everything gets escaped properly:
function escape_string($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return mysql_real_escape_string($string);
}

Categories