I have this code:
<?php
define('ga_email', 'xxxxxxxxx#xxxxx.com'); // GA Email
define('ga_password', 'xxxxxxxxxxx'); // 2-part authorization password
define('profile_id', 'xxxxxxxxx'); // Analytics profile ID
$gapi_url = 'gapi/gapi.class.php';
require_once $gapi_url;
$ga = new gapi(ga_email,ga_password);
// here goes next code
?>
and it's ok. Gapi will load.
However, if I change ga_password from xxxxxxxxxxx to yyyyyyyyyyy (so the information for logging into GA are incorrect) I get a nasty error, that gapi is not loaded etc.
I need some if condition to implement so it checks if my object $ga was created or not and execte a code only then.
e.g.:
<?php
define('ga_email', 'xxxxxxxxx#xxxxx.com'); // GA Email
define('ga_password', 'yyyyyyyyyyyyyy'); // 2-part authorization password
define('profile_id', 'xxxxxxxxx'); // Analytics profile ID
$gapi_url = 'gapi/gapi.class.php';
require_once $gapi_url;
$ga = new gapi(ga_email,ga_password);
if($ga loaded) {
// SUCCESS
// here goes next code
} else {
// FAILURE
echo "Your connection details are wrong.";
}
?>
So, instead a bad looking PHP error I will get a nicer "Your connection details are wrong."message.
After looking at the source of the class, it appears that the constructor will not throw an exception when the error details are wrong, but only when the credentials are used. Wrapping all your calls to the object in a try...catch block will give you some error handling capabilities:
try {
$ga = new gapi(ga_email,ga_password);
// here goes next code
} catch (Exception $ex) {
// FAILURE
echo "Your connection details are wrong.";
// $ex->getMessage() has a detailed message
}
You also need to ensure you know the correct signature of the constructor method, which appears to be the following:
public function __construct($auth_method)
On your __construct() of gapi check if the username and password is valid. Also create another public function or variable to return whether it is a valid login or not.
Related
I am using AWS to send emails in my project.. I created subscription and done all the steps. Its sending emails to the user but the notification is not receiving.. it says notification failed. I don't know the reason.. but I am getting notifications if I use http url instead https url.
The php code I am using is added below -
<?php
require 'path/to/vendor/autoload.php';
use AwsSnsMessageValidatorMessage;
use AwsSnsMessageValidatorMessageValidator;
use GuzzleHttpClient;
// Make sure the request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die;
}
try {
// Create a message from the post data and validate its signature
$message = Message::fromRawPostData();
$validator = new MessageValidator();
$validator->validate($message);
} catch (Exception $e) {
// Pretend we're not here if the message is invalid
http_response_code(404);
die;
}
if ($message->get('Type') === 'SubscriptionConfirmation') {
// Send a request to the SubscribeURL to complete subscription
(new Client)->get($message->get('SubscribeURL'))->send();
} elseif ($message->get('Type') === 'Notification') {
// Do something with the notification
save_message_to_database($message);
}
I am following the AWS documentation. Do you know the reason.. is there any issue in this code?
I am implementing twilio outgoing call with wordpress woocommerce. As soon as the order is placed the site owner will receive a call. However i couldn't find a way to handle if the person didn't answer the call for some reason. The documentation is going above my head.
What i want is to make twilio recall if the call isn't answered. Or i am open to suggestion how else would be the good way to handle. Please note that i have not created any application at Twilio yet. Just using the PHP SDK as the account id and token is provided by default.
here is the code
function send_order_Call($order_id) {
try {
$file = plugin_dir_path(__FILE__) . "order.xml";
$twiML = simplexml_load_file($file);
$twiML->Say = "Hello, You have received a new order. The order id is {$order_id}. Kindly check you fax for details";
file_put_contents($file, $twiML->asXML());
require_once 'Twilio.php';
//Initializing Twilio Rest
$sid = "ACcbd06f8e73asdfsdaf1";
$token = "32ccf4bdcasdfsafc";
$client = new Services_Twilio($sid, $token);
$call = $client->account->calls->create("+12asfsaf", "+1ssd8777asfsf7", site_url()."/wp-content/plugins/woocommerce-twilio/order.xml", array());
// echo $call->sid;
} catch (Exception $e){
$error = $e->getMessage();
die($error);
}
}
TL;DR; You need to set the statusCallBack parameter for the options array.
Please see https://stackoverflow.com/a/24482140/1751451
I have a class in PHP called cUser:
class cUser {
var $m_email;//The users email adresse(String)
var $m_password;//His password(String)
var $m_username;//His username(String)
var $m_active;//If the user have been activate (By following a link send to him via is email)(Bool)
function __construct($p_username, $p_password, $p_email, $p_active) {
$this->m_username = $p_username;
$this->m_password = $p_password;
$this->m_email = $p_email;
$this->m_active = $p_active;
}
//this is the important part...
function connexion() {
include "Config.php";//include all the parameters needed to connect to the DB
$cn = new cConnexion($ConnexionDBHost, $ConnexionDBName, $ConnexionDBLogin, $ConnexionDBPassword);//Initiate a connection to the DB
if($cn->DBConnexion())//If it is connected {
$parameters = array('username'=>$this->getUsername(), 'password'=>$this->getPassword());//create an array with the username and the password
$getConnexion = $cn->SecureSelect("SELECT username, password, email, active FROM user WHERE BINARY username = :username AND BINARY password = :password", $parameters);//selecte the user in the DB (for DB description see below code)
if($getConnexion != null) { //if there is no error in the query.
$resultSet = $getConnexion->fetch();//fetch the results
if($resultSet != null) { //if there is a match
//assigne the DB field values to this instance of cUser
$this->setUsername($resultSet['username']);
$this->setPassword($resultSet['password']);
$this->setEmail($resultSet['email']);
$this->setActive($resultSet['active']);
if($this->getActive() == 1) {
//If the user has been activate already return success
}
else {
//Else send an activation email to the user.Dont connecte him and return an error message
}
}
else {
//Send an error message
}
}
else {
//send an error message
}
}
else {
//send an error message
}
}
//this are not important for the question but I put them there so you can see what kind of operation the class is doing.
function delete(){//Delete this instance of cUser from de DB}
function insert(){//Insert this instance of cUser from the DB}
function update($p_email, $p_username, ...){//Update this instance of cUser with the new parameters}
function activateAccount(){//Activate this instance of cUser}
//And all the getters and setters associate with the class attributes.
}
Here is the MySQL Table containing the field for the cUser class (roughly coded):
USER
varchar email,
varchar password,
varchar username,
tiny int activate,//1 or 0
tiny int connected//1 or 0
Question:
How can I implement or change the function connection so one instance of a user is connected at the same time?
Note:
I already know I can just check if the DB connected field is set to 1 but if two user access the DB at the same time it would create a problem (race condition or something like that).
Is there something like a mutex or semaphore I can use to sync the access of the DB field connected??
Example:
David fill the HTML form and submit it with user name and password ("Dav1", "ThisIsPassword"), a process page create the cUser instance and connect to check if Dav1 already existe then give him access to the rest of the web-app.
Now Davos fill the form and submits it with the same user-name and password that David used because Davos and David are friend and they shared the same account and shared there password.
With the existing code both David and Davos can then access the web application at the same time with the same account what I want is that when David connect Davos get an error message that tell him that the user is either already connected or the user-name/password doesn't match.
Use a transaction.
In MySql you can also use SELECT FOR UPDATE statement.
Pseudocode:
$transaction = db->beginTransaction();
try {
$user = User::getByUsername($username);
if ($passwordImcorrect)
throw new Exception('invalid credentials');
if (user->loggedIn)
throw new Exception('already logged in');
user->loggedIn = 1;
user->save();
$transaction->commit();
}
catch (Exception $e) {
echo $e->getMessage();
$transaction->rollback();
}
I am working with both the Facebook PHP SDK and the Facebook JS SDK (using the JS SDK to handle login only, much as is discussed here: https://developers.facebook.com/blog/post/534/).
I have a custom button that I have created and attached to the FB.login() function. My goal is to have the text inside that button say "Log in with Facebook" if the user is not logged in, and to the text inside the button display the user's name if they are logged in.
The problem is that when I try to refer to the $user_profile variable that has the logged in user's information, it works when I use it outside the button, but says that the variable is not set when it is used inside the button (code below). What could be causing this?
<?php
// Get the contents of static-head.html to open the HTML doc:
readfile("static-head.html");
// Include the Facebook PHP SDK so that we can have people login
require_once('fb/facebook.php');
$config = array(
'appId' => 'MY_APP_ID',
'secret' => 'MY_APP_SECRET',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
// Get Facebook Login information
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user_profile = $facebook->api('/me','GET');
// If this doesn't throw an error, we now we have a $user_profile that we can use
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll just wait for the user to log in.
error_log($e->getType());
error_log($e->getMessage());
// Set the $user_id to NULL so that there's no confusion elsewhere in the app.
$user_id = NULL;
}
} else {
// Let the user log in through the JavaScript SDK
}
// Just to prove that $user_profile is being recognized:
// ***This works! It returns "Chris"
echo $user_profile['first_name'];
// Function to set the text inside the LogIn/LogOut button:
// ***This doesn't work! It returns "Log in with Facebook"
function getLogInLogOutText(){
if(isset($user_profile)){
return $user_profile['first_name'];
} else{
return 'Log in with Facebook';
}
}
?>
<div id="userLogInLogOut" class="uiControlsDivs">
<button id="userLogInLogOutButton"><?php echo getLogInLogOutText(); ?></button>
</div>
I am utterly confused how this is possible. On one line, the code works and returns the Facebook user's name. Then, just a few lines later, it doesn't work! What is going on?!
Thanks for any help you might be able to provide!
Try parsing the variable to the function, so say make the function:
function getLogInOutText() { ...
into
function getLogInOutText($user_profile) { ...
and call with with that, i.e. :
<?php echo getLogInOutText($user_profile); ?>
Not sure it will work, but it's worth a test. Otherwise try making it a global variable:
PHP reference for variables scope - http://www.php.net/manual/en/language.variables.scope.php
I've been searching this site for the answer for a while and I haven't been able to find one for this problem so I'm hoping someone can give me a hand. I'm not exactly an experience PHP programmer so there could be something severely wrong with what I'm doing.
Anyways I am working with another developer who doesn't code in PHP at all and needs access to Facebook information. That being said I'm trying to develop a facebook class which encapsulates all of the Facebook graph calls, allowing for my buddy to call a single function and get all of the information he needs without having to worry about any of the Facebook PHP SDK functions at all. This class I've put in a separate file called CFacebook.php. The code for this class can be found below (I've simply copied the example off of the facebook website)
<?php
require_once 'facebook.php';
class CFacebook
{
//private variables
private $Config = "";
private $FBObject = "";
private $Code = "";
private $Session = "";
private $AppId = '*************';
private $ApiSecret = '*******************';
//I have the API secret and AppID in
//here but for privacy reasons I've taken them out
//constructor
public function CFacebook()
{
$this->FBObject = new Facebook();
$this->FBObject->setApiSecret($this->ApiSecret);
$this->FBObject->setAppId($this->AppId);
}
//Get profile information
public function GetFBProfileInformation()
{
$FBProfile = "";
$ID = $this->FBObject->getUser();
echo "<br />";
if($ID)
{
try {
$FBProfile = $this->FBObject->api('/me','GET');
return $FBProfile;
}catch (FacebookApiException $e)
{
//send back to UI to have user sign in
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
echo "has ID <br />";
$login_url = $this->FBObject->getLoginUrl();
echo 'Please login.';
echo $this->FBObject->getAccessToken()."<br />";
echo $this->FBObject->getApiSecret()."<br />";
error_log($e->getType());
error_log($e->getMessage());
}
}else
{
//return to UI taht user isn't logged in and have user re-sign in
//If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$Page = "http://fratlabs.com/FacebookTest.php";
$login_url = $this->FBObject->getLoginUrl(array('scope'=>'email,publish_stream,user_likes,user_hometown','redirect_uri'=>$Page));
//$logout_url = $this->FBObject->getLogoutUrl(array('next'=>'http://fratlabs.com/FacebookTest.php'));
echo 'Please login.';
//echo 'Logout Url: Logout';
error_log($e->getType());
error_log($e->getMessage());
}
//echo $this->FBObject->getLogoutUrl(array('next'=>'http://fratlabs.com/FacebookTest.php'));
}
};
?>
This class is included and instantiated in a test page which is where the Facebook login is returned too. Maybe I need to include all of these calls in the same page as the one the facebook login is returned to? The only thing that is confusing me is that once every blue moon the code will work and I will actually create a link to Facebook, but every other time I'm left staring at the login page with the "please login" link on it.
While I am not a php expert myself, I believe it is advised to use try/catch objects for catching exceptions usually as message output not as a logic operator (like if/else) with well-defined pathways of the script like you seem to do. Consider a different approach like initializing the fb session and authenticating the user in the first class and presenting the user information in a second class. But for your partner who only wants fb user info, a message can be delivered in second class if user did not successfully login or authenticate.
For illustration (without functions), I use the code included here.