In this tutorial, you will implement forgotten password functionality to a login box. The overall goal here is for the user to enter there email address into a TextInput field and have a PHP service check the database for a match, then send the username and password for that user to the email address provided if it exists in the db. If no match is found, it will alert the user that there was no match found.
The first thing we are going to need is the PHP service that will handle the request from the client side.
NOTE: If you are using MAMP and not MAMP Pro, you will not be able to send emails. So to check this functionality, either test on another server or upgrade and configure your application for MAMP Pro.
<?
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="example12"; // Database name
//Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// value sent from form
$email_to = mysql_real_escape_string($_POST["email_to"]);
// table name
$tbl_name=users;
// retrieve password from table where e-mail = $email_to(mark@phpeasystep.com)
$sql="SELECT password FROM $tbl_name WHERE email='$email_to'";
$result=mysql_query($sql);
// If there is an email match, it must be in one single row, then keep the value in the variable "$count"
$count=mysql_num_rows($result);
// compare if $count =1 row
if($count==1){
$rows=mysql_fetch_array($result);
// keep password in $your_password
$your_password=$rows['password'];
// ---------------- SEND MAIL FORM ----------------
$to=$email_to; // Who the email will be sent to
$subject="Your Password"; // Email subject
$header="from: CreativeRIA <jeff@creativeria.com>"; // From is the email being sent from
$messages.="Your password is $your_password \r\n"; // What is body of the message?
$sentmail = mail($to,$subject,$messages,$header); // Send email
}
//start outputting the XML
$output = "<getPassword>";
//If an email was sent then output yes else output no
if($sentmail)
$output .= "yes";
else
$output .= "no";
$output .= "</getPassword>";
//output all the XML
print ($output);
?>
In English, this PHP code says: Take the “email_to” variable being passed by Flex and check the “users” table of the database and see if there is a match. If there is, then send an email to the user with their password and send a response of “yes” back to the client. If there is no match found, then send a “no” response to the client. The client side is then responsible for deciding what to do with the response.
Changes in FB4
Step 1. We need to write the function that will handle the “yes” or “no” from PHP – print ($output);
private function getPassword(event:ResultEvent):void
{
if(event.result.getPassword == "yes")
{
mx.controls.Alert.show('Your password has been emailed to you.');
currentState = "loggedOut";
}
else
{
mx.controls.Alert.show('Invalid email, please try again.');
}
}
In English, the code says says: if event.result.getPassword (what is being sent back from the server) is “yes”, then show the message in an Alert box and take the user to the “loggedOut” state. Otherwise, show the invalid message in an Alert box.
Step 2. Write the HTTPService that will be initiated by the button click from the “Get Info” button on the “Get Login Info” state. This service will call the “getPassword” function written in Step 1, know the location of forgotPW.php, the method of communication, and what the name of the variable we are sending to PHP.
<mx:HTTPService id="get_password" result="getPassword(event)" showBusyCursor="true" method="POST" url="forgotPW.php" useProxy="false">
<mx:request xmlns="">
<email_to>
{email_to.text}
</email_to>
</mx:request>
</mx:HTTPService>
Step 4. Make the “Get Login Info” button call the HTTPService rather than just taking the user to the “loggedOut” state as it is now.
Change From:
<s:Button x="10" y="72" label="Get Login Info" includeIn="forgotPW"/>
Change To:
<s:Button x="8" y="72" label="Get Login Info" click="get_password.send();" includeIn="forgotPW"/>
If you have been following along with these tutorials, your application should look similar to:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
applicationComplete="init()"
minWidth="955" minHeight="600" xmlns:valueObjects="valueObjects.*"
xmlns:usersservice="services.usersservice.*">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
private var userid:int;
private var usertype:String;
[Bindable]
private var cookieAction:Boolean;
protected function saveBtn_clickHandler(event:MouseEvent):void
{
var users2:Users = new Users();
users2.username = usernameTextInput2.text;
users2.email = emailTextInput2.text;
users2.password = passwordTextInput2.text;
users2.user_type = "user";
createUsersResult.token = usersService.createUsers(users2);
createUsersResult.token = usersService.commit();
currentState = 'loggedOut';
}
private function checkLogin(event:ResultEvent):void
{
userid = event.result.loginsuccess;
trace (userid);
usertype = event.result.usertype;
trace (usertype);
cookieAction = event.result.usertype;
trace (cookieAction);
if (userid != 0)
{
currentState = usertype;
}
else
{
mx.controls.Alert.show('Invalid username/password');
}
}
protected function createUsersResult_resultHandler(event:ResultEvent):void
{
mx.controls.Alert.show('Thank you for registering. You may login now!');
currentState = "loggedOut";
}
private function init():void
{
getCookie.send();
}
protected function getCookie_resultHandler(event:ResultEvent):void
{
if(event.result.storedCookie == true)
{
cookieAction = true;
username.text = event.result.creds.username;
password.text = event.result.creds.password;
}
else
{
cookieAction == false;
}
}
private function getPassword(event:ResultEvent):void
{
if(event.result.getPassword == "yes")
{
mx.controls.Alert.show('Your password has been emailed to you.');
currentState = "loggedOut";
}
else
{
mx.controls.Alert.show('Invalid email, please try again.');
}
}
]]>
</fx:Script>
<s:states>
<s:State name="loggedOut"/>
<s:State name="forgotPW"/>
<s:State name="register"/>
<s:State name="user"/>
<s:State name="admin"/>
</s:states>
<fx:Declarations>
<s:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST"
url="login.php" useProxy="false">
<s:request xmlns="">
<username>
{username.text}
</username>
<password>
{password.text}
</password>
<logincookie>
{setCookie.selected}
</logincookie>
</s:request>
</s:HTTPService>
<s:HTTPService id="getCookie" result="getCookie_resultHandler(event)" method="POST" url="getCookie.php"/>
<mx:HTTPService id="get_password" result="getPassword(event)" showBusyCursor="true" method="POST"
url="forgotPW.php" useProxy="false">
<mx:request xmlns="">
<email_to>
{email_to.text}
</email_to>
</mx:request>
</mx:HTTPService>
<valueObjects:Users id="users"/>
<usersservice:UsersService id="usersService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/>
<s:CallResponder id="createUsersResult" result="createUsersResult_resultHandler(event)"/>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Panel width="250" height="200" title="Flex 4 Login Box" horizontalCenter="0" verticalCenter="0">
<s:Label x="10" y="18" text="Username" includeIn="loggedOut"/>
<s:TextInput x="110" y="10" id="username" includeIn="loggedOut"/>
<s:Label x="12" y="47" text="Password" includeIn="loggedOut"/>
<s:TextInput x="110" y="40" id="password" displayAsPassword="true" includeIn="loggedOut"/>
<s:Button x="10" y="72" label="Login" click="login_user.send();" includeIn="loggedOut"/>
<s:Button x="120" y="72" label="Forgot Login Info?" click="currentState='forgotPW'" includeIn="loggedOut"/>
<s:CheckBox x="10" y="101" label="Remember Me" id="setCookie" selected="{cookieAction}" includeIn="loggedOut"/>
<s:Label x="195" y="103" text="Sign Up" click="currentState='register'" includeIn="loggedOut"/>
<s:Label x="10" y="46" text="Email:" includeIn="forgotPW"/>
<s:TextInput x="110" y="39" id="email_to" includeIn="forgotPW"/>
<s:Button x="8" y="72" label="Get Login Info" click="get_password.send();" includeIn="forgotPW"/>
<s:Button x="168" y="72" label="<< Login" click="currentState='loggedOut'" includeIn="forgotPW"/>
<s:Label x="10" y="31" text="Username:" includeIn="register"/>
<s:TextInput x="110" y="24" id="usernameTextInput2" text="{users.username}" includeIn="register"/>
<s:Label x="10" y="61" text="Email:" includeIn="register"/>
<s:TextInput x="110" y="54" id="emailTextInput2" text="{users.email}" includeIn="register"/>
<s:Label x="10" y="91" text="Password:" includeIn="register"/>
<s:TextInput x="110" y="84" id="passwordTextInput2" text="{users.password}" displayAsPassword="true" includeIn="register"/>
<s:Button x="10" y="118" label="Save" id="saveBtn" click="saveBtn_clickHandler(event)" includeIn="register"/>
<s:Button x="168" y="118" label="<< Login" click="currentState='loggedOut'" includeIn="register"/>
<s:Label x="10" y="10" text="Welcome User" includeIn="user"/>
<s:Button x="10" y="30" label="Log Out" click="currentState='loggedOut'" includeIn="user"/>
<s:Label x="10" y="10" text="Welcome Admin" includeIn="admin"/>
<s:Button x="10" y="30" label="Admin Log Out" click="currentState='loggedOut'" includeIn="admin"/>
</s:Panel>
</s:Application>