PHP - Question Regarding Ajax Login Setting A $_cookie[] Value
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! Similar TutorialsI am trying to make a login using cookies, I had been using sessions but i need to use cookies for it now. I have a page called login.php, and i use ajax to login. It seems to be setting the cookie and printing the value of it out when i login, however that's about it. When i'm reading the cookie on other pages it doesn't appear to recognize a cookie. However, If i set the cookie on just a regular index page it has no problem with setting it and reading it. it works fine when i do that. This is how i set the cookie on the login page (also the exact code i used to test setting it on the index page): $expire=time()+60*60*24*30; setcookie("id", $dbid, $expire); $session = $_COOKIE['id']; then to read it on other pages i just use: $session = $_COOKIE['id']; This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=350592.0 Is it bad practice to use $_COOKIE for your log in system and to protect your pages or would it be better to use $_SESSION? I have always used cookie but I am not sure if that is good practice Hi there, I am using the jQuery, Ajax PHP code which is given at http://roshanbh.com.np/2008/04/ajax-login-validation-php-jquery.html The form I am using, which is in index.html, is: Code: [Select] <form method="post" action="" name="login" id="login_form"> <div class="field_row"> <div class="label_container"> <label>Email</label> </div> <div class="field_container"> <input type="text" placeholder="login with your email address..." name="email_address" id="email_address" value="" class="large" /> </div> <div class="clear"><span class="nodisp"> </span></div> </div> <div class="field_row"> <div class="label_container"> <label>Password</label> </div> <div class="field_container"> <input type="password" placeholder="...and password" name="password" id="password" value="" class="large" /> </div> <div class="clear"><span class="nodisp"> </span></div> </div> <div class="final_row"> <input type="image" src="images/login_blue.gif" id="user_login_button" name="user_login_button" value="login" id="submit" class="submit_button" /> <div class="final_row_text_container" > <a href="/login/forgot_password" style="color: #008ee8;" class="small_text">Forgot your Password?</a> <br /> <span id="msgbox" style="display:none"></span> </div> </div> <div class="clear"><span class="nodisp"> </span></div> </form> The Javascript, which is situated in the head of index.html. is: Code: [Select] <script language="javascript"> $(document).ready(function() { $("#login_form").submit(function() { //remove all the class add the messagebox classes and start fading $("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000); //check the email address exists or not from ajax $.post("login_ajax.php",{ email_address:$('#email_address').val(),password:$('#password').val(),rand:Math.random() } ,function(data) { if(data=='yes') //if correct login detail { $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox { //add message and change the class of the box and start fading $(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1, function() { //redirect to secure page document.location='secure.php'; }); }); } else { $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox { //add message and change the class of the box and start fading $(this).html('Your login details are incorrect.').addClass('messageboxerror').fadeTo(900,1); }); } }); return false; //not to post the form physically }); //now call the ajax also focus move from $("#password").blur(function() { $("#login_form").trigger('submit'); }); }); </script> And the PHP, in login_ajax.php, is: <?php session_start(); $host = "localhost"; $user = "bford"; $pass = "bford"; $db = "bford"; $link = mysql_connect($host, $user, $pass); if (!link) { die('<strong>Error(s) occured:</strong> Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db($db, $link); if (!db_selected) { die ('<strong>Error(s) occured:</strong> Cant use bford: ' . mysql_error()); } //get the posted values $email_address=$_GET['emailaddress']; $pass=$_GET['password']; //now validating the username and password $sql="SELECT * FROM users WHERE email_address='".$email_address."'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); //if username exists if(mysql_num_rows($result)>0) { //compare the password if($row["password"],$pass)==1 { echo "yes"; //now set the session from here if needed $_SESSION["user_name"]=$userID; } else echo "no"; } else echo "no"; //Invalid Login ?> I have been working on this for days now, changing around the form names, database table names, php variables, allsorts! I still cannot get it functioning properly. When I input a correct email_address and password combination, the 'Your login details are incorrect.' message still appears. Help would be much appreciated. Ben.
I'm trying to login and scrape a page 4 pages deep. I can get to the fourth page...but that page only returns AJAX ERROR:0. I know NOTHING about AJAX calls via Curl. Can someone please help me with what to look for in the source code of the 4th page (when using a browser) to what I'm supposed to pass along via CURL? I like to use $_REQUEST to get something from either $_POST or $_GET. Annoying though, it also includes values from cookie, like the PHP session id, FCK editor cookies and the google tracking code. Is there anyway to remove cookie values from request, besides looping through cookie and unsetting the values I don't want? In my system I have a collection of php files which handle the requests from my ajax e.g. I have a function which lets users "subscribe" to another user's posts "userConnect()" and another function which lets a user uprate another user's post "uprate()" At the moment the uprate() function uses ajax to pass it's data to a file called "ajax_uprate.php" and the userConnect() function similarly passes it's data to a file called "ajax_userConnect.php". Would I be better to combine these files into one global ajax.php file or is it better to keep them seperate? Basically I am wondering because at the moment I have a tonne of ajax_XXX files for every single function, each containing a very small amount of code. My thinking was that the smaller these files are the faster these ajax processes would take place. Am I right in thinking this or not? Nonsense question, but still... Is there any method to detect gmail client timezone setting? Like mobile app and web gmail client? Not browser or IP or similar, but gmail. Thank you for your answers. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=325435.0 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. 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 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 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']; ?> 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 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? Right now I redirect to index page after I delete a record. However I am looking to make it so that I can delete a record without redirecting the page. I know this can be accomplised using Ajax. I have spent countless hours before trying to make it work, but it did not work.
So here is a basic setup I created. Can you please update it with ajax code so that I can see how it's done properly?
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <div class="record" > <a href="record.php?id=<?php echo $record_id ?>"><?php echo $record_name; ?></a> <div class="delete-record"> <a href="delete.php">Delete Record</a> </div> </div> </body> </html> Edited by man5, 18 August 2014 - 08:55 PM. |