I have JSON-RPC handler function that handle objects like this:
class Service {
public function sqlite_query($token, $filename, $query) {
if (!$this->valid_token($token)) {
throw new Exception("Access Denied: Invalid Token");
}
$db = new SQLite($filename);
$res = $db->query($query);
if ($res) {
if (preg_match("/^\s*INSERT|UPDATE|DELETE|ALTER|CREATE/i", $query)) {
return $db->rowAffected();
} else {
return $res->fetchAll();
}
} else {
throw new Error("Coudn't open file");
}
}
}
SQLite is a class that call SQLite 2 or 3. The code catch all exceptions but when I try to execute invalid SQL I got not exception but php error handled by this code:
set_error_handler('error_handler');
ini_set('display_errors', 1);
ini_set('track_errors', 1);
ob_start();
function error_handler($err, $message, $file, $line) {
global $stop;
$stop = true;
$content = explode("\n", file_get_contents($file));
header('Content-Type: application/json');
$id = extract_id();
$error = array(
"code" => 100,
"message" => "Server error",
"error" => array(
"name" => "PHPErorr",
"code" => $err,
"message" => $message,
"file" => $file,
"at" => $line,
"line" => $content[$line-1]));
ob_end_clean();
echo response(null, $id, $error);
exit();
}
Is there a way to make SQLite throw exception?
Yes, use PHP's PDO to access SQLite3 (not the SQLite function). PDO is arguably the best and now standard and preferred way to access any database, including SQLite3. You can make PDO throw exceptions by specifying \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION when instantiating a PDO object.
Related
I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
I'm experimenting with SammyK/LaravelFacebookSdk.
Trying to run this line from example:
$response = Facebook::get('/me?fields=id,name,email', 'user-access-token');
which in turn runs /var/www/vendor/facebook/php-sdk-v4/src/Facebook/HttpClients/FacebookGuzzleHttpClient.php line 61
public function send($url, $method, $body, array $headers, $timeOut)
{
$options = [
'headers' => $headers,
'body' => $body,
'timeout' => $timeOut,
'connect_timeout' => 10,
'verify' => __DIR__ . '/certs/DigiCertHighAssuranceEVRootCA.pem',
];
$request = $this->guzzleClient->createRequest($method, $url, $options);
try {
$rawResponse = $this->guzzleClient->send($request);
} catch (RequestException $e) {
$rawResponse = $e->getResponse();
if ($e->getPrevious() instanceof RingException || !$rawResponse instanceof ResponseInterface) {
throw new FacebookSDKException($e->getMessage(), $e->getCode());
}
}
$rawHeaders = $this->getHeadersAsString($rawResponse);
$rawBody = $rawResponse->getBody();
$httpStatusCode = $rawResponse->getStatusCode();
return new GraphRawResponse($rawHeaders, $rawBody, $httpStatusCode);
}
That calls /var/www/vendor/guzzlehttp/guzzle/src/Client.php line 87
public function __call($method, $args)
{
if (count($args) < 1) {
throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
}
$uri = $args[0];
$opts = isset($args[1]) ? $args[1] : [];
return substr($method, -5) === 'Async'
? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
: $this->request($method, $uri, $opts);
}
This methond interprets input as array('method' => 'createRequest', 'uri' => 'GET'))
Changing index seems to correct the error (though other problems araise)
$uri = $args[1];
$opts = isset($args[2]) ? $args[2] : [];
But since it's a very bad practice to edit other packages, how should I correct this error?
I've get the same problem.
Changing indexes won't work for me, but I've found a workaround. Installing php-curl extension switches a whole workflow thru cURL, so the problem is vanished.
Due to Facebook SDK 5.x use guzzle version 5.
So downgrade the guzzle library will workaround
$ composer require guzzlehttp/guzzle:~5.0
I have developed a php web service on a server with mysql database connection. It can not connect to database and does not execute codes after database connection. Also it does not show any error.
If I return something before database connection line, it is returned.
I have tested another php file with database connection and it works properly.
<?php require_once('lib/nusoap.php');
$server = new soap_server();
$server->configureWSDL('ivrmci', 'urn:ivrmciwsdl');
$server->register('upload_file', // method
array('username' => 'xsd:string','password' => 'xsd:string','encoded_filepath' => 'xsd:string','filename' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmciwsdl', // namespace
'urn:ivrmciwsdl#upload_file', // soapaction
'rpc', // style
'encoded', // use
'Uploads files to the server' // documentation
);
$server->register('inquiryMsisdnCalls', // method
array('username' => 'xsd:string','password' => 'xsd:string','callerid' => 'xsd:string','advertise_id' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmci', // namespace
'urn:ivrmci#inquiryMsisdnCalls', // soapaction
'rpc',
'encoded', // style // use
'Returns User Log' // documentation
);
function upload_file($username,$password,$encoded,$name) {
if ($username != "abc" OR $password != "123")
{
return "-2";
}
$location = "uploads/".$name; // Mention where to upload the file
//$current = file_get_contents($location); // Get the file content. This will create an empty file if the file does not exist
$current = base64_decode($encoded); // Now decode the content which was sent by the client
file_put_contents($location, $current); // Write the decoded content in the file mentioned at particular location
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$filename = explode(".", $name);
$sql = "INSERT INTO advertise (name) VALUES ($filename[0])";
try{
$db->exec($sql);
return $db->lastInsertid();
}
catch(PDOException $e)
{
return $e->getMessage();
}
if($name!="")
{
return "File Uploaded successfully..."; // Output success message
}
else
{
return "Please upload a file...";
}
}
function inquiryMsisdnCalls($username,$password,$callerid,$contentid)
{
if ($username != "abc" OR $password != "123")
{
return "-2";
}
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$sql = "select status from user_advertise_log where callerId=$callerid and advertise_id=$contentid";
try{
$log = $db->query($sql)->fetch(PDO::FETCH_OBJ);
return $log->status;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I'm really stuck on this one. At the bottom of this post, I've attached the API documentation I'm working with. I want to catch the "message" when the response ("ask") isn't "Success". Seems reasonable enough, right? But when I do something like:
sfcSendError('Something went wrong. This is the message from the API: ' . $result->message);
I get a fatal error:
PHP Fatal error: Cannot access protected property SoapFault::$message
I found this seemingly related question on SO, so I tried changing "message" to "getMessage()" but (no surprise) that results in a different fatal error about calling an undefined function.
Here's my code snippet:
$client = mySoapClient(MODULE_SHIPPING_SFC_API_URL);
if (!$client) {
sfcSendError('could not make a SOAP connection. Halting until next CRON. [' . __FILE__ . ':' . __LINE__ . ']', 'SOAP Failure in cron job');
exit; //halt and wait for the next time cron runs
} else {
$HeaderRequest = array(
'customerId' => MODULE_SHIPPING_SFC_ACCOUNT,
'appToken' => MODULE_SHIPPING_SFC_TOKEN,
'appKey' => MODULE_SHIPPING_SFC_KEY
);
$reg = array(
'HeaderRequest' => $HeaderRequest,
'detailLevel' => 1,
'ordersCode' => $_query->fields['sfc_ordersCode']
);
$result = $client->getOrderByCode($reg);
if ($result->ask != "Success") {
sfcSendError('Something went wrong. This is the message from SFC: ' . $result->message, 'SOAP Failure in cron job');
$_query->MoveNext();
continue;
}
}
This is the referenced function:
function mySoapClient($url)
{
try {
$client = #new SoapClient($url, array(
'trace' => 1,
'exceptions' => 0,
'encoding' => 'UTF-8'
));
} catch (SoapFault $e) {
return 0;
}
return $client;
}
What am I doing wrong? Or is this a "bug" with the API where they really shouldn't be using "message" in their response?
I have the following code:
<?php
$consumer_key="C:\xampp\htdocs\consumer_key.php";
$access_token="C:\xampp\htdocs\access_token.php";
$api_url_base="C:\xampp\htdocs\api_url_base.php";
$error="C:\xampp\htdocs\error.php";
try {
$consumer_key="C:\xampp\htdocs\consumer_key.php";
$access_token="C:\xampp\htdocs\access_token.php";
$api_url_base="C:\xampp\htdocs\api_url_base.php";
$error="C:\xampp\htdocs\error.php";
include "oauth.php";
//***************************************************************************************************
$oauth = new oauth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1,
OAUTH_AUTH_TYPE_AUTHORIZATION);
//***************************************************************************************************
$oauth->enableDebug();
$oauth->setToken($access_token, $access_secret);
} catch(OAuthException $E) {
Error("setup exception", $E->getMessage(), null, null, $E->debugInfo);
}
try {
$api_url_base="C:\xampp\htdocs\api_url_base.php";
$error="C:\xampp\htdocs\error.php";
$filename = "www.sim3dmodel.com/example2.stl";//cube-1cm3-centered_in_meter.stl
$file = file_get_contents("../models/". $filename);
$data = array("fileName" => "$filename",
"file" => rawurlencode(base64_encode($file)),
"hasRightsToModel" => 1,
"acceptTermsAndConditions" => 1,
);
$data_string = json_encode($data);
$oauth->fetch($api_url_base ."/models/v1", $data_string, OAUTH_HTTP_METHOD_POST, array("Accept" => "application/json"));
$response = $oauth->getLastResponse();
$json = json_decode($response);
if (null == $json) {
PrintJsonLastError();
var_dump($response);
} else {
print_r($json);
}
} catch(OAuthException $E) {
Error("fetch exception", $E->getMessage(), null, $oauth->getLastResponseInfo(), $E->debugInfo);
}
?>
But I get the following error: Fatal error: Class 'oauth' not found in C:\xampp\htdocs\shapeway.php
If anyone could explain me why I get this error I would be very happy.
Insetead of:
$consumer_key = "C:\xampp\htdocs\consumer_key.php";
use:
include 'C:\xampp\htdocs\consumer_key.php';
If you have a variable $consumer_key in that file you are good to go. I have to say that you need to use a relative path to the file or it won't work. So something like include 'consumer_key.php';. If you need a file from a previous folder use include '../file.php';. Don't use \ backslashes for files this will fail. This also includes images etc. You need to do this for every file.