I an using this code in laravel 5.3 for sending email. But it says undefined variable $email, while i have defined the variable already.
This is my code.
$user->save();
if (!empty($user->save())) {
$email = 'ppriyadarshi49#gmail.com';
$mail = Mail::send('email_page', ['verification_key' => $verification_code], function($message) {
$message->from('prince.priyadarshi#fluper.com', 'Verify');
$message->to($email)
->subject('Verify your email address');
});
return view('for_company');
}
And the error is Undefined variable: email
Your are missing use() in closure function as:
$user->save();
if (!empty($user->save())) {
$email = 'ppriyadarshi49#gmail.com';
$mail = Mail::send('email_page', ['verification_key' => $verification_code], function($message) use($email) {
$message->from('prince.priyadarshi#fluper.com', 'Verify');
$message->to($email)
->subject('Verify your email address');
});
return view('for_company');
}
Related
I'll try to explain my problem.
I have recently started a new projet and wanted to implement a reset password functionnality.
Everything seems to work except the generation of the url which is send by email.
picture of my URL
My URL should look like this : http://localhost/projectName/public/reset-password/reset/xOdfPc0iGC7nmReqX02jcemgX4EIlt2tb5vNYgTZ
But the "/projectName/public/" is missing.
I don't understand what i did wrong.
Here is my twig template for the email :
<h1>Bonjour !</h1>
<p>Pour réinitialiser votre mot de passe, merci de vous rendre sur le lien suivant</p>
{{ url('app_reset_password', { token: resetToken.token }) }}
<p>Ce lien expirera dans {{ resetToken.expirationMessageKey|trans(resetToken.expirationMessageData, 'ResetPasswordBundle') }}.</p>
<p>A bientôt !</p>
Here is the function in the controller that generates the templated email :
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse
{
$user = $this->entityManager->getRepository(User::class)->findOneBy([
'email' => $emailFormData,
]);
// Do not reveal whether a user account was found or not.
if (!$user) {
return $this->redirectToRoute('app_check_email');
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
// If you want to tell the user why a reset email was not sent, uncomment
// the lines below and change the redirect to 'app_forgot_password_request'.
// Caution: This may reveal if a user is registered or not.
//
// $this->addFlash('reset_password_error', sprintf(
// '%s - %s',
// $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
// $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
// ));
return $this->redirectToRoute('app_check_email');
}
$email = (new TemplatedEmail())
->from(new Address('assistance#asintel.com', 'AS Intel - Assistance'))
->to($user->getEmail())
->subject('Your password reset request')
->htmlTemplate('reset_password/email.html.twig')
->context([
'resetToken' => $resetToken,
])
;
$mailer->send($email);
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
return $this->redirectToRoute('app_check_email');
}
And this is the function with app_reset_password route :
/**
* Validates and process the reset URL that the user clicked in their email.
*
* #Route("/reset/{token}", name="app_reset_password")
*/
public function reset(Request $request, UserPasswordHasherInterface $userPasswordHasher, TranslatorInterface $translator, string $token = null): Response
{
if ($token) {
// We store the token in session and remove it from the URL, to avoid the URL being
// loaded in a browser and potentially leaking the token to 3rd party JavaScript.
$this->storeTokenInSession($token);
return $this->redirectToRoute('app_reset_password');
}
$token = $this->getTokenFromSession();
if (null === $token) {
throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
}
try {
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash('reset_password_error', sprintf(
'%s - %s',
$translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
$translator->trans($e->getReason(), [], 'ResetPasswordBundle')
));
return $this->redirectToRoute('app_forgot_password_request');
}
// The token is valid; allow the user to change their password.
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// A password reset token should be used only once, remove it.
$this->resetPasswordHelper->removeResetRequest($token);
// Encode(hash) the plain password, and set it.
$encodedPassword = $userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
);
$user->setPassword($encodedPassword);
$this->entityManager->flush();
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
return $this->redirectToRoute('main_index');
}
return $this->render('reset_password/reset.html.twig', [
'resetForm' => $form->createView(),
]);
}
Does someone have an idea what i should do to fix this problem ?
Thanks a lot
Im working with laravel 5.3. In that i have mail functionality the variable get after the mail function is not working, below is my controller coding
public function checkEmail(Request $request) {
$email = $request->input('email');
$users = Student::where('email', $email)->select('email')->first();
if(count($users) > 0){
$id =Student::where('email',$email )->value('id');
$url=url('/').'/password-reset/'.$id;
Mail::send('/resetpassword', ['email'=>$email,'url'=>$url ], function($message)
{
$message->to(Input::get('email'))->subject('Reset Password');
});
return redirect()->back()->with('message', 'Link has been sent to your Mail');
} else {
return redirect()->back()->with(['message' => 'No Records Found']);
}
}
I got all the variable values before mail function (i.e.,)
Mail::send('/resetpassword', ['email'=>$email,'url'=>$url ], function($message)
{
$message->to(Input::get('email'))->subject('Reset Password');
});
I got error like this
Class 'App\Http\Controllers\Input' not found
if i use any variable the error is like this
Undefined Variable:url
Please anyone tellme what i did wrong...
i want to make WordPress plugin or if already exists please tell me
i want if user post 15 post on my WordPress site publish post to his Facebook wall with images and level and more than posts with another level
login to WordPress throw Facebook
save the access token to use it to publish offline
on save posts if equal certain number publish the post to user
time line
i do first step and this images the result
but no thing published to timeline and the code is
<?php
session_start();
require_once 'facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxx',
'app_secret' => 'xxxxxxxxx',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/xxxxxxx/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// posting on user timeline using publish_actins permission
try {
// message must come from the user-end
$data = ['message' => 'testing...'];
$request = $fb->post('/me/feed', $data);
$response = $request->getGraphEdge()->asArray;
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo $response['id'];
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
//$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/xxxxxxxx/', $permissions);
$loginUrl = $helper->getLoginUrl("http://www.xxxxxx.com/facebook/index.php",$permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
help :)
i used this tutorial to solve some steps
https://www.youtube.com/watch?v=XYawdJh_mNQ
My Contact Form 7 in some period of time doesn't work in other works fine.
I am getting message:
Failed to send your message. Please try later or contact the administrator by another method
I tried to debug this and found that CF7 will call wp_mail.
It will call this code from Contact Form 7:
if ( $send ) {
return #wp_mail( $recipient, $subject, $body, $headers, $attachments );
}
But this will return false.
Hase anyone some idea what can be problem.
EDIT:
When it call wp_mail it will throw error in this part of wordpress code:
if (!$this->smtp->data($header . $body)) {
throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
}
EDIT:
This data function will at the first line will call function "sendComand":
public function data($msg_data)
{
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
.....
It will failm in this if statment.
Here is sendCommand function:
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->error = array(
"error" => "Called $command without being connected"
);
return false;
}
$this->client_send($commandstring . self::CRLF);
$reply = $this->get_lines();
$code = substr($reply, 0, 3);
if ($this->do_debug >= 2) {
$this->edebug('SMTP -> FROM SERVER:' . $reply);
}
if (!in_array($code, (array)$expect)) {
$this->last_reply = null;
$this->error = array(
"error" => "$command command failed",
"smtp_code" => $code,
"detail" => substr($reply, 4)
);
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP -> ERROR: ' . $this->error['error'] . ': ' . $reply
);
}
return false;
}.......
and this will fail in this last if statment, this condition in if (!in_array($code, (array)$expect)) will be true.
So $expect was provided on sendCommand function call:
$this->sendCommand('DATA', 'DATA', 354)
(array)$expect) == Array([0] => 354)
and $code we will get from get_lines() function:
$reply = $this->get_lines();
$code = substr($reply, 0, 3);
When it fail in $reply is next value:
$reply = 550 5.4.5 Daily sending quota exceeded. u1sm14669850qat.27 - gsmtp
And here is get_lines() source:
https://github.com/WordPress/WordPress/blob/master/wp-includes/class-smtp.php#L820
I've had this issue before and resolved it by switching to gmail's smtp by using this plugin:
https://wordpress.org/plugins/wp-mail-smtp/faq/
All you need to set it up is a gmail account, if this is a client/work website, you can create a free account with gmail and simply enter it in the plugin settings.
I was looking for docs on official page but there is no anything helpful, so i build this code and it don't work.
FacebookSession::setDefaultApplication('app-id', 'app-secret');
$helper = new \Facebook\FacebookRedirectLoginHelper('http://my-return-url');
if (isset($_SESSION['token'])) {
$session = new FacebookSession($_SESSION['token']);
if (!$session->validate()) {
$session = null;
}
} else {
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
die("Oops! :/");
} catch(Exception $ex) {
die($ex->message());
}
}
if (isset($session)) {
$_SESSION['token'] = $session->getToken();
$session = new FacebookSession($session->getToken());
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
echo '<pre>';
print_r($graphObject);
echo '</pre>';
} else {
echo 'Login';
}
I think the problem is in SDK but i'm not sure. I always get this error:
Fatal error: Uncaught exception 'Facebook\FacebookSDKException' with message 'Session has expired, or is not valid for this app.' in /var/www/html/Facebook/FacebookSession.php:238 Stack trace: #0 /var/www/html/Facebook/FacebookSession.php(216): Facebook\FacebookSession::validateSessionInfo(Object(Facebook\GraphSessionInfo), 'my-app-id', 'app-secret...') #1 /var/www/html/verify.php(98): Facebook\FacebookSession->validate() #2 {main} thrown in /var/www/html/Facebook/FacebookSession.php on line 238
I also tried through incognito mode tried setting up new app but always i get this error.
I agree, FB documentations are pretty bad. Also, they are frequently changing thier SDK versions, a few days back they release v 4.0.5. Try this ->
<?php
// include required files form Facebook SDK
// added in v4.0.5
require_once( 'Facebook/FacebookHttpable.php' );
require_once( 'Facebook/FacebookCurl.php' );
require_once( 'Facebook/FacebookCurlHttpClient.php' );
// added in v4.0.0
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookOtherException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphSessionInfo.php' );
// added in v4.0.5
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
// added in v4.0.0
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxx','yyy' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://yourwebsite.com/app/' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} else {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
echo $ex->message;
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
Source
Steps to avoiding PHP facebook SDK 4.0 login error
First install composer in your PC if your are using windows OS.
Download facebook SDK 4.0 and rename what ever you want (Like: fbsdk).
Run Command prompt and locate your recently downloaded sdk folder.
Check if there are composer.json file exist or not
if composer.json file exist then type this command:
composer install otherwise you have create new file composer.json in same folder with following code: {
"require" : {
"facebook/php-sdk-v4" : "4.0.*"
}
}
If you will type correct command as above mentioned in line number 5 then you will get this message : Loading composer repositories with package information Installing dependencies (including require-dev).
Create index.php file and include autoload.php top of the file.
For example follow the sample codes for login with facebook
session_start();
require_once('/home3/users/public_html/fbsdk/vendor/autoload.php');
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
FacebookSession::setDefaultApplication(YOUR APP_ID, YOUR SECRET_KEY);
$helper = new FacebookRedirectLoginHelper('http://example.com/fbsdk/login.php');
if(isset($_SESSION['access_token'])) {
$access_token = $_SESSION['access_token'];
$session = new FacebookSession($access_token);
} else {
unset($_SESSION['access_token']);
try {
$session = $helper->getSessionFromRedirect();
if($session)
$_SESSION['access_token'] = $session->getToken();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(Exception $ex) {
// When validation fails or other local issues
}
}
if ($session) {
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
header('Location: ./home.php');
} else {
$loginUrl = $helper->getLoginUrl();
header('Location: ' . $loginUrl);
}