PHP - Cookie Login Question
I have a quick Question guys about a code i am using!
Basicly i have a from which call the login.php which should create a cookie and display Welcome $_cookie['username'] but it doesnt seem to work? If anyone here spots my error please call me on in. Code: [Select] <form name="login" method="post" action="scripts/login.php"> Username: <input type="text" name="username"> <br> Password: <input type="password" name="password"> <br> Remember Me: <input type="checkbox" name="rememberme" value="1"> <br> <input type="submit" name="submit" value="Login!"> </form> Login.php Code: [Select] <?php /* These are our valid username and passwords */ $user = 'guest'; $pass = 'guest'; if (isset($_POST['username']) && isset($_POST['password'])) { if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) { if (isset($_POST['rememberme'])) { /* Set cookie to last 1 year */ setcookie('username', $_POST['username'], time()+60*60*24*365, '/account', 'c:/wamp/www/notemapper'); setcookie('password', md5($_POST['password']), time()+60*60*24*365, '/account', 'c:/wamp/www/notemapper'); } else { /* Cookie expires when browser closes */ setcookie('username', $_POST['username'], false, '/account', 'c:/wamp/www/notemapper'); setcookie('password', md5($_POST['password']), false, '/account', 'c:/wamp/www/notemapper'); } header('Location: ../index.php'); } else { echo 'Username/Password Invalid'; } } else { echo 'You must supply a username and password.'; } ?> here is how i am testing to see if my cookies are being set which they arnt! Code: [Select] <?php if (isset($_COOKIE['username'])) { echo $_COOKIE['username']; } else { include("widgets/login.html"); } //This is just to see if the cookie is set? echo $_COOKIE['username']; ?> Similar Tutorials
I'm trying to login to a site, navigate a couple of pages deep, and then scrape a table. I had all this working, but the site changed their login workflow...and I can't figure out what I need to do to make this work. Hi I have a login script that allows the user to store info into a cookie if he doesn't want to be bothered by entering is password and other login credentials. however I read somewhere that's not smart to leave a cookie with your pass on your pc. Therefore I want to ask your opionion on how to adapt the below mentioned script so that's safe to store delicate information in a cookie Code: [Select] <?php include("config.php"); if(isset($_SESSION['user_id'])) { // Inloggen correct, updaten laatst actief in db $sql = "UPDATE gebruikers SET lastactive=NOW() WHERE id='".$_SESSION['user_id']."'"; mysql_query($sql); }else{ if(isset($_COOKIE['user_id'])) { $sql = "SELECT wachtwoord,status FROM gebruikers WHERE id='".$_COOKIE['user_id']."'"; $query = mysql_query($sql); $rij = mysql_fetch_object($query); $dbpass = htmlspecialchars($rij->wachtwoord); $dbstatus = htmlspecialchars($rij->status); if($dbpass == $_COOKIE['user_password']) { $_SESSION['user_id'] = $_COOKIE['user_id']; $_SESSION['user_status'] = $dbstatus; }else{ setcookie("user_id", "", time() - 3600); setcookie("user_password", "", time() - 3600); echo "Cookies incorrect. Cookies verwijderd."; header("Location: inloggen.php"); } }else{ header("Location: inloggen.php"); } } ?> this is the concerning table Code: [Select] CREATE TABLE IF NOT EXISTS `gebruikers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `naam` varchar(50) NOT NULL DEFAULT '', `wachtwoord` varchar(50) NOT NULL DEFAULT '', `status` char(1) NOT NULL DEFAULT '0', `email` varchar(100) NOT NULL DEFAULT '', `actief` char(1) NOT NULL DEFAULT '0', `actcode` varchar(15) NOT NULL DEFAULT '', `lastactive` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; Hey guys I'm pretty new to both PHP and Javascript. I think my problem is a PHP one, not a Javascript one. But it involves both. I'm trying to delete a cookie by clicking a link. I call the javascript function like so: if (isset($_COOKIE["active"])) { echo "<a href='addpost.php'>Add Post</a> <a href onClick='eraseCookie()'>Log Out</a>"; } And the function looks like this: Code: [Select] function eraseCookie() { <?php setcookie(active, 0, time()-3600); echo "It works"; ?> } The function doesn't delete the cookie and doesn't echo "It works". Like I said this could be a Javascript error, not a PHP one, but I have to start somewhere. Can someone tell me what I'm doing wrong? Hi. I'm new to this forum so it may be the wrong place i am posting. In school I'm working on a project where i have to make website with php and a database in MySQL. I have made one project. It was good (for one with my lack of skills), but now my teacher asks me to do it in another way. Problem is, I have no way how I can improve it. Right now i'm stuck on my login part. I figure that i have to post my code somewhere if I want some help, but how is the easiest way of doing that? Don't get me wrong. I'm not asking for anyone to make my project. All i need is a nod in the right direction One major problem I want to fix is that as of right now any user who knows the link to my admin panel can go to it directly. What I want to do is see if the the user is logged in (session exists). And if they are not logged in meaning no session exists then to kick them back to the login.php script. index.php(admin page only php coding) <?php session_start(); // Access the existing session // Include the variables page include ('inc/variables.php'); // If no session is present, redirect the user: if(!isset($SESSION['id'])) { header("Location: login.php"); exit(); } ?> However on my login page after I log in its as if with the top code goes right back to it for some reason? Any fixes? Hi! So I know that when redirecting to administrator pages after login is very often done like this: header(location:admin.php); But what if I didnt want to use header? I'm asking because I would just like to include the admin section within the part of the website I'm currently residing, if that makes any sense. Also, I think using headers is a bit cumbersome. I have just recently started learning PHP, so please excuse me if this is a dumb question I have been reading (here and on the internet) about login security, and I have now formulated a dumb question to ask. Not having a secure connection is there any way to NOT send plain text over the internet. In other words, when you have a login form plain text is entered. It is then passed to some type of encryption (hash, md5, sha1) BUT is the password always vulnerable between these two? And just for the record I am asking this because McAfee Secure is giving me a rash of (insert your favorite word here) about my login form which encrypts using sha1. Hey, So I have a couple of files, and I'm trying to create a login script. There is a MySQL query that accesses a database with a list of usernames and passwords. I have a feeling something is wrong with my SQL query, because it's not working correctly. Code: [Select] <?php $connect = mysql_connect("localhost", "root", "root"); if(!$connect){//If user can't connect to database die('Could not connect: ' . mysql_error()); //Throw an error } mysql_select_db("colin_db", $connect); //Get given username and password from username field and password field $givenUsername = $_POST["usernameField"]; $givenPassword = $_POST["passwordField"]; $myQuery = "SELECT * FROM ADMINS WHERE USERNAME = $givenUsername AND PASSWORD = $givenPassword"; $queryResult = mysql_query($myQuery); $numRows = mysql_num_rows($queryResult); if($numRows == 1){ //If the details are correct... //Reload the page and login echo "<script type = 'text/javascript'> window.location.reload() </script>"; echo "Details correct"; } elseif($numRows == 0){ //Else if the details are not found //Display error accordingly echo "Details not correct!"; //This is what happens every time } mysql_close($connect); ?> The database is configured correctly, but I'm not sure how to correctly create a SQL query to determine if the given username and password are correct. In case you'd like to see it, the segment from the index.php file is below. Code: [Select] <form action = "login.php" method = "POST"> Admin Login: <br> Username: <input type = "text" name = "usernameField"/><br> <!-- Password field--> Password: <input type = "password" name = "passwordField"/><br> <!-- Username field --> <input type = "submit" value = "Login" name = "submitButton"/> <!-- Login button --> </form> Any ideas? Thanks, Jake Hello, I'm doing something that looks like framework. It's my first serious "project". And now, I have a few questions: what basic functions are needed in MVC model class? Just tell me some functions, that could use, so I could try to code them. And the next question is... I'm going to create a login system for users. In my website there will be pages, that are visible for all visitors, and only for members. For example main website page should be visible for all visitors, but the page, where member can change his password, should be visible only for member. I know only one way to do this: allways and everywhere check if user is logged in. But isn't there smarter and simpler way? I hope you understood what I need. Sorry for bad english I have a login system that uses a flat file database. The flat file is in a directory outside the public_html. My questions; 1- Is is still possible to hack into that file? Currently I do not encrypt the passwords as I have been told that having the file outside the public_html makes the file unavailable to the public. This allows me the advantage of sending the Username and Password to the user in an email if they forget there password or username. Otherwise- I would have to set up a more complicated method to allow them to change their password to re-gain access to the site. I have an SSL on the site also so I am not worried about packet sniffing. Thanks Hi y'all. It's been forever and a day since I've dealt with cookies, and I can't get through the cobwebs in my brain about them. I know that cookies have to be set before any output goes to the browser, but if I'm not mistaken, it's the same with sessions and sessions work in this situation. Unfortunately, the client needs cookies for integration with an existing piece of software.
Basically, what's happening is this: You load a page, click the 'login' button, which uses JQuery to change the display on the login screen from 'none' to 'block'. Use the newly-visible login form to enter username and password, which are passed via ajax to my login function. If the login is successful, I set the cookie variable and redirect the user to the protected page. However, despite the ajax reporting a successful login and redirecting the browser as expected, the check on the protected page is kicking the user back to the beginning because the cookie was never actually set.
FunctionsClass.php:
/** * Logs in the requesting user with the agent and email values supplied via AJAX. * @return string JSON-encoded array */ public function agentLogin(){ $ret['success'] = $this->_site->login($_POST['username'],$_POST['password']); $ret['location'] = '/protected-page'; print(json_encode($ret)); die(); }Site.php (that's $_site in FunctionsClass): /** * Logs in the agent. * Checks to see if the user is already logged in, if not, attempts to do so. * @param string $un username * @param string $pw password * @return boolean */ public function logIn($un, $pw){ if($this->isLoggedIn()){ return true; } return $this->logAgentIn($un,$pw); } /** * Check to see if the cookie set so we know if the user has logged in. * @return boolean */ public function isLoggedIn(){ // return !empty($_SESSION['mycheckvariable']); return !empty($_COOKIE['mycheckvariable']); } /** * Log the user in. * @param string $un username * @param string $pw password * @return boolean */ private function logAgentIn($un,$pw){ // $_SESSION['mycheckvariable']['email'] = 'me@notmyemail.com'; setcookie('mycheckvariable','me@notmyrealemail.com',time()+60*60*8,'/'); return true; }It's not as though I'm even actually checking a database - just trying to stub this out for client presentation. And, if I uncomment the two lines using sessions and comment out the cookies, it all works perfectly. I'm not at all sure what I'm missing and would very much appreciate some other eyes on this - any takers? I'm using WordPress, if that matters at all... Thanks in advance! Hello, I am slightly nervous about posting this because I am almost completely new to php, I have a few introductory books on the subject which I am working through at the moment as well as some reference books but I am still getting through the basics of it all. I recently downloaded a login script, which allows a user to login and also allows the protection of some pages if users are not logged in. This script was a free one from easykiss123. it comes with other .php files and I have given them all a look over and I get the general idea of what's going on for the most part, and I THINK as I keep reading my books I will understand everything even more. However, what I really want to do right now is make it so a website would know which user is logged on, and then use this information elsewhere. For example if a particular user logged on and submitted something, I would like obviously the submission to be recorded but also the id of the user that submitted it, at the moment with this code, I do not think that is possible, however I could be wrong. I am looking for any pointers or a nudge in the right direction or link to a tutorial of how I would go about this, anything that may help. I think I would be storing the user ID in a global variable that can be used throughout the site, but again I am not sure. Thanks in advance for any help, I have included both the login script and the script used for protecting pages, as its already freely available online I see no issue with posting snippits of it here since the source has been referenced. Code: [Select] <?php # Script 16.8 - login.php // This is the login page for the site. require_once ('includes/config.inc.php'); $page_title = 'Login'; include ('includes/header.html'); if (isset($_POST['submitted'])) { require_once (MYSQL); // Validate the email address: if (!empty($_POST['email'])) { $e = mysqli_real_escape_string ($dbc, $_POST['email']); } else { $e = FALSE; echo '<p class="error">You forgot to enter your email address!</p>'; } // Validate the password: if (!empty($_POST['pass'])) { $p = mysqli_real_escape_string ($dbc, $_POST['pass']); } else { $p = FALSE; echo '<p class="error">You forgot to enter your password!</p>'; } if ($e && $p) { // If everything's OK. // Query the database: $q = "SELECT user_id, first_name, user_level FROM users WHERE (email='$e' AND pass=SHA1('$p')) AND active IS NULL"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); if (@mysqli_num_rows($r) == 1) { // A match was made. // Register the values & redirect: $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC); mysqli_free_result($r); mysqli_close($dbc); $url = BASE_URL . 'index.php'; // Define the URL: ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { // No match was made. echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>'; } } else { // If everything wasn't OK. echo '<p class="error">Please try again.</p>'; } mysqli_close($dbc); } // End of SUBMIT conditional. ?> <h1>Login</h1> <p>Your browser must allow cookies in order to log in.</p> <form action="login.php" method="post"> <fieldset> <p><b>Email Address:</b> <input type="text" name="email" size="20" maxlength="40" /></p> <p><b>Password:</b> <input type="password" name="pass" size="20" maxlength="20" /></p> <div align="center"><input type="submit" name="submit" value="Login" /></div> <input type="hidden" name="submitted" value="TRUE" /> </fieldset> </form> <?php // Include the HTML footer. include ('includes/footer.html'); ?> Code: [Select] <?php require_once ('includes/config.inc.php'); $page_title = 'YOUR PAGE TITLE GOES HERE'; // Start output buffering: ob_start(); // Initialize a session: session_start(); // Check for a $page_title value: if (!isset($page_title)) { $page_title = 'User Registration'; } // If no first_name session variable exists, redirect the user: if (!isset($_SESSION['first_name'])) { $url = BASE_URL . 'index.php'; // Define the URL. ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } ?> Code: [Select] <?php // Flush the buffered output. ob_end_flush(); ?> Someone parses the html login form and gets the csrf token from hidden field. Now can he request with that csrf token to login through jquery ajax? hi i need help an idea how can i separate members from admins since i dont know how to create login form i used tutorial ( http://www.youtube.com/watch?v=4oSCuEtxRK8 ) (its session login form only that i made it work other tutorials wre too old or something) how what i want to do is separate members and admins because admin need more rights to do now i have idea but dont know will it work like that what i want to do is create additional row in table named it flag and create 0 (inactive user) 1 (member) 2 (admin) will that work? and how can i create different navigation bars for users and admins? do you recommend that i use different folders to create it or just script based on session and flag? Hi guys, Can anyone assist me. I am trying to create a login for admin and user (if user not a member click register link) below is my code: But whenever I enter the value as: Username: admin Password:123 - I got an error message "That user does not exist!" Any suggestion and help would be appreciated. Thanks. login.php <?php //Assigned varibale $error_msg as empty //$error_msg = ""; session_start(); $error_msg = ""; if (isset($_POST['submit'])) { if ($a_username = "admin" && $a_password = "123") { //Define $_POST from form text feilds $username = $_POST['username']; $password = $_POST['password']; //Add some stripslashes $username = stripslashes($username); $password = stripslashes($password); //Check if usernmae and password is good, if it is it will start session if ($username == $a_username && $password == $a_password) { session_start(); $_SESSION['session_logged'] = 'true'; $_SESSION['session_username'] = $username; //Redirect to admin page header("Location: admin_area.php"); } } $username = (isset($_POST['username'])) ? $_POST['username'] : ''; $password = (isset($_POST['password'])) ? $_POST['password'] : ''; if($username && $password) { $connect = mysql_connect("localhost", "root", "") or die ("Couldn't connect!"); mysql_select_db("friendsdb") or die ("Couldn't find the DB"); $query = mysql_query ("SELECT * FROM `user` WHERE username = '$username'"); $numrows = mysql_num_rows($query); if ($numrows != 0){ while ($row = mysql_fetch_array($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } //Check to see if they are match! if ($username == $dbusername && md5($password) == $dbpassword) { header ("Location: user_area.php"); $_SESSION['username'] = $username; } else $error_msg = "Incorrect password!"; //code of login }else $error_msg = "That user does not exist!"; //echo $numrows; } else $error_msg = "Please enter a username and password!"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Login Page</title> </head> <body> <br /> <?php require "header.php"; ?><br /> <div align="center"> <table width="200" border="1"> <?php // If $error_msg not equal to emtpy then display error message if($error_msg!="") echo "<div id=\"error_message\"style=\"color:red; \">$error_msg</div><br />";?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <!--form action="login_a.php" method="post"--> Username: <input type="text" name="username" /><br /><br /> Password: <input type="password" name="password" /><br /><br /> <input type="submit" name = "submit" value="Log in" /> </form> <p> </p> Register a <a href="register.php">New User</a> </table> </div> </body> </html> How to add the ability to login with username or email for login?
<?php ob_start(); include('../header.php'); include_once("../db_connect.php"); session_start(); if(isset($_SESSION['user_id'])!="") { header("Location: ../dashboard"); } if (isset($_POST['login'])) { $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); $result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and pass = '" . md5($password). "'"); if ($row = mysqli_fetch_array($result)) { $_SESSION['user_id'] = $row['uid']; $_SESSION['user_name'] = $row['user']; $_SESSION['user_email'] = $row['email']; header("Location: ../dashboard"); } else { $error_message = "Incorrect Email or Password!!!"; } } ?>
Hello guys, Is there on web any updated tutorial on how can I add Facebook login on my simple php login script? Hi guys. What I want to create is really complicated. Well I have a login system that works with post on an external website. I have my own website, but they do not give me access to the database for security reasons, therefore I have to use their login system to verify my users. What their website does is that it has a post, with username and password. The POST website is lets say "https://www.example.com/login". If login is achieved (i.e. username and password are correct), it will redirect me to "https://www.example.com/login/success" else it will redirect me to "https://www.example.com/login/retry". So I want a PHP script that will do that post, and then according to the redirected website address it will return me TRUE for success, FALSE for not successful login. Any idea?? Thanks Hello, I am once again desperately asking for your help, I am working on a simple login page and I am having trouble actually getting it to login. I display error messages for if the user doesn't enter anything but I can't seem to get it to work for if the credentials are wrong. It logs the user in whether the information is right or not and i dont even know what to do now
This is the code any suggestions would be greatly appreciated <?php /* Name: Deanna Slotegraaf Course Code: WEBD3201 Date: 2020-09-22 */ $file = "sign-in.php"; $date = "2020-09-22"; $title = "WEBD3201 Login Page"; $description = "This page was created for WEBD3201 as a login page for a real estate website"; $banner = "Login Page"; require 'header.php'; $error = ""; if($_SERVER["REQUEST_METHOD"] == "GET") { $username = ""; $password = ""; $lastaccess = ""; $error = ""; $result = ""; $validUser = ""; } else if($_SERVER["REQUEST_METHOD"] == "POST") { $conn; $username = trim($_POST['username']); //Remove trailing white space $password = trim($_POST['password']); //Remove trailing white space if (!isset($username) || $username == "") { $error .= "<br/>Username is required"; } if (!isset($password) || $password == ""){ $error .= "<br/>Password is required"; } if ($error == "") { $password = md5($password); $query = "SELECT * FROM users WHERE EmailAddress='$username' AND Password='$password'"; $results = pg_query($conn, $query); //$_SESSION['username'] = $username; //$_SESSION['success'] = "You are now logged in"; header('location: dashboard.php'); }else { $error .= "Username and/or Password is incorrect"; } } ?> <div class = "form-signin"> <?php echo "<h2 style='color:red; font-size:20px'>".$error."</h2>"; ?> <form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <label for="uname"><b>Login ID</b></label> <input type="text" name="username" value="<?php echo $username; ?>"/> <br/> <label for="psw"><b>Password</b></label> <input type="password" name="password" value="<?php echo $password; ?>"/> <br/> <button type="submit" name="login_user">Login</button> <button type="reset">Reset</button></div> </form> </div> <?php require "footer.php"; ?>
Hi everyone i wonder if you can help me he I need a script for a login and check login- create cookie. Here is my form: <form method="post" action="check_login.php"> <p> <input type="submit" name="Submit2" value="go" /> </fieldset> </p> </form> that sends it to check_login (which BEFORE i deleted something by accident, used to take me to a username and password box) But now all it does is send me straight to the memebrs area??? Can i change the check_login.php script to make it work correctly: Code: [Select] <?php // Connects to your Database mysql_connect("server", "user", "password") or die(mysql_error()); mysql_select_db("DB") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])) //if there is, it logs you in and directes you to the members page { $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) { if ($pass != $info['upassword']) { } else { header("Location: members_area.php"); } } } //if the login form is submitted if (isset($_POST['submit'])) { // if form has been submitted // makes sure they filled it in if(!$_POST['username'] | !$_POST['upassword']) { die('You did not fill in a required field.'); } // checks it against the database if (!get_magic_quotes_gpc()) { $_POST['email'] = addslashes($_POST['email']); } $check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error()); //Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. <a href=register.php>Click Here to Register</a>'); } while($info = mysql_fetch_array( $check )) { $_POST['upassword'] = stripslashes($_POST['upassword']); $info['upassword'] = stripslashes($info['upassword']); $_POST['upassword'] = md5($_POST['upassword']); //gives error if the password is wrong if ($_POST['upassword'] != $info['upassword']) { die('Incorrect password, please try again.'); } else { // if login is ok then we add a cookie $_POST['username'] = stripslashes($_POST['username']); $hour = time() + 3600; setcookie(ID_my_site, $_POST['username'], $hour); setcookie(Key_my_site, $_POST['upassword'], $hour); //then redirect them to the members area header("Location: members_area.php"); } } } else { // if they are not logged in ?> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <table width="316" height="120" border="0"> <tr><td colspan=2><h1>Login</h1></td></tr> <tr><td>Username:</td><td> <input type="text" name="username" maxlength="40"> </td></tr> <tr><td>Password:</td><td> <input type="password" name="upassword" maxlength="50"> </td></tr> <tr><td colspan="2" align="right"> <input type="submit" name="submit" value="Login"> </td></tr> </table> </form> <?php } ?> |