yanjchan Posted July 10, 2009 Share Posted July 10, 2009 I'm sure this is a pretty common question... But I need clarification. How should I structure the flow of my login script? I understand that there is a form, and the contents of the form are submitted then proccessed in a PHP script. However, if the username/pass are correct, how do you redirect the person to the new page? Or should I make it work in a different way? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/ Share on other sites More sharing options...
cs.punk Posted July 10, 2009 Share Posted July 10, 2009 I'm sure this is a pretty common question... But I need clarification. How should I structure the flow of my login script? I understand that there is a form, and the contents of the form are submitted then proccessed in a PHP script. However, if the username/pass are correct, how do you redirect the person to the new page? Or should I make it work in a different way? Thanks! Well you need a login page to 'set $_SESSION varibles'... Then you need this: verify_user.php <?php if (!isset ($_SESSION['user']) || !isset($_SESSION['rank'])) {header("Location: /login.php); } ?> Include that in every 'login protected' page... Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-873174 Share on other sites More sharing options...
ignace Posted July 10, 2009 Share Posted July 10, 2009 Then you need this: verify_user.php <?php if (!isset ($_SESSION['user']) || !isset($_SESSION['rank'])) {header("Location: /login.php); } ?> Include that in every 'login protected' page... Right and then he will be coming back asking why he gets: Notice: Undefined index: user Notice: Undefined index: rank Or why after he logs in he is being redirected to the login after going to a login protected page. Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-873184 Share on other sites More sharing options...
ignace Posted July 10, 2009 Share Posted July 10, 2009 How should I structure the flow of my login script? I understand that there is a form login_form.php <?php require_once('csrf.php'); ?> <?php if (!empty($_GET['errors'])): ?> <ul> <li><?php print implode("</li>\n\t<li>", explode(';', $_GET['errors'])); ?></li> </ul> <?php endif; ?> <form action="login_process.php" method="post"> <input type="hidden" name="csrf" value="<?php print $_SESSION['csrf']; ?>"> <label>Username: <input type="text" name="username"></label> <label>Password: <input type="password" name="password"></label> <input type="submit" value="Login"> </form> and the contents of the form are submitted then proccessed in a PHP script login_process.php <?php error_reporting(0); // set to E_ALL if under development ini_set('display_errors', FALSE); // set to TRUE if under development if (!empty($_POST)) { if (empty($_POST['csrf'])) { session_destroy(); header('Location: login_form.php'); } $csrf = $_POST['csrf']; if (!strcmp($csrf, $_SESSION['csrf']) || $_SESSION['csrf_ttl'] < time()) { session_destroy(); header('Location: login_form.php'); // re-creates the session and the csrf } $username = htmlentities($_POST['username']); $password = htmlentities($_POST['password']); $errors = array(); if (!ctype_alnum($username)) { $errors[] = 'Username should only contain alphanumeric characters'; } if (sizeof($errors)) { $errors = implode(';', $errors); header("Location: login_form.php?errors=$errors"); } require_once('connect2db.php'); $query = 'SELECT * FROM users WHERE username=\'%s\' AND password=sha1(\'%s\')'; $fquery = sprintf($query, $username, $password); $result = mysql_query($fquery, $db); $total_result_rows = mysql_num_rows($result); if ($total_result_rows === 1) { require_once('getip.php'); require_once('sessions.php'); $_SESSION['username'] = $username; $_SESSION['userip'] = sha1(getip()); $_SESSION['useragent'] = sha1($_SERVER['HTTP_USER_AGENT']); } else {// 0: username, password match not found; 1+: multiple matches found, ambiguous $errors = 'Username and/or password are incorrect'; header("Location: login_form.php?errors=$errors"); } } else { header('Location: login_form.php'); } ?> verify_login.php <?php require_once('getip.php'); require_once('sessions.php'); if (!empty($_SESSION['useragent']) && (!strcmp($_SESSION['useragent'], sha1($_SERVER['HTTP_USER_AGENT'])) || !strcmp($_SESSION['userip'], sha1(getip()))) { // 1: same session, different browser? 2: ip changed? session_destroy(); header('Location: login_form.php'); } ?> Then on your login protected pages: <?php require_once('verify_login.php'); //protected page content ?> Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-873206 Share on other sites More sharing options...
sKunKbad Posted July 11, 2009 Share Posted July 11, 2009 There is a multitude of php authentication scripts available online. Making an authentication script goes way beyond php basics, and you should consider the high probability of getting hacked if you don't do your homework. A great solution for you might be to use a php framework that includes an authentication class, or use PEAR's authentication. kohanaphp.com is the home page for the Kohana framework. It includes an authentication class. codeigniter.com is the home page of CodeIgniter, and CodeIgniter is a great php framework, and some community members have posted authentication modules in the site wiki. phpclasses.org might be a good place to look for authentication scripts that are not part of a framework. Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-873293 Share on other sites More sharing options...
yanjchan Posted July 12, 2009 Author Share Posted July 12, 2009 Some help on using the Kohana Authentication would be appreciated. As a reply to ignace, require_once('connect2db.php'); $query = 'SELECT * FROM users WHERE username=\'%s\' AND password=sha1(\'%s\')'; $fquery = sprintf($query, $username, $password); $result = mysql_query($fquery, $db); $total_result_rows = mysql_num_rows($result); What is %s? And I assume connect2db.php would be the login information for the msyql? (mysql_connect(blahblah)). So the contents of the table would be two columns, username and password, and the password in a sha1 hash? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-874172 Share on other sites More sharing options...
yanjchan Posted July 13, 2009 Author Share Posted July 13, 2009 Bump? Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-874351 Share on other sites More sharing options...
ignace Posted July 13, 2009 Share Posted July 13, 2009 Some help on using the Kohana Authentication would be appreciated. As a reply to ignace, require_once('connect2db.php'); $query = 'SELECT * FROM users WHERE username=\'%s\' AND password=sha1(\'%s\')'; $fquery = sprintf($query, $username, $password); $result = mysql_query($fquery, $db); $total_result_rows = mysql_num_rows($result); What is %s? And I assume connect2db.php would be the login information for the msyql? (mysql_connect(blahblah)). So the contents of the table would be two columns, username and password, and the password in a sha1 hash? Thanks! %s is an identifier used by sprintf(): http://us3.php.net/manual/en/function.sprintf.php And yes connect2db.php is indeed creates the database connection And yes the password is a sha1() hash Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-874450 Share on other sites More sharing options...
ignace Posted July 13, 2009 Share Posted July 13, 2009 Here is the getip() function function getip() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; // shared internet } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { return $_SERVER['HTTP_X_FORWARDED_FOR']; // behind a proxy } else { return $_SERVER['REMOTE_ADDR']; // directly connected to the internet } } Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-874452 Share on other sites More sharing options...
yanjchan Posted July 14, 2009 Author Share Posted July 14, 2009 I'm sorry, what is crsf.php? (I'm sorry if I'm being a nuisance.) EDIT: Is it: 1 <?php 2 /* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ 3 /* 4 # ***** BEGIN LICENSE BLOCK ***** 5 # This file is part of Plume Framework, a simple PHP Application Framework. 6 # Copyright (C) 2001-2007 Loic d'Anterroches and contributors. 7 # 8 # Plume Framework is free software; you can redistribute it and/or modify 9 # it under the terms of the GNU Lesser General Public License as published by 10 # the Free Software Foundation; either version 2.1 of the License, or 11 # (at your option) any later version. 12 # 13 # Plume Framework is distributed in the hope that it will be useful, 14 # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 # GNU Lesser General Public License for more details. 17 # 18 # You should have received a copy of the GNU Lesser General Public License 19 # along with this program; if not, write to the Free Software 20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 21 # 22 # ***** END LICENSE BLOCK ***** */ 23 24 /** 25 * Cross Site Request Forgery Middleware. 26 * 27 * This class provides a middleware that implements protection against 28 * request forgeries from other sites. This middleware must be before 29 * the Pluf_Middleware_Session middleware. 30 * 31 * Based on concepts from the Django CSRF middleware. 32 */ 33 class Pluf_Middleware_Csrf 34 { 35 public static function makeToken($session_key) 36 { 37 return md5(Pluf::f('secret_key').$session_key); 38 } 39 40 /** 41 * Process the request. 42 * 43 * When processing the request, if a POST request with a session, 44 * we will check that the token is available and valid. 45 * 46 * @param Pluf_HTTP_Request The request 47 * @return bool false 48 */ 49 function process_request(&$request) 50 { 51 if ($request->method != 'POST') { 52 return false; 53 } 54 $cookie_name = Pluf::f('session_cookie_id', 'sessionid'); 55 if (!isset($request->COOKIE[$cookie_name])) { 56 // no session, nothing to do 57 return false; 58 } 59 try { 60 $data = Pluf_Middleware_Session::_decodeData($request->COOKIE[$cookie_name]); 61 } catch (Exception $e) { 62 // no valid session 63 return false; 64 } 65 if (!isset($data['Pluf_Session_key'])) { 66 // no session key 67 return false; 68 } 69 $token = self::makeToken($data['Pluf_Session_key']); 70 if (!isset($request->POST['csrfmiddlewaretoken'])) { 71 return new Pluf_HTTP_Response_Forbidden($request); 72 } 73 if ($request->POST['csrfmiddlewaretoken'] != $token) { 74 return new Pluf_HTTP_Response_Forbidden($request); 75 } 76 return false; 77 } 78 79 /** 80 * Process the response of a view. 81 * 82 * If we find a POST form, add the token to it. 83 * 84 * @param Pluf_HTTP_Request The request 85 * @param Pluf_HTTP_Response The response 86 * @return Pluf_HTTP_Response The response 87 */ 88 function process_response($request, $response) 89 { 90 $cookie_name = Pluf::f('session_cookie_id', 'sessionid'); 91 if (!isset($request->COOKIE[$cookie_name])) { 92 // no session, nothing to do 93 return $response; 94 } 95 if (!isset($response->headers['Content-Type'])) { 96 return $response; 97 } 98 try { 99 $data = Pluf_Middleware_Session::_decodeData($request->COOKIE[$cookie_name]); 100 } catch (Exception $e) { 101 // no valid session 102 return $response; 103 } 104 if (!isset($data['Pluf_Session_key'])) { 105 // no session key 106 return $response; 107 } 108 $ok = false; 109 $cts = array('text/html', 'application/xhtml+xml'); 110 foreach ($cts as $ct) { 111 if (false !== strripos($response->headers['Content-Type'], $ct)) { 112 $ok = true; 113 break; 114 } 115 } 116 if (!$ok) { 117 return $response; 118 } 119 $token = self::makeToken($data['Pluf_Session_key']); 120 $extra = '<div style="display:none;"><input type="hidden" name="csrfmiddlewaretoken" value="'.$token.'" /></div>'; 121 $response->content = preg_replace('/(<form\W[^>]*\bmethod=(\'|"|)POST(\'|"|)\b[^>]*>)/i', '$1'.$extra, $response->content); 122 return $response; 123 } Found it while searching for csrf.php online Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-874933 Share on other sites More sharing options...
yanjchan Posted July 15, 2009 Author Share Posted July 15, 2009 Gah, bumpity bump bump. (I think i must be posting at the wrong time or something) Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-875515 Share on other sites More sharing options...
yanjchan Posted July 15, 2009 Author Share Posted July 15, 2009 Bump yet again. (This forum is too actrive.) XD Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-875866 Share on other sites More sharing options...
phporcaffeine Posted July 16, 2009 Share Posted July 16, 2009 This is a very basic login script, it is real easy to see how it works and understand what is going on. http://codetree.rthconsultants.com/2009/07/php-a-simple-login-script/ Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-876163 Share on other sites More sharing options...
yanjchan Posted July 16, 2009 Author Share Posted July 16, 2009 Yes, I have already written something like that for myself. However, I am waiting to get a more secure one. D: Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-876173 Share on other sites More sharing options...
pengu Posted July 16, 2009 Share Posted July 16, 2009 What is the best method for security? At present I'm using mysql_real_escape_string for my login to protect it from "sql injection". Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-876197 Share on other sites More sharing options...
yanjchan Posted July 16, 2009 Author Share Posted July 16, 2009 We both need help! Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-876233 Share on other sites More sharing options...
yanjchan Posted July 18, 2009 Author Share Posted July 18, 2009 Help with this error please. Using require('authent.php'); if (!empty($_SESSION['useragent']) && (!strcmp($_SESSION['useragent'], hashPassword($_SERVER['HTTP_USER_AGENT']))) || !strcmp($_SESSION['userip'], hashPassword(getip())) { session_destroy(); header('Location: login.php'); } , I get Parse error: syntax error, unexpected '{' in /home/s2zsl9rx/public_html/citizen/authentverify.php on line 3 help please Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-877472 Share on other sites More sharing options...
ignace Posted July 19, 2009 Share Posted July 19, 2009 require('authent.php'); if (!empty($_SESSION['useragent']) && (!strcmp($_SESSION['useragent'], hashPassword($_SERVER['HTTP_USER_AGENT']))) || !strcmp($_SESSION['userip'], hashPassword(getip())) { session_destroy(); header('Location: login.php'); }//<-you forgot this Quote Link to comment https://forums.phpfreaks.com/topic/165543-solved-php-login-script/#findComment-878106 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.