DevelopPHP
home gear home donate
Search Results For
in:

Libraries book

HTML Library CSS Library JavaScript Library PHP Library

Videosbook

PHP and MySQL JavaScript HTML and CSS Vector and 3D Flash Actionscript Android Dev Miscellaneous

Resourcesbook

Website Hosting Developer Q+A
Sprite Programming Mastery
<iframe width="560" height="315" src="http://www.youtube.com/embed/gav4HmZ8xe8" frameborder="0" allowfullscreen></iframe>
You can embed this video on your blog or web page by copying the video embed code above and pasting it into the source code of your page. Adjust the width and height to specify the size you would like it to display.
Thumb 7. PHP Tutorial - Log In Form - Log Out Script - Cookies and Sessions - User Profile
Embed Source - http://www.youtube.com/watch?v=gav4HmZ8xe8
Publish Date - Jan 27, 2013     Author - Adam Khoury
7. PHP Tutorial - Log In Form - Log Out Script - Cookies and Sessions - User Profile
Learn to program the HTML - PHP - Ajax log in form, the log out script, start the user profile page for your social network web site software. We also create a module for checking user session, cookies and authentication against the MySQL database. In the next tutorial we will cover site maintenance automation using Cron Jobs.
Lesson Code
<!-- ******** login.php ******** -->

<?php
include_once("php_includes/check_login_status.php");
// If user is already logged in, header that weenis away
if($user_ok == true){
header("location: user.php?u=".$_SESSION["username"]);
    exit();
}
?><?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["e"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
// GET USER IP ADDRESS
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if($e == "" || $p == ""){
echo "login_failed";
        exit();
} else {
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
        $row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
        $db_pass_str = $row[2];
if($p != $db_pass_str){
echo "login_failed";
            exit();
} else {
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
    setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE); 
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
            $query = mysqli_query($db_conx, $sql);
echo $db_username;
   exit();
}
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<style type="text/css">
#loginform{
margin-top:24px;
}
#loginform > div {
margin-top: 12px;
}
#loginform > input {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#loginbtn {
font-size:15px;
padding: 10px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var e = _("email").value;
var p = _("password").value;
if(e == "" || p == ""){
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "login.php");
        ajax.onreadystatechange = function() {
       if(ajaxReturn(ajax) == true) {
           if(ajax.responseText == "login_failed"){
_("status").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
       }
        }
        ajax.send("e="+e+"&p="+p);
}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
  <h3>Log In Here</h3>
  <!-- LOGIN FORM -->
  <form id="loginform" onsubmit="return false;">
    <div>Email Address:</div>
    <input type="text" id="email" onfocus="emptyElement('status')" maxlength="88">
    <div>Password:</div>
    <input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
    <br /><br />
    <button id="loginbtn" onclick="login()">Log In</button> 
    <p id="status"></p>
    <a href="#">Forgot Your Password?</a>
  </form>
  <!-- LOGIN FORM -->
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>

<!-- ******** logout.php ******** -->

<?php
session_start();
// Set Session data to an empty array
$_SESSION = array();
// Expire their cookie files
if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])) {
setcookie("id", '', strtotime( '-5 days' ), '/');
    setcookie("user", '', strtotime( '-5 days' ), '/');
setcookie("pass", '', strtotime( '-5 days' ), '/');
}
// Destroy the session variables
session_destroy();
// Double check to see if their sessions exists
if(isset($_SESSION['username'])){
header("location: message.php?msg=Error:_Logout_Failed");
} else {
header("location: http://www.yoursite.com");
exit();
?>

<!-- ******** user.php ******** -->

<?php
include_once("php_includes/check_login_status.php");
// Initialize any variables that the page might echo
$u = "";
$sex = "Male";
$userlevel = "";
$country = "";
$joindate = "";
$lastsession = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
    header("location: http://www.yoursite.com");
    exit();
}
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
    exit();
}
// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
$isOwner = "yes";
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$gender = $row["gender"];
$country = $row["country"];
$userlevel = $row["userlevel"];
$signup = $row["signup"];
$lastlogin = $row["lastlogin"];
$joindate = strftime("%b %d, %Y", strtotime($signup));
$lastsession = strftime("%b %d, %Y", strtotime($lastlogin));
if($gender == "f"){
$sex = "Female";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $u; ?></title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
  <h3><?php echo $u; ?></h3>
  <p>Is the viewer the page owner, logged in and verified? <b><?php echo $isOwner; ?></b></p>
  <p>Gender: <?php echo $sex; ?></p>
  <p>Country: <?php echo $country; ?></p>
  <p>User Level: <?php echo $userlevel; ?></p>
  <p>Join Date: <?php echo $joindate; ?></p>
  <p>Last Session: <?php echo $lastsession; ?></p>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>

<!-- ******** check_login_status.php ******** -->

<?php
session_start();
include_once("db_conx.php");
// Files that inculde this file at the very top would NOT require 
// connection to database or session_start(), be careful.
// Initialize some vars
$user_ok = false;
$log_id = "";
$log_username = "";
$log_password = "";
// User Verify function
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND username='$u' AND password='$p' AND activated='1' LIMIT 1";
    $query = mysqli_query($conx, $sql);
    $numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
}
}
if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
$log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
$log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
$log_password = preg_replace('#[^a-z0-9]#i', '', $_SESSION['password']);
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
$_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
    $_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
    $_SESSION['password'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['pass']);
$log_id = $_SESSION['userid'];
$log_username = $_SESSION['username'];
$log_password = $_SESSION['password'];
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
if($user_ok == true){
// Update their lastlogin datetime field
$sql = "UPDATE users SET lastlogin=now() WHERE id='$log_id' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
}
}
?>

Home   •   Terms of Use   •   T-Shirts   •   RSS   •   Testimonials   •   Subscribe   •   Classroom Chalkboard   •   Developer Q+A   •   Donate   •   Top ↑
Popular In PHP / MySQL E-Commerce Store Production
Social Network Website Building
Image Upload / Photo Processing
CMS Software Programming
Mass Email Systems
Magic XML Data
Search Programming
Popular In JavaScript JSON Programming
Ajax Programming
Animating Elements
WYSIWYG Programming
Date/Time Programming
DOM Scripting
Object Reference
Popular In HTML Canvas Element
New Form Elements
Audio Element
Video Element
Drag and Drop
Event Handling
Element Grouping
Popular In CSS Custom Font Embedding
Dynamic Fit Backgrounds
Theatre Mode
Box Overlays
CSS Level 1 Properties
CSS Level 2 Properties
CSS Level 3 Properties
DevelopPHP.com is a growing educational system packed with video and written material that you can access 24/7 100% free. The focus here in 2014 is spread between five technologies: HTML, CSS, JavaScript, PHP and MySQL. Learn programming theory, database interaction, web design, animation, graphics editing, vector art, 3D modeling, and much more. The educational experience here is a hybrid one offering both high quality video tutorials and code libraries that grow more robust every day. The code libraries are being assembled so that developers can discover all of the building blocks of their favorite languages. The libraries coupled with high quality video tutorials will take you deep down the rabbit hole very quickly. You can also ask questions and get free advice at WebIntersect.com.
HTML5