PHP - Login Form With Sessions
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"); } } ?> Similar TutorialsChecking to see if I am going in the right direction, any suggestions would be appreciated! I am setting up SESSIONs for login and setting a time limit on them. I have basically 2 scenarios that I need to code for. 1. Registerd user w/good billing has all access 2. Registerd user w/expired billing & Guest user can only go to certain pages and have limited access This is my login page, will validate the login info and either sends user to one page or another or gives error that the login is incorrect <?php // http://www.daniweb.com/forums/thread124500.html session_start(); // starting session if( isset($_POST['submitLogin'])) { include('library/login.php'); login(); mysql_select_db('test'); // username and pswd from login $userID=$_POST["userID"]; $pswd=$_POST["pswd"]; // to protect from MySQL injection $userID = stripslashes($userID); $pswd = stripslashes($pswd); $userID = mysql_real_escape_string($userID); $pswd = mysql_real_escape_string($pswd); $sql="SELECT * FROM user WHERE userID='$userID' and pswd='$pswd'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $userID and $pswd, table row must be 1 row if($count == 1) { session_register("userID"); session_register("pswd"); $_SESSION['userID'] = $userID; // verifies billing if ($exp_date >= $todays_date) { // billing is up to date echo "<meta http-equiv='refresh' content='0;url=session2.php'>"; } else { // billing has expired echo "<meta http-equiv='refresh' content='0;url=expBilling.php'>"; } } else { // login form for when there us an incorrect user/password echo " <div id='incorrect'>Please verify the username or password.</div> <form method='post' action='' name='login' id='login'> <div id='loginForm'> <fieldset> <span class='textbox'> <label for='username'>Username: </label> <input type='text' name='userID' size='25' class='cells' value='$userID'> <br><label for='pswd'>Password: </label> <input type='password' name='pswd' size='25'class='cells' value='$pswd'> <br><label for='pswd'> </label>Remember Me: <input type='checkbox' name='Remember' value='21'> <br><label for='blank'> </label><a href='resetPswd.php'>Forget Your Password? </a> <br><label for='blank'> </label><input type='image' value='Login' src='img/button_login.gif' width='64' height='25' onmouseover=\"javascript:this.src='img/button_login2.gif';\" onmouseout=\"javascript:this.src='img/button_login.gif';\"> <input type='hidden' name='submitLogin' value='true'> </span> </fieldset> </div> </form> "; } } else { // log in form echo " <form method='post' action='' name='login' id='login'> <div id='loginForm'> <fieldset> <span class='textbox'> <label for='username'>Username: </label> <input type='text' name='userID' size='25' class='cells'> <br><label for='pswd'>Password: </label> <input type='password' name='pswd' size='25'class='cells'> <br><label for='pswd'> </label>Remember Me: <input type='checkbox' name='Remember' value='21'> <br><label for='blank'> </label><a href='resetPswd.php'>Forget Your Password?</a> <br><label for='blank'> </label><input type='image' value='Login' src='img/button_login.gif' width='65' height='25' onmouseover=\"javascript:this.src='img/button_login2.gif';\" onmouseout=\"javascript:this.src='img/button_login.gif';\"> <input type='hidden' name='submitLogin' value='true'> </span> </fieldset> </div> </form> "; } ?> If the billing is good then user will go here <?PHP session_start(); // session timing // set timeout period in seconds $inactive = 15; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing if(!session_is_registered(userID)){ header("location:login.php"); } ?> <html> <body> Login Successful </body> </html> If the billing has expired user goes here <?php session_start(); // session timing // set timeout period in seconds $inactive = 15; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing // if the user has been timed out or not logged in if(!session_is_registered(userID)){ header("location:form.php"); } // user is logged in and their billing is good else { echo "Warning! <b>"; echo $_SESSION['userID']; echo "</b> Your billing has expired "; } // end session ?> I also created this page to test what happens when a non-subscriber trys to go to a page without logging in, it also test the billing and blocks a user whose billing is expired. <?php session_start(); // session timing // set timeout period in seconds $inactive = 15; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing // if the user has been timed out or not logged in if(session_is_registered(userID)){ // verify billing if user comes in directly thru this page include('library/login.php'); login(); mysql_select_db('test'); $userID = $_SESSION['userID']; $sql="SELECT * FROM user WHERE userID='$userID'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $userID and $pswd, table row must be 1 row if($count == 1) { // checks dates if ($exp_date >= $todays_date) { // billing is up to date echo "Welcome: "; echo $_SESSION['userID']; } else { // billing has expired echo "<meta http-equiv='refresh' content='0;url=expBilling.php'>"; } } // END verify billing } // user is logged in and their billing is good else { echo "Welcome: "; echo "Non-user can view this stuff."; echo "<br><a href='form.php'>Click here to register</a>"; } // end session ?> These are all test pages once I get the coding right I will incorporate it into the real pages. Hi What is the best way of handling a login system with sessions, I have read that you should never hold the password in a session, so what should you hold in the session in order to access a users data? Hello. I am coding a remember me feature. Everything is working, except i am being logged in using cookies even when i want to use a session. To login using a cookie i must select the checkbox, for sessions i must leave it blank. Here is my code, if someone could spot a mistake i would be really grateful. Login page Code: [Select] <?php ob_start(); // starting session... session_start(); // requiring connection... require("functions.php"); // assigning variables... $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $submit = mysql_real_escape_string($_POST['submit']); $rememberme = $_POST['rememberme']; // querying database... $query = mysql_query("SELECT * FROM users WHERE username = '$username'"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $db_username = $row['username']; $db_password = $row['password']; } } // verifying login details... if ($submit) { if (!empty($username) && !empty($password)) { if ($username == $db_username && $password == $db_password) { if ($rememberme = "on") { setcookie("username", $username, time() + 7200); header('Location: tablets.php'); } else { $_SESSION['username'] = $db_username; $url = $_SESSION['origin'] ? $_SESSION['origin'] : "main.php"; unset($_SESSION['origin']); header('Location: ' . $url); exit; } } else { echo "Incorrect login details"; } } else { echo "You must type in username and password"; } } ob_end_flush(); ?> Login form Code: [Select] <?php session_start(); require("connect.php"); if (isset($_SESSION['username']) || isset($_COOKIE['username'])) { header('Location: main.php'); } ?> <!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" xml:lang="en" lang="en"> <head> <title>Login</title> <link rel="stylesheet" type="text/css" href="form.css" /> </head> <body> <form method="post" action="login.php"> <div class="box"> <h1>Login</h1> <label> <span>Username</span> <input type="text" class="input_text" name="username" id="name" /> </label> <label> <span>Password</span> <input type="password" class="input_text" name="password" id="password" /> </label> <input type="checkbox" name="rememberme" /> <label> <input type="submit" class="button" value="Login" name="submit" /> </label> </div> </form> </body> </html> If you are a PHP expert, then I really your help. I have a question regarding PHP sessions and their security. So here is my story ... I created a login script (login.php) for my website. When a user goes to the login.php page, they see a login form that they must fill with their username and password to login to the members' area and view their profile, etc. On that login page, when the user enters their username and password and then clicks the "Login" button, my script filters the data, sends MySQL query and checks if the login is valid. If the login is NOT valid, then they get a "Login Failed" message. If the login is valid, I register their username and the password in sessions and redirect them to the members.php page. Here is some of my code for my login.php page after mysql confirms the login is valid <?php $query = mysql_query('SELECT * FROM `users` WHERE username='$user' AND password='$pass'"); $numRows = mysql_num_rows($query); if ( $numRows ) { // login is valid $_SESSION['username'] = $user; $_SESSION['pass'] = $pass; // redirect user to members area header('Location: /members.php'); } else { // login is invalid echo "Login failed"; } ?> My question is ... is this login script secured? I mean, I am not generating any session id or any cookie. I am just storing the username and the password in two session variables and those are the things that i will use to display the user's profile, etc. Can attackers attack this script? Is this secured or is there any other way I can make it stronger? hi i need help an idea how can i separate members from admins since i dont know how to create login form i used tutorial ( http://www.youtube.com/watch?v=4oSCuEtxRK8 ) (its session login form only that i made it work other tutorials wre too old or something) how what i want to do is separate members and admins because admin need more rights to do now i have idea but dont know will it work like that what i want to do is create additional row in table named it flag and create 0 (inactive user) 1 (member) 2 (admin) will that work? and how can i create different navigation bars for users and admins? do you recommend that i use different folders to create it or just script based on session and flag? I have a form that multiple users are accessing at the same time. Within the form is a project number field. The project number is generated from a function that queries the project table in the database for the maximum project number then adds 1. It's starting to be a problem where multiple users access the form and are given the same project number. The form doesn't insert into the table, instead an excel spreadsheet is generated with the form info and the user emails it to someone else for data entry. Is there a way that I can resolve my issue so that each time someone accesses the form no one receives the same project number? I have two scripts: script1.php and script2.php.
Script1 creates if it doesn't already exist and adds to a session named "SESSION1" and displays it:
Script2 similarly adds to a session named "SESSION2", but then needs to display the session used by the first script (i.e. SESSION1), and then goes back to its original session (SESSION2).
Script1 works perfect. But when Script2 is executed, it changes the session ID in the SESSION1 cookie to the same value as used in its SESSION2 cookie. If Script1 is later executed, it obviously lost its previous session values as it is now using a new session ID.
If I comment out the two session_name() lines, it will not overwrite the other session, however, this doesn't provide the functionality I need.
What is causing this and how do I prevent it????
script1.php
<?php // script 1. Will be accessed as http://one.example.com $t=time(); //Access the primary session for script 1 session_name('SESSION1'); session_start(); $_SESSION['s1_'.$t]=$t; echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>"); ?>script2.php <?php // script 2. Will be accessed as http://two.one.example.com $t=time(); //Access the primary session for script 2 $default_name=session_name('SESSION2'); session_start(); $_SESSION['s2_'.(2*$t)]=2*$t; echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>"); //Use session created by script 1 $old_id_script2 = session_id(); session_write_close(); $old_name_script2 = session_name('SESSION1'); session_start(); echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>"); //Go back to primary session session_write_close(); $old_id_script1 = session_id($old_id_script2); $old_name_script1 = session_name($old_name_script2); session_start(); echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>"); echo("default_name: $default_name<br>"); echo("old_id_script2: $old_id_script2<br>"); echo("old_name_script2: $old_name_script2<br>"); echo("old_id_script1: $old_id_script1<br>"); echo("old_name_script1: $old_name_script1<br>"); ?> Edited by NotionCommotion, 30 November 2014 - 11:45 AM. 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 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. 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); } ?> 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); }); } } }); 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 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 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(); ?> 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> 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"; } }
|