PHP - Php Login Form Validation
Hi my code below checks for Username and password from a form and if they match those in database, it redirects to main.php However, I would like some help setting up error page?!
at the moment if the username or password are incorrect and teh form is submitted, the pages just goes white and blank?! <?php session_start(); include_once("config.php"); checkLoggedIn("no"); if(isset($_POST["submit"])) { field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 3, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 3, 15); if($messages){ doIndex(); exit; } if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { $messages[]="Incorrect login/password, try again"; } if($messages){ doIndex(); exit; } cleanMemberSession($row["rsUser"], $row["rsPass"], $row["UserID"]); if ($user = checkPass($_REQUEST['rsUser'], $_REQUEST['rsPass'])) { cleanMemberSession($user['rsUser'], $user['rsPass'], $user['UserID']); } else { echo('Login failed'); } header("Location: main.php"); } else { doIndex(); } function doIndex() { global $messages; global $title; } ?> Login failed does not get shown if a username is entered wrong?! Similar Tutorialshi 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, just been writing this script up but for some reason the validation is messing up creating account, apparently nothing is valid that i put in Any ideas? the .phps are below and the .inc ar all below. Also when i try to log in with an existing user it says i cant because the username or password is incorrect which is isn't. Any help will be much appreciated. Enlighten Code: [Select] <?php /* File: login_reg_form.inc * Desc: Contains the code for a web page that displays two html forms, side by side. One is a login form, and the second is a registration form. */ include("functions.inc"); ?> <head><title>Customer Login page</title> <style type='text/css'> <!-- label { font-weight: bold; float: left; width: 27%; margin-right: .5em; text-align: right; } legend { font-weight: bold; font-size: 1.2em; margin-bottom: .5em; } #wrapper { margin: 0; padding: 0; } #login { position: absolute; left: 0; width: 40%; padding: 1em 0; } #reg { position: absolute; left: 40%; width: 60%; padding: 1em 0; } #field { padding-bottom: .5em; } .errors { font-weight: bold; font-style: italic; font-size: 90% color: red; margin-top: 0; } --> </style> </head> <body style="margin: 0"> <?php $fields_1 = array("fusername" => "User Name", "fpassword" => "Password"); $fields_2 = array("user_name" => "User Name", "password" => "Password", "email" => "Email", "first_name" => "First Name", "last_name" => "Last Name", "street" => "Street", "city" => "City", "county" => "County", "post_code" => "Post Code", "phone" => "Phone", "fax" => "Fax"); ?> <div id="wrapper"> <div id="login"> <form action=<?php echo $_SERVER['PHP_SELF']?> method="POST"> <fieldset style='border: 2px solid #000000'> <legend>Login Form</legend> <?php if (isset($message_1)) { echo "<p class='errors'>$message_1</p>\n"; } foreach ($fields_1 as $field => $value) { if(preg_match("/pass/i", $field)) $type = "password"; else $type = "text"; echo "<div id ='field'> <label for='$field'>$value</label> <input id='$field' name='$field' type= '$type' value='".@$$field."' size='20' maxlength='50' /> </div>\n"; } ?> <input type="submit" name="Button" style='margin-left: 45%; margin-bottom: .5em' value="Login" /> </fieldset> </form> <p style='text-align: center; margin: 1em'> If you already have an account, log in.</p> <p style='text-align: center; margin: 1em'> If you do not have an account, register now.</p> </div> <div id='reg'> <form action=<?php echo $_SERVER['PHP_SELF']?> method="POST"> <fieldset style='border: 2px solid #000000'> <legend>Registration form</legend> <?php if(isset($message_2)) { echo "<p class='errors'>$message_2</p>\n"; } foreach($fields_2 as $field => $value) { if (preg_match("/pass/i", $field)) $type="password"; else $type="text"; echo "<div id='field'> <label for='$field'>$value</label> <input id='$field' name='$field' type='$type' value='".@$$field."' size='40' maxlength='65' /> </div>\n"; } // end foreach field ?> <input type="submit" name="Button" style='margin-left: 45%; margin-bottom: .5em' value="Register"> </fieldset> </form> </div> </div> </body></html> 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. Dear all, Please help me. I have two sites and both run on separate DB, both have separate signup and login process, Now i want if any user login from any site can access both sites. There are separate session for both sites now i want to use any of the session for user authentication. Please give suggestions. Thanks, I'm not sure why, but once I added a search form in my nav menu, it made my other forms on the website such as login and signup form take them to where the search button would take them. any ideas??? Hello, guys i hope you will help me with this cause i'm a complete newbie. First 2 words about the goal : I want to make a PHP script to autologin in one webpage and to get statistics in every 2 minutes. The account is mine so i dont want to scam or anything , just want to automate it cause this info i need in realtime, and refreshed often. The page login page code looks like this : Code: [Select] <dl> <dt>Username:</dt> <dd><input type="text" name="user" size="20" value="" class="input_text" /></dd> <dt>Password:</dt> <dd><input type="password" name="passwrd" value="" size="20" class="input_password" /></dd> </dl> <dl> <dt>Minutes to stay logged in:</dt> <dd><input type="text" name="cookielength" size="4" maxlength="4" value="60" class="input_text" /></dd> <dt>Always stay logged in:</dt> <dd><input type="checkbox" name="cookieneverexp" class="input_check" onclick="this.form.cookielength.disabled = this.checked;" /></dd> </dl> <p><input type="submit" value="Login" class="button_submit" /></p> and i try login like that : Code: [Select] $_login_url = 'URL of the login'; // url to login :) $_user = 'myusername'; // username for login $_pass = 'mypass'; // password.. $start = microtime(true); file_get_contents( $_login_url, false, stream_context_create( array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query( array( 'user' => $_user, 'passwrd' => $_pass, 'cookielength' => '-1', //what here ???? 'Login', ) ), ) ) ) ); $search['from'] = 'Set-Cookie: '; $search['to'] = ';'; $cookie = array(); //the problem is that i cant login to go to the statistics page, cause site requires login for view. User fills log in form on another page, but is then presented with "Your username cannot be found or password doesnt match" untill they press F5.... any ideas anyone? Code: [Select] <?php mysql_connect("localhost","ambroid_mike","347610"); @mysql_select_db("ambroid_findapart") or die( "Unable to select database"); $user = $_POST['user']; $pass = $_POST['pass']; $mysqluser = ereg_replace("_", "\_", $user); $query = "SELECT password FROM users WHERE username LIKE BINARY '$mysqluser'"; $result = mysql_query($query) or die("Error: ".mysql_error()); $row = mysql_fetch_array($result, MYSQL_NUM); $foundpass = $row[0]; if ($foundpass == $pass) { setcookie("FAPusername", $user); setcookie("FAPpassword", sha1($foundpass)); $user = $_COOKIE['FAPusername']; $pass = $_COOKIE['FAPpassword']; } $query = "SELECT * FROM users WHERE username='$user'"; $result = mysql_query($query) or die("Error: ".mysql_error()); $info = array(); $info = mysql_fetch_array($result, MYSQL_NUM); $original = array(); $original = $info; if (sha1($info[2]) != $pass) { mysql_close(); die("<br><br><center><body bgcolor='#FFFFFF'><b><font face='Verdana' size='2pt'>Your username cannot be found or password doesnt match</font></b></center></body></html>"); } ?> Hi guys, I'm currently in the process of creating a login form. I'm using PHP to check a simple text file called 'users.txt' for the username and password which has been entered in the form. If the username and password are NOT in the 'users.txt' file, it will create them on a new line. Like so: Users.txt Code: [Select] ExampleUser,ExamplePass\n Marc,password Craig,password John,password Once I try to log into an account which is NOT there, it will create an account underneath. So if I try to log in with username as "Matthew" and password as "password" it will show like so: Code: [Select] ExampleUser,ExamplePass\n Marc,password Craig,password John,password Matthew,password Hoping this makes sense so far, all of the above works. However when I click back, to go back onto the login form, I try to log in with one of the usernames/passwords in the 'users.txt' file, and it will create the exact same user on a new line, so I have 2 of the same usernames/passwords. What I want it to do it, if the username is in the 'users.txt' file, for it to display a message saying "Congratulations you're logged in". Here is the code for the PHP login page. P4 LoginScriptFile.php Code: [Select] <?php //This checks for required fields from the form. if ((!$_POST[username]) || (!$_POST[password])) { header("Location: P4 LoginForm.php"); exit; } //This reads values from the form. $form_user = $_POST[username]; $form_password = $_POST[password]; $flag = FALSE; $filename = "users.txt"; $fp = fopen( $filename, "r" ) or die ("Couldn't open $filename"); while ( ! feof( $fp ) ) { $line = fgets( $fp); $user = strtok($line, ","); //Username $password = strtok(","); //Password if (($form_user == $user) && ($form_password == $password)) { $flag = TRUE; } } if ($flag) { echo "<br>Congratulations, you're logged in"; } else{ $filename = "users.txt"; $updateuser = $_POST ['username']; $updatepass = $_POST ['password']; $fp = fopen( $filename, "a" ) or die("Couldn't open $filename"); fwrite( $fp, "$updateuser,$updatepass\n") or die ("Couldn't write values to your file!"); fclose( $fp ); echo "<br>An account has been created for you!"; } ?> I think what I need is to read the file once the new user has been created. Any help would be greatly appreciated. Thanks in advance for any help. gixxx Hi I am new to php and I have a login form for users that works ok with a mysql database table for users. The problem I have is that it only takes all loggedin users to the same page and I want to take logged in users to their own page. I should have no more than 5 users at anyone time and for example I will call them simply user1, user2, user3, user4 and user 5. I want user1 to go to user1.php, user2 to go to user2.php and so on. The login.php code is as follows, can someone please tell me in laymans terms how to change it to accommodate this: Code: [Select] <?php include 'dbc.php'; $err = array(); foreach($_GET as $key => $value) { $get[$key] = filter($value); //get variables are filtered. } if ($_POST['doLogin']=='Login') { foreach($_POST as $key => $value) { $data[$key] = filter($value); // post variables are filtered } $user_email = $data['usr_email']; $pass = $data['pwd']; if (strpos($user_email,'@') === false) { $user_cond = "user_name='$user_email'"; } else { $user_cond = "user_email='$user_email'"; } $result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE $user_cond AND `banned` = '0' ") or die (mysql_error()); $num = mysql_num_rows($result); // Match row found with more than 1 results - the user is authenticated. if ( $num > 0 ) { list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result); if(!$approved) { //$msg = urlencode("Account not activated. Please check your email for activation code"); $err[] = "Account not activated. Please check your email for activation code"; //header("Location: login.php?msg=$msg"); //exit(); } //check against salt if ($pwd === PwdHash($pass,substr($pwd,0,9))) { if(empty($err)){ // this sets session and logs user in session_start(); session_regenerate_id (true); //prevent against session fixation attacks. // this sets variables in the session $_SESSION['user_id']= $id; $_SESSION['user_name'] = $full_name; $_SESSION['user_level'] = $user_level; $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); //update the timestamp and key for cookie $stamp = time(); $ckey = GenKey(); mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error()); //set a cookie if(isset($_POST['remember'])){ setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/"); } header("Location: myaccount.php"); } } else { //$msg = urlencode("Invalid Login. Please try again with correct user email and password. "); $err[] = "Invalid Login. Please try again with correct user email and password."; //header("Location: login.php?msg=$msg"); } } else { $err[] = "Error - Invalid login. No such user exists"; } } ?> Hello guys, first post here.
I have a web system which contains a login form programmed in 3 different languages HTML, PHP and JS. The problem is that it's not working, you can access without entering any data, you just press enter and it will work, I don't know why it is not validating any credentials. I was thinking about some query problems but I don't know. I am a newbie on this. I have read a lot but haven't found an answer. A friend helped me build the system but left that uncompleted and he's nowhere to be found.
I was wondering if you could help me out with this.
<form role="form" ng-submit="login(user,password)"> <div class="form-group"> <input type="user" class="form-control" ng-model='user' placeholder="Usuario"> </div> <div class="form-group"> <input type="password" class="form-control" ng-model='password' placeholder="Contraseña"> </div> <div class="alert alert-warning" id='alert' style="display:none">Revise la informacion...</div> <div class="alert alert-danger" style="display:none" id='alertErr'>Error Usuario o Contraseña Erronea intentelo de nuevo</div> <button type="submit" class="btn btn-primary">Ingresar</button> </form> <?php require_once 'database.php'; $db = new Database(); $body = json_decode(file_get_contents('php://input')); $user =$db->query("SELECT * FROM usuario WHERE usua_login = '".$body->user."' AND usua_pass = '".$body->password."'"); if($user == false){ http_response_code(404); } else{ http_response_code(200); echo json_encode($user); } ?> 'use strict'; /** * @ngdoc function * @name belkitaerpApp.controller:MainCtrl * @description * # MainCtrl * Controller of the belkitaerpApp */ angular.module('belkitaerpApp') .controller('MainCtrl', function ($scope,$http,$location) { $scope.login = function(user,password){ console.log('Login...'); if(user =='' || password ==''){ $('#alert').show("slow"); setTimeout(function() { $('#alert').hide('slow'); }, 3000); } else{ $http.post('../serverSide/login.php',{user:user,password:password}).success(function(data){ console.log('OK!'); $location.path('/products'); }).error(function(data){ $('#alertErr').show("slow"); setTimeout(function() { $('#alertErr').hide('slow'); }, 3000); }); } } }); I must be losing my marbles on this one: I have a standard login form that queries my MySQL database for user info, but the problem doesn't even get that far. Here's the form: Code: [Select] <div id="login_form"> <form action="access/" method="post"> <input type="text" name="username" class="username" /><br> <input type="password" name="password" class="password" /><br> <input type="submit" class="submit" value=""> </form> </div> Then the backend: <?php echo '<pre>'; print_r($_POST); echo '</pre>'; //The rest of the validation is beyond here... ?> Lets say in the db I have username = 'test' and password = 'test1234', when I enter the correct username and password the POST array displays blank: Code: [Select] array ( ) So then, I enter another entry, lets say I enter username = 'test' and password = 'test2468', but the mysql stays the same: I get this: Code: [Select] array( [username] => test [password] => test2468 } So then, because at this point i'm 98% sure i've lost my mind I go in and change the password in the DB to match the new entry. So now mysql db says username = 'test' and password = 'test2468' I try using that info again and voila: Code: [Select] array ( ) Has anyone run into something similar to this, the info is not interacting with the database in any way at this point, yet it seems to be affecting it. Thanks for any help you can offer, and for not thinking i'm crazy E Right I'm going to try and explain what i'm trying to do and i'll post the code i have at the bottom. Whatever I do I seem to get a new error and I can't get any closer to getting the script right!!! I give up myself. There's only so much one man can take!!!!!!! I have a database with two table. Members owners Both tables have the same fields for the login section! username password (stored in md5 format) access_level Now I'm trying to make a script that selects both tables and finds the username. then checks that the md5 of the password entered into the field is equal to the stored md5 password in the database. if details are correct it sends the person to the correct page while updating a table called mem_logins with the email of the user loging in as a feild along with the time, If there is no account at all it sends them to the create account page, if the access level is equal to 1 or 50 it sends them to the check_email.php Now I'm very new to php and therefore have most certainly written the script wrong. I have been tryig to sort the errors for days and now, have given up. Can anyone help? Here is the code as it stands and at the minute im getting this error..... mysql_num_rows(): supplied argument is not a valid MySQL result resource in site on line 11 <?php include('Connections/YA1.php'); session_start(); ?> <?php if(isset($_POST['submit3'])) { $qCheckUserInfo = "SELECT * FROM Members, owners WHERE username='".mysql_real_escape_string($_POST['username3'])."'"; $rCheckUserInfo = mysql_query($qCheckUserInfo); $numUsers = mysql_num_rows($rCheckUserInfo); if($numUsers == 0) { $message = "Incorrect login details"; $success = 0; } else { $userInfo = mysql_fetch_array($rCheckUserInfo); $password = $userInfo['password']; $email = $userInfo ['email']; if($password == md5($_POST['password3'])) { $success = 1; $_SESSION['logged'] = 1; $_SESSION['club_id'] = $userInfo['club_id']; $_SESSION['username'] = $userInfo['username']; $today = date("Y-m-d h:m:s"); if($_SESSION['access_level'] == 1) { $sql = "INSERT INTO mem_logins `email`, `login` VALUES ('$email','$today')"; mysql_query($sql) or die ("could not execute insert."); header('Location: check_email.php'); } else if($_SESSION['access_level'] == 2) { $sql = "INSERT INTO mem_logins `email`, `login` VALUES ('$email','$today')"; mysql_query($sql) or die ("could not execute insert."); header('Location: members/index.php'); } else if($_SESSION['access_level'] ==50) { $sql = "INSERT INTO mem_logins `email`, `login` VALUES ('$email','$today')"; mysql_query($sql) or die ("could not execute insert."); header('Location: check_email.php'); } else if($_SESSION['access_level'] == 51) { $sql = "INSERT INTO mem_logins `email`, `login` VALUES ('$email','$today')"; mysql_query($sql) or die ("could not execute insert."); header('Location: clubs/index.php'); } else if($_SESSION['access_level'] == 99) { $sql = "INSERT INTO mem_logins `email`, `login` VALUES ('$email','$today')"; mysql_query($sql) or die ("could not execute insert."); header('Location: admin/D/index.php'); } } else { $message = "Incorrect login details"; $success = 0; } } } ?> <body> <div id="wrapper"> <div id="title_box"> <div id="logo"><img src="image/your_arena.jpg" /></div> <div id="login_box"> <?php if($success==0) { echo $message; } else { echo ' '; } ?> <?php if($success != 1 && !($_SESSION['logged'])) { ?><?php ?> <form METHOD="POST" name="login_form" class="black_text" id="login_form"> <table width="252" border="0" align="right" cellpadding="0" cellspacing="5" id="login_tab"> <tr> <td width="84"><div align="left">Username:</div></td> <td><input name="username3" type="text" class="form_fields" value="<?php echo $_POST['username3']; ?>" id="username3" tabindex="1" /></td> </tr> <tr> <td><div align="left">Password:</div></td> <td><input name="password3" type="password" class="form_fields" id="password3" tabindex="2" /></td> </tr> <tr> <td colspan="2"></td> </tr> <tr> <td colspan="2" class="forgotten_pass"><div align="right">Forgotten your password?</div></td> </tr> <tr> <td height="24"><div align="left"></div></td> <td><div align="right"> <input name="submit3" type="submit" id="submit3" tabindex="3" value="Login" /> </div></td> </tr> </table> <?php } //end fail if ?> </form> </div> </div> <?php include('nav.php');?> <div id="test">main page </div> <?php include('footer.php');?> </div> </body> </html> I'm using a login form which allows me enter the pages as member only the only thing that I need to do is to include the file safe.php and the user has to login in order to see the content of this page. so far so good. if I use my subscription forms ( spread over 2 pages) the first page can be filled in properly however when I come to the second page (where I included the safe.php aswell I think I loose the session ID that I got after logging in the first time) I am redirected to the login page which I don't want. how can I avoid this? this is the content of safe.php Code: [Select] <?php // Pagina: safe.php: Includen if you want te securise your page just add it at the top of your page 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"); } } ?> Hello everybody, I need to make a login form and I need to complete that this sunday. I done pretty much most of it, except 1, pretty important thing. That is letting the username stay in the form field when only the password field is wrong. But for that, I need to stay on the same page and the problem is I need to use a switch, so that gets a little difficult for me. I also MUST use template power, that's why I only show my PHP code. I saw a video on YouTube, where they explained to use different files and link them to each other by using require and include. They used a index.php file and a loginform.inc.php. But since I'm using template power AND a switch, I don't think that will help me. But he did used something like isset and also header function. And he managed to stay on the same page, by using index and loginform.inc. Is there a way I can use that do? Or do I have to use something totally different? Thanks much for any help Code: [Select] <?php session_start(); $link = mysql_connect('localhost', 'root', ''); $db_selected = mysql_select_db('mydb', $link); error_reporting(0); include("includes/class.TemplatePower.inc.php"); $tpl = new TemplatePower("Werkbron4.html"); $tpl->prepare(); switch($_GET['actie']) { case logout: if($_POST['submit']) // controleren of er op logout gedrukt is { $_SESSION['accountsid'] = ""; $_SESSION['groepenid'] = ""; // de sessie leeghalen $tpl->newBlock("LOGOUT_SESSION"); $tpl->assign("LOGOUT_SESSION", "U bent uitgelogd."); // tekst weergeven nadat er op logout gedrukt is } else { $tpl->newBlock("LOGOUT_FORM"); // zo niet, terug naar formulier } break; case login_sql: if($_POST['gebruikersnaam'] AND $_POST['wachtwoord']) // controleren of er een gebruikersnaam en wachtwoord is ingevuld { $gebruikersnaam = mysql_real_escape_string($_POST['gebruikersnaam']); $wachtwoord = mysql_real_escape_string($_POST['wachtwoord']); // zo ja, beveilig de gebruikersnaam en het wachtwoord tegen SQL injecties $check = mysql_query("SELECT * FROM accounts WHERE gebruikersnaam='".$gebruikersnaam."' AND wachtwoord='".sha1($wachtwoord)."'"); // haal de gegevens uit de database met deze query if(mysql_num_rows($check) == 1) // controleren of de gegevens over een komen. later bijwerken { $info = mysql_fetch_array($check); // ?? later bijwerken $_SESSION['accountsid'] = $info['accountsid']; $_SESSION['groepenid'] = $info['groepenid']; // gegevens in de sessie zetten $tpl->newBlock("LOGOUT_FORM"); // laat de logout form zien $tpl->newBlock("TEXT_INLOG"); $tpl->assign("TEXT_INLOG", "U bent ingelogd."); // deze tekst laten zien indien er succesvol ingelogd is if($_SESSION['groepenid'] == 1) // kijken of het groepenid van het account dat inlogt overeenkomt met het groepenid 1 { $tpl->newBlock("LOGIN_KLANT"); $tpl->assign("LOGIN_KLANT", "Welkom klant!"); // zo ja, laat deze tekst zien en eventueel andere informatie die een klant mag zien/doen } elseif($_SESSION['groepenid'] == 2) // kijken of het groepenid van het account dat inlogt overeenkomt met het groepenid 2 { $tpl->newBlock("LOGIN_ADMIN"); $tpl->assign("LOGIN_ADMIN", "Welkom Admin!"); // zo ja, laat deze tekst zien en eventueel andere informatie die een admin mag zien/doen } else { $tpl->newBlock("ERROR_GEEN"); $tpl->assign("ERROR_GEEN", "U heeft geen toestemming om hier te komen."); // deze tekst laten zien als een account inlogt met een ander groepenid dan 1 of 2 } } else { $check2 = mysql_query("SELECT * FROM accounts WHERE gebruikersnaam='".$gebruikersnaam."'"); // controleren of de ingevulde gebruikersnaam overeenkomt met degene in de database if(mysql_num_rows($check2) == 1) { $tpl->newBlock("ERROR_PASS"); $tpl->assign("ERROR_PASS", "U heeft een ongeldig wachtwoord ingevuld."); // deze tekst laten zien als de ingevulde gebruikersnaam correct is, maar het wachtwoord niet } else { $tpl->newBlock("ERROR_GEB"); $tpl->assign("ERROR_GEB", "U heeft een ongeldige gebruikersnaam ingevuld."); // deze tekst laten zien als de ingevulde gebruikersnaam ongeldig is } } } break; default: $tpl->newBlock("LOGIN_FORM"); } $tpl->printToScreen(); ?> I'm always getting the "Falha ao selecionar o usuario no banco de dados." error. Why??? Another thing, any tip to improve my code? A way to do the same thing, but with a "more clean" code... login.php Code: [Select] <?php session_start(); require_once('../includes/link.php'); include('../functions/clean.php'); $errmsg_arr = array(); $errflag = false; $email = clean($_POST['email']); $password = clean($_POST['password']); if(($email == '') OR ($password == '')) { $errmsg_arr[] = 'Por favor, preencha todos os campos.'; $errflag = true; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } $query = "SELECT * FROM users WHERE email = '$email' AND passwd = '".md5($_POST['password'])."'"; $result = mysql_query($query); $user = mysql_fetch_assoc($result); if($result) { if(mysql_num_rows($result) == 1) { $user = mysql_fetch_assoc($result); session_regenerate_id(); $_SESSION['SESS_ID'] = $user['id']; $_SESSION['SESS_STATUS'] = $user['status']; $_SESSION['SESS_SCHOOL_ID'] = $user['school_id']; $_SESSION['SESS_CLASS_ID'] = $user['class_id']; $_SESSION['SESS_NAME'] = $user['name']; $_SESSION['SESS_REGISTRATION'] = $user['registration']; $_SESSION['SESS_EMAIL'] = $user['email']; session_write_close(); if($_SESSION['SESS_STATUS'] == 1) { header("location: ../users/superadministrator/index.php"); exit(); } } else { $errmsg_arr[] = 'Suas informacoes de login estao incorreta. Por favor, tente novamente.'; $errflag = true; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } } else { die("Falha ao selecionar o usuario no banco de dados."); } ?> link.php Code: [Select] <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'social_escola'); $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if (!$link) { die('Falha ao conectar ao servidor: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if (!$db) { die('Falha ao selecionar o banco de dados: ' . mysql_error()); } ?> clean.php Code: [Select] <?php function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } ?> I created a login form for my system and I don't sure that it's enought for security to protect my website? include("database.php"); session_start(); if($_SERVER["REQUEST_METHOD"] == "POST") { // username and password sent from form $stmt = $conn->prepare("SELECT Sale_ID FROM tb_sales WHERE Login_Name = ? AND Login_Password = ? LIMIT 1"); $stmt->bind_param("ss", $_POST['username'], $_POST['password']); $stmt->execute(); $res = $stmt->get_result(); $count = mysqli_num_rows($res); if($count == 1) { // session_register("myusername"); $_SESSION['login_user'] = $_POST['username']; echo "Login Succcess"; //header("location: index.php"); }else { echo "Your Login Name or Password is invalid"; } }
I need help getting my login form to redirect to my admin area. I have been following tutorials on youtube trying to create a content management system and have made it as far as creating the form and creating the login action required to look for a username and password form my database and log in. I'll post up the pages I think are required for someone to give me some advice on where im going wrong. my login page login.php Code: [Select] <html> <head> <title>Basic CMS - Admin Area - Login</title> </head> <body> <?PHP session_start(); if(isset($_SESSION['user'])) header("Location: index.php"); ?> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </body> </html> my login actions page dologin.php Code: [Select] <?php include('includes/functions.php'); session_start(); if (isset($_POST['login'])) { if(isset($_POST['username'])) { if(isset($_POST['password'])) { $username = $_POST['username']; $query = mysql_query("SELECT * FROM users WHERE Username = '$username'") or die (mysql_error()); $user = mysql_fetch_array($query); if(md5($_POST['password']) == $user['Password']) { echo "Login successful"; $_SESSION['user'] = $user['Username']; header("Location: index.php"); } else { echo "Please check your login details!"; include('login.php'); } } else { echo "Please check your password!"; include('login.php'); } } else { echo "Please check your username!"; include('login.php'); } } else { echo "Please check that you filled out the login form!"; include('login.php'); } ?> and my admin area index.php Code: [Select] <?php session_start(); if(!isset($_SESSION['user'])) header("Location: admin/login.php"); ?> <html> <head> <title>Basic CMS - Admin Area</title> </head> <body> <span>Logged In! Welcome <?php> echo $_SESSION['user']; ?></span> <a href="logout.php">Logout</a> <a href="posts.php">Manage Posts</a> </body> </html> On logging in I am given "Login succesful" on the dologin.php page but I need it to redirect me to my index.php page, which is my admin area. If there's any other information you need to help me out just let me know. Any help anyone has for me is greatly appreciated! Thank you in advance. Hello,
i got a problem with a part of my code :
<?php In my login form I'm getting the error Code: [Select] Notice: Use of undefined constant Errors - assumed 'Errors' in /home/content/n/a/t/nathanwatson/html/admin/YBK/post.php on line 91 Warning: Cannot modify header information - headers already sent by (output started at /home/content/n/a/t/nathanwatson/html/admin/YBK/post.php:91) in /home/content/n/a/t/nathanwatson/html/admin/YBK/post.php on line 91 Warning: Cannot modify header information - headers already sent by (output started at /home/content/n/a/t/nathanwatson/html/admin/YBK/post.php:91) in /home/content/n/a/t/nathanwatson/html/admin/YBK/post.php on line 92 //if the name exists it gives an error if ($check2 != 0) { //Line 85 $error="<span style="; $error .="color:red"; $error .=">"; $error .= "Sorry, the username is already in use."; $error .="</span>"; setcookie(Errors, $error, time()+20); //Line 91 header('Location: /YBK/'); //Line 92 exit; } |