Php curl showing empty string after data - php

Ive got this little snippet that I use to get data about what players are online in my server. The data displays correctly, I just have 1 extra empty row being echoed.
<?php
$id = ***; //service ID
$api_key = '***'; //CBSM API key
$act = 5; //action #5 indicates retrieval of online players
$response = null;
$ch = curl_init('https://api.envul.com/?s='.$id.'&api='.$api_key.'&act='.$act);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response !== false) {
$response_data = explode("<hr>", $response); //process the data
foreach($response_data as $player_data)
{ // listing of players
$player_data = explode("{#!}", $player_data); //process the data
echo 'Username: '.$player_data[0].'<br>';
} //end listing of players
} else {
echo 'Error '.curl_error($ch);;
}
?>
Ive looked at countless posts on here and other sites about this issue with both curl, and file_get_contents.
Both methods return an empty string with and without actual data to display.

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.

Submit POST data in loop without cURL and get response data - CodeIgniter

I have a code that sends SMS to customers that is set up as cron job. My problem is, when I use cURL, it's sending 2-part messages and our wallet is being charged twice. We have an average of 500 messages to send per day. My goal is to make the message 1-part only.
So I'm trying to find the best way to send messages in loop without using cURL.
I have thought of saving the post data from the loop in an array and send it to my view. Then when the view is called, I will automatically send the form withouth hitting the submit button and using javascript to auto submit. After the view is called, I will use file_get_contents() to get the response from the URL. But I cant make it work:
The view is not working inside the loop. It just works outside the loop.
If I pass the loop inside the view and not in the controller, how can I get the response data each loop?
My current code in CURL:
public function send_sms_globe(){
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
//get all data from the database pull with status = queue
$globe_data = $this->New_Sms_Api_model->get_queued_data('globe_api');
$passphrase = '[our_pass_phrase]';
$app_id = '[our_app_id]';
$app_secret = '[our_app_secret]';
$url = 'https://devapi.globelabs.com.ph/smsmessaging/v1/outbound/<our_shortcode>/requests/';
$ch = curl_init($url);
$limit = 0;
foreach($globe_data AS $records_data){
if($limit == 49){
break;
}
switch($limit) {
case 49:
$limit = 0;
break;
default:
if($records_data['Remarks'] == 'LOADED'){
if($records_data['sent_to'] == 'sender'){
$address = $records_data['sender_phone_number'];
}else if($records_data['sent_to'] == 'consignee'){
$address = $records_data['consignee_phone_number'];
}
} else {
$address = $records_data['sender_phone_number'];
}
//$address = '+63917*******';//address : *subscriber number $records_data['phone_number'];
$message = (isset($records_data['Message']) && $records_data['Message'] != '') ? $records_data['Message']:''; //message : *sms content
$str = iconv('UTF-8', 'ASCII//IGNORE//TRANSLIT', $message);
$post_data = [
'app_id' => $app_id,
'app_secret' => $app_secret,
'passphrase' => $passphrase,
'message' => rawurlencode($str),
'address' => $address
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute!
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$queue_id = $records_data['ID'];
$invoice_number = $records_data['InvoicecNumber'];
$status_remark = $records_data['Remarks'];
$record_id = $records_data['record_id'];
if($http_code == 201 || $http_code == 200){
$no_of_tries = $records_data['no_of_tries'];
if($no_of_tries == 0){
$no_of_tries = 1;
} else {
$no_of_tries = $records_data['no_of_tries'];
}
$status = 'sent';
$retry = 0;
} else {
$no_of_tries = $records_data['no_of_tries'] + 1;
if($no_of_tries == 3){
$status = 'failed';
$retry = 0;
} else {
$status = 'retry';
$retry = 1;
}
}
$update_queued_data = $this->New_Sms_Api_model->update_queued_data($queue_id, $invoice_number, $status, $retry, $no_of_tries);
if($update_queued_data){
if($status == 'sent'){
if($status_remark == 'LOADED'){
$sent_to = $records_data['sent_to'];
} else {
$sent_to = NULL;
}
$this->New_Sms_Api_model->save_to_cq_sms($invoice_number, $status_remark, $record_id,$sent_to);
echo $records_data['record_id'].' ---- '.$status;
}
$limit++;
}
}
}
// close the connection, release resources used
curl_close($ch);
}
We have a message with 157 characters (160 max). I already talked to the API support we're using. First they suggested to format my message as URL encoding, and so I did. So from 3-part message it became 2-part. And then they said it will send as 2-part even if it's formatted that way because we use cURL. They suggested that we use PostMan but it's not for free so it's not an option.
Any ideas that can replace my current code? Thanks!
Sorry for the confusion. I was able to fix the issue without changing all of my code. I just removed rawurlencode in my string message and it's sending a 1-part message now.
Maybe using $str = iconv('UTF-8', 'ASCII//IGNORE//TRANSLIT', $message); already did the trick and using rawurlencode after just added additional characters ex: %20.
Thanks everyone!

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...
}
}

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

PHP cURL - Sending array succeded but not entirely

I'm using CURL to post to a script hosted on a remote server.
I'm sending a multidimensional array using this:
$urlserver = "myserver";
$arraytag = array('tags'=>$taggenerici,'tagesplosi'=>$tagesplosi,'matrice'=>$matricefin,'id' =>$identificativo);
$postfields = http_build_query($arraytag);
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$urlserver);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_POST,sizeof($postfields));
curl_setopt($ch, CURLOPT_POSTFIELDS,$postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
//execute request sending post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
The problem is about the result: infact if i try to execute my script i get a randomic result. I'd like to view an array of 20rows X 43columns but it stops at row10 and column28. But if i refresh my page after some try i get my full array.
I'd like to say that i have tried to get the array before sending it to the remote server and it works fine cos i get my array entirely without any kind of cutting.
script being called (minus unused mysql connection):
<?php
$taggenerici = $_POST['tags'];
$matrice = $_POST['matrice'];
$identificativo = $_POST['id'];
$tagesplosi = $_POST['tagesplosi'];
//Here i create the array with "a" and "?"
for($dom=0;$dom<sizeof($identificativo);$dom++) {
for ($tag=0;$tag<sizeof($taggenerici);$tag++) {
$matrice[$dom][$tag] = "a, ";
}
$tagAdd=sizeof($taggenerici)+1;
$matrice[$dom][$tagAdd] ="?";
}
//Here i set "p".
for($dom=0;$dom<sizeof($identificativo);$dom++) {
for ($tag=0;$tag<sizeof($taggenerici);$tag++) {
for ($tagarray=0;$tagarray<sizeof($tagesplosi[$dom]);$tagarray++) {
if ($taggenerici[$tag] == $tagesplosi[$dom][$tagarray]) {
$matrice[$dom][$tag] = "p, ";
}
}
}
}
//this is the $result which I call on the client. (echo $valore);
foreach ($matrice as $kappa => $vu) {
echo "<br>";
foreach ($vu as $kii => $valore)
echo $valore;
}
}

Categories