This is my third day on PHP. I have the following code for selecting data-
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$sql = "SELECT LoginName FROM users WHERE LoginName = :LoginName";
$statement = $db->prepare($sql); //intentionally used $db here
$statement->bindParam(':LoginName', $LoginName, PDO::PARAM_STR, 50);
$statement->execute();
$count= $statement->rowCount();
}
catch(PDOException $e)
{
header('Content-Type: application/json');
echo json_encode(array('result'=>'Error','data'=> $e->getMessage()));
}
I intentionally used $db instead of $conn. So there supposed to be an exception. But in my ajax call, $e->getMessage() has not been sent from catch block.
Any help?
Here is how it have to be done
First, set this handler ho handle ALL errors that may occur in your script, be it PDO or anything else.
set_error_handler("myErrorHandler");
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
error_log("$errstr in $errfile:$errline");
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
header('Content-Type: application/json');
echo json_encode(array('result'=>'Error', 'data'=>'Server error'));
exit;
}
then make your PDO code this way
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT 1 FROM users WHERE LoginName = ?";
$statement = $db->prepare($sql); //intentionally used $db here
$statement->execute([$LoginName]);
$found = $statement->fetchColumn();
In essence, you should follow these rules:
never use try catch operator to report an error
never reveal a real error to an outsider. Just a generic message
Related
I am using the following script to connect to a remote SQL Server from my xaamp and it works but when I use the same script in my Godaddy plesk hosting, it's not working.
$conn = false;
try {
$conn = new PDO("sqlsrv:server = tcp:xx.xx.xx.xx\instancename; Database = dbname", "uname", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
catch (PDOException $e) {
print("Error connecting to SQL Server.");
die(print_r($e));
}
However, on my hosting, I can use this code to connect to local instance (using but if I change the credential and the hostname to the remote server, it's not working.
this works
$connectionInfo = array("UID" => "uname", "pwd" => "password", "Database" => "db_second");
$serverName = "tcp:blablabla.shr.prod.iad2.secureserver.net";
$conn = sqlsrv_connect($serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
but this doesn't
$connectionInfo = array("UID" => "uname", "pwd" => "password", "Database" => "dbname");
$serverName = "tcp:xx.xx.xx.xx\instancename";
$conn2 = sqlsrv_connect($serverName, $connectionInfo);
if ($conn2){
echo "cool" ;
}
if( $conn2 ) {
echo "Connection 2 established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
Please help me.
I am currently learning sql but I cannot get some things done like send a new data to the localhost when I am submiting data
$short_title=$_POST['short_title'];
$title=$_POST['title'];
$statement=$connection->prepare(
'INSERT INTO post (title,short_name) VALUES (:title,:short_name)');
$statement->execute(array(':title'=>$title,':short_name'=>$short_title));
Where is the db_connect file please?
And is the ID of the table in Auto-Increment?
Something seems wrong with your last line. Are you using PDO or MYSQLI?
Here is an example of a query and a db_connect file in PHP using PDO method
The db connect :
<?php
$db_username = "root";
$db_password = "";
$db_host = "localhost";
$db_name = "veterinaires";
$db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
try {
$db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8", $db_username, $db_password, $db_options);
} catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>
Model for insert in DB
<?php
/* Basic function */
$query = "INSERT INTO users (
ID,
password,
email,
role
) VALUES (
:ID,
:password,
:email,
:role)";
// Security measures
$query_params = array(
':ID' => NULL,
':password' => $password,
':email' => $email,
':role' => 'vet');
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$check = true;
}catch(PDOException $ex){
$errormsg = "Vous possédez déjà un compte!";
$check = false;
}
?>
I'm developing with localbitcoin API and i am using path “/api/dashboard/closed/” and this is my code:
<?php
function localbitcoinsquery($path, $nonce,array $req = Array()) {
global $random;
$key='mykey';
$secret='secretkey';
if ($req) {
$get=httpbuildquery($req);
$path=$path.'?'.$get;
}
$postdata=$nonce.$key.$path;
$sign = strtoupper(hashhmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curlinit('https://localbitcoins.com'.$path);
curlsetopt($ch, CURLOPTRETURNTRANSFER, true);
curlsetopt($ch, CURLOPTHTTPHEADER, $headers);
curlsetopt($ch, CURLOPTSSLVERIFYPEER, TRUE);
curlsetopt($ch, CURLOPTCONNECTTIMEOUT, 20);
$res = curlexec($ch);
if ($res === false) throw new Exception('Curl error: '.curlerror($ch));
$dec = jsondecode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}
$getinfo = array();
$url='/api/dashboard/closed/';
$mt = explode(' ', microtime());
$random = $mt[1].substr($mt[0], 2, 6);
$getinfo = localbitcoinsquery($url,$random);
echo "<pre>";
printr($getinfo);
echo "</pre>";
?>
This works OK, but show only 50 trades,
Also I get this at result:
[pagination] => Array
(
[next] => https://localbitcoins.com/api/dashboard/closed/?order_by=-closed_at&start_at=2017-10-26+17%3U50%3A49%2B00%9A00
)
But I don't know how to use pagination, when I try to use this link at my code I get error:
[message] => HMAC authentication key and signature was given, but they
are invalid. Error 41
I already investigated at google large time but the information is scarce.
I'm using the python library and had the same issue. When I spoke to technical support they said the issue was in the way I was calculating the authentication.
Basically you have to include the pagination url as part of the signature.
On the python library at least, you do not have to change the api endpoint since arguments are being delivered as part of the form data.
So you still access for example "/api/dashboard/closed/" when getting the second page and the "?order_by=-closed_at&start_at=2017-10-26+17%3U50%3A49%2B00%9A00" stuff goes in the form somehow.
The python API does all this for you, you just have to copy the example from the github page.
I fixed error no. 41. I modified your example to show that works, (read my NOTE: comments to understand better where is the problem) Read my NOTE: comments.
<?php
function localbitcoins_query($path, array $req = Array()) {
$key='yourkey';
$secret='yoursecret';
$array_mt = explode(' ', microtime());
$nonce = $array_mt[1].substr($array_mt[0], 2, 6);
$get = "";
if ($req) {
$get=http_build_query($req);
}
$postdata=$nonce.$key.$path.$get; // NOTE: here $postdata goes without '?' char before the parameters!
$sign = strtoupper(hash_hmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curl_init('https://localbitcoins.com'.$path.( $get=="" ? "" : "?".$get)); // NOTE: here it's necesary '?' char before the parameters!
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
$res = curl_exec($ch);
if ($res === false) throw new Exception('Curl error: '.curlerror($ch));
$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}
$getinfo = array();
$api_endpoint = '/api/dashboard/closed/';
$array_params = array( "order_by" => "-closed_at"
, "start_at" => "2019-08-14 18:00:26+00:00"
);
$getinfo = localbitcoins_query($api_endpoint,$array_params);
echo "<pre>"; print_r($getinfo); echo "</pre>";
?
I have an array of phone numbers which I am looping over and sending a text message to.
Occasionally a number may be invalid and an error is thrown from Twilio. I know I can comment out the echo in the catch but if an exception is still thrown I need to my loop to continue. Should I remove the try catch entirely?
foreach($filterphones as $key => $value){
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Services_Twilio($account_sid, $auth_token);
try {
$message = $client->account->messages->create(array(
'From' => "+16XXXXXXXXX",
'To' => $value,
'Body' => $body,
));
}catch (Services_Twilio_RestException $e) {
//echo $e->getMessage();
}
}
I had some really complicated code, and now I've made it ridiculously simple, and it doesn't work.
Currently it simply takes me back to the page with the login URL echoed out.
Code is here:
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'sd',
'secret' => 'sda',
));
// Get User ID
$user = $facebook->getUser();
if($user) {
echo $user;
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>'http://www.facebook.com/pages/CharlesTestPage/225802194155435?sk=app_252946408094785','scope'=>'email'));
echo $loginUrl;
}
exit;
?>
Please. I have spent a whole paid work day on this now, and am at the point of crying, not only for myself but for my boss.
Cry.
Edit: OK, the weird thing is, if I have the redirect_uri set to the facebook tab, if it's not authenticated itself, then it constantly redirects in an infinite loop. However, if I remove the redire
This is what's working for me using PHP SDK 3.1.1. Try it and let us know if this works:
include('facebook.php');
session_start();
//facebook application
$config['appid' ] = "YOUR_APP_ID";
$config['secret'] = "YOUR_APP_SECRET";
$config['baseurl'] = "http://example.com/facebookappdirectory";
$config['appbaseurl'] = "http://apps.facebook.com/your-app-name";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('APP ERROR: '.$e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if (isset($_GET['code'])){
header("Location: " . $config['appbaseurl']);
exit;
}
Check for
if(isset($_GET['code'])){
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
}
Facebook return userID only after the login and that code.