PHP - One Login Form 2 Tables
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> 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 there, I've just registered here and had a quick look around but couldn't find the answer I was looking for so I hope I'm posting this question in the right place. I want to write a PHP Login/Registration script that I can run on a website I am developing for a client but this website has more than one piece of software on it (each with it's own user-tables) and this is the first time I have had to integrate software before so I need a bit of help. When a user fills in the registration form, that data needs to be sent to the relevent user-tables for each application running on the website & when a user logs in, they need to be authenticated for each of the applications also so that we can have a one-click login process. I hop 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??? 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 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>"); } ?> I'm not sure where the issue really lies after the form submits it DOES perform the error messages if there is one, however if the username and password are atleast filled in and the user clicks Log In it doesn't do anything after that. login.php <?php /** * @author Jeff Davidson * @copyright 2010 */ if (isset($_POST['submitted'])) { require_once ('inc/login_functions.php'); require_once ('inc/dbconfig.php'); list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']); if ($check) { // OK! // Set the session data:. session_start(); $_SESSION['id'] = $data['id']; $_SESSION['firstname'] = $data['firstname']; // Redirect: $url = absolute_url ('loggedin.php'); header("Location: $url"); exit(); }else { // Unsuccessful! $errors = $data; } mysqli_close($dbc); } // End of the main submit conditional. include ('inc/login_page.php') ?> login_functions.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // This page defines two functions used by the login/logout process. /* This function determines and returns an absolute URL. * It takes one argument: the page that concludes the URL. * The argument defaults to index.php. */ function absolute_url($page = 'index.php') { // Start defining the URL... // URL is http://plus the host name plus the current directory: $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Remove any trailing slashing: $url = rtrim($url, '/\\'); // Add the page $url .= '/' . $page; // Return the URL: return $url; } // End of absolute_url() function. /* This function validates the form data (the username and password). * If both are present, teh database is queried. * The function requires a database connection. * The function returns an array of information, including: * - a TRUE/FALSE variable indicating success * - an array of either errors or the database result */ function check_login($dbc, $username = '', $password = '') { $errors = array(); // Initialize error array. // Validate the username if (empty($username)) { $errors[] = 'You forgot to enter your username.'; } else { $u = mysqli_real_escape_string($dbc, trim($username)); } // Validate the password: if (empty($password)) { $errors[] = 'You forgot to enter your password.'; } else { $p = mysqli_real_escape_string($dbc, trim($password)); } if (empty($errors)) { // If everythings OK. // Retrieve the firstname and lastname for the username/password combination: $q = "SELECT id, firstname FROM users WHERE username='$u' AND password=SHA('$p')"; $r = @mysqli_query($dbc, $q); // Run teh query. // Check the result: if (mysqli_num_rows($r) == 1) { // Fetch the record: $row = mysqli_fetch_array($r, MYSQLI_ASSOC); // Return true and the record: return array(true, $row); }else { // Not a match! $errrors[] = 'The username and password entered do not match those on file.'; } } // End of empty ($errrors) IF. // Return false and the errors: return array(false, $errors); } //End of check_login() function. ?> login_page.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // This page prints any errors associated with logging in and creates the login, including the form. // Prints any error messages, if they exists: if (!empty($errors)) { echo '<h1>Error!</h1> <p class="error">The following error(s) occured:<br />'; foreach ($errors as $msg) { echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p>'; } // Display the form: ?> <!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=utf-8" /> <meta name="description" content="Caracole" /> <title>Titanium</title> <link HREF="favicon.ico" type="image/x-icon" rel="icon" /> <link HREF="favicon.ico" type="image/x-icon" rel="shortcut icon" /> <link rel="stylesheet" type="text/css" href="css/tripoli.simple.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/base.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/layout.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/theme.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/icons.css" media="screen, projection, print" /> <script type="text/javascript" SRC="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> //<![CDATA[ document.write('<link rel="stylesheet" type="text/css" href="css/js/js.css" media="screen, projection, print" />'); //]]> $(document).ready(function(){ $(".close").click(function(){ $(this).parents(".message").hide("puff"); }); }); </script> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/ie/ie.css" media="screen, projection, print" /> <![endif]--> <!--[if lt IE 7]> <script src="js/DD_belatedPNG_0.0.7a-min.js" type="text/javascript"></script> <script> DD_belatedPNG.fix(' #header, h1, h1 a, .close, .field,.paginate .current, .icon, .required-icon'); </script> <link rel="stylesheet" href="css/ie/ie6.css" type="text/css" media="screen, projection"/> <![endif]--> </head> <body> <!-- Content --> <div id="login" class="content"> <div class="roundedBorders login-box"> <!-- Title --> <div id="title" class="b2"> <h2>Log In</h2> <!-- TitleActions --> <div id="titleActions"> <div class="actionBlock"> <a href="#">Forgot your password ?</a> </div> </div> <!-- /TitleActions --> </div> <!-- Title --> <!-- Inner Content --> <div id="innerContent"> <form action="login.php" method="post"> <div class="field"> <label for="username">Username</label> <input type="text" class="text" id="username" name="username" /> </div> <div class="field"> <label for="password">Password</label> <input type="password" class="text" id="password" name="password"/> </div> <div class="clearfix login-submit"> <span class="fleft"> <input type="checkbox" name="remember-me" id="remember-me" /> <label for="remember-me">Remember me</label> </span> <span class="fright"> <button class="button" type="submit" name="submit"><strong>Log In</strong></button> </span> </div> <input type="hidden" value="TRUE" name="submitted" /> </form> </div> <!-- /Inner Content --> <div class="bBottom"><div></div></div> </div> </div> </body> </html> loggedin.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // The user is redirected here from login.php. session_start(); // Star the session. // If no session value is present, redirect the user: if (!isset($_SESSION['id'])) { require_once('inc/login_functions.php'); $url = absolute_url(); header("Location: $url"); exit(); } $page_title = 'Logged In!'; // Print a customized message: echo "<h1>Logged In!</h1> <p>You are now logged in, {$_SESSION['firstname']}!</p> <p><a href=\"logout.php\">Logout</a></p>"; ?> I thought I'd come back in and insert the file manager I have setup here. root/loggedin.php root/login.php root/inc/login_page.php root/inc/login_functions.php 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); }); } } }); 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?! 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"); } } ?> Hey all, I am trying to put a login form on the front pages (index, contact us, about us) of my site. I want the members to put in username and pass, and when they click submit, it takes them to the /members/ area of the site. Right now this is how I have the form. Code: [Select] <form method="POST" action="login.php"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="Login"> </form> I have this, but the members area consist of several pages and not just on location. Code: [Select] if ($_SESSION['authorized'] != true) { header("Location: login_form.php"); exit; } Finally, I am going to create a login.php page that has this in it. Code: [Select] $select_user = mysql_query('select * from users where username = "' . $_POST['username'] . '" and password = "' . md5($_POST['password'] . '"')); if (mysql_num_rows($select_user) != 0) { session_start(); session_register('authorized'); $_SESSION['authorized'] = true; header("Location: protected_content.php"); exit; } else { header("Location: login_form.php"); exit; } So My questions are, How can I make it so they can access the entire /members/ area (directory) and what would I put in the database 'members' when I create it. All members are going to use the same username and pass. So there is only need for 1 query for username and 1 for password. I appreciate anyone help in advance. 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); } ?> when I test this script on browser. This is all that I see. invalid username or password Code: [Select] <?php //start session session_start(); include 'functions.php'; if (loggedin()) { header("Location: userarea.php"); exit(); } if ($_POST['login']) { //get data $username = $_POST['username']; $password = $_POST['password']; $rememberme = $_POST['rememberme']; } if (username&&$password) { $login = mysql_query("SELECT * FROM users WHERE username='$username'"); while ($row = mysql_fetch_assoc($login)) { $db_password = $row['password']; if (md5($password)==$db_password) $loginok =TRUE; else $loginok = FALSE; if ($loginok ==TRUE); { if($rememberme=="on") setcookie("username",$username, time()+7200); else if ($rememberme=="") $_SESSION['username']=$username; header("Location: userarea.php"); exit(); } } } else { die("invalid username or password"); } ?> <form action="login.php" method="POST"> username:<br /> <input type="text" name="username" /><br /> password:<br /> <input type="password" name="password" /><br /> <input type="checkbox" name="rememberme">remember me<br /> <input type="submit" name="login" value="Log in" /> </form> 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; } Hi I'm a beginner and I would like to create a simple login form by using PDO connection. I wrote all these codes but nothing happened. The only thing I know is my PDO connection is working. Any help I appreciate that. login form:
<!DOCTYPE html>
<form method="post" action="loginaccess.php"> </form>
<?php
?> </html>
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 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 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 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"; } }
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"; } } ?> |