Jump to content

Search the Community

Showing results for tags 'login'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start





Website URL








Donation Link

  1. Error: Parse error: syntax error, unexpected token "else" in C:\Users\brand\OneDrive\Desktop\XAMAPP\htdocs\Water Tower 2000\index.php on line 139 <?php require_once 'connection.php'; session_start (); if(isset ($_SESSION["admin_login"])) { header ("location:admin/admin_home.php"); } if(isset ($_SESSION["parent_login"])) { header ("location:parent/parent_home.php"); } if(isset ($_SESSION["swimmer_login"])) { header ("location:swimmer/swimmer_home.php"); } if (isset ($_REQUEST['btn_login'])) { $email = $_REQUEST ["txt_email"]; $password = $_REQUEST ["txt_password"]; $email = $_REQUEST ["txt_role"]; if(empty($email)){ $errorMsg[]="please enter yout water tower email"; } else if(empty($password)){ $errorMsg[]="please enter yout water tower email"; } else if(empty($role)){ $errorMsg[]="please enter yout water tower email"; } else if($email AND $password AND $role){ try{ $select_stmt=$db->prepare("SELECT email,password,role FROM masterlogin WHERE email=:uemail AND password=:upassword AND role=:urole"); $select_stmt->bindParam(":uemail",$email); $select_stmt->bindParam(":upassword",$password); $select_stmt->bindParam(":uemail",$role); $select_stmt->excute(); while ($row=$select_stmt->fetch(PDO::FETCH_ASSOC)){ $dbemail =$row["email"]; $dbpassword =$row["password"]; $dbrole =$row["role"]; } if($email!=null AND $password!=null AND $role!=null){ if($select_stmt->rowCount()>0){ if ($email!==$dbemail AND $password==$dbpassword AND $role==$dbrole){ switch($dbrole) { case "admin": $_SESSION ["admin_login"]=$email; $loginMsg="Admin...Your in Water Tower..."; header("refresh:3;admin/admin_home.php"); break; case "parent": $_SESSION["parent_login"]=$email; $loginMsg="Parent...Welcome To Water Tower..."; header("refresh:3;parent/parent_home.php"); break; case "swimmer": $_SESSION ["swimmer_login"]=$email; $loginMsg="Fellow swimmer...Your in Water Tower..."; header("refresh:3;swimmer/swimmer_home.php"); break; default: $errorMsg[]="Sorry but either the email/password/role is wrong"; } } else { $errorMsg="Sorry but either the email/password/role is wrong"; } else { $errorMsg="Sorry but either the email/password/role is wrong"; } } else{ $errorMsg="Sorry but either the email/password/role is wrong"; } } } catch (PDOException $e){ $e->getMassage(); } } else { $errorMsg="Sorry but either the email/password/role is wrong"; } } ?>
  2. Hi Freaks, I'm looking for advice if someones willing to give it. Here's the situation -> I've been working on a project, I started to learn PHP specifically to complete this idea I had. My code has evolved a lot over time as I've started understanding more. Up until today I've been working on it with just the registration functionality, no login. I had my username hardcoded into the $user_obj instantiation. I decided I wanted to try to make category subscription functionality and doing that I realized I was better off finishing the login form first so as to get a users subscriptions into a session variable at login. This has brought about the issue of getting an unassigned variable warning from the User class when not logged in. How I made all my other classes was putting a $user in the __construct parameter for each class. I now feel this may have been a rookie error since I'm having problems with error messages especially undefined array keys and variables when there isn't a session started. It's become a bit of a mess. So the advice I'm looking for and hoping to find here is how you folks handle non $_SESSION sessions, when a user is just scrolling the site not logged in. Did I make a mistake requiring $user for each class __construct? should I move the $user parameter to only the methods that require them? Is there a simpler solution that my inexperience causes to elude me? What would you folks do in this situation?
  3. i want to display 'Welcome userid!' after user has successfully logged in. I managed to display it after successfully logged in, but when the user key in the wrong userid and password, the 'Welcome userid' is also displayed. What should i do about it? Below are my coding: login.html processLogin.php index.html
  4. Hello there, I have this as login in function for an application. function login($username, $password) { $db =& $this->db; Kit::ClassLoader('userdata'); if (Config::Version('DBVersion') < 62) { // We can't do CSPRNG because the field doesn't exist, so we need to do standard user login // This can ONLY happen during an upgrade. $dbh = PDOConnect::init(); $sth = $dbh->prepare('SELECT UserID, UserName, UserPassword, UserTypeID FROM `user` WHERE UserName = :userName'); $sth->execute(array('userName' => $username)); $rows = $sth->fetchAll(); if (count($rows) != 1) { setMessage(__('Username or Password incorrect')); return false; } $userInfo = $rows[0]; // Check the password using a MD5 if ($userInfo['UserPassword'] != md5($password)) { setMessage(__('Username or Password incorrect')); return false; } } else { // Get the SALT for this username if (!$userInfo = $db->GetSingleRow(sprintf("SELECT UserID, UserName, UserPassword, UserTypeID, CSPRNG FROM `user` WHERE UserName = '%s'", $db->escape_string($username)))) { setMessage(__('Username or Password incorrect')); return false; } // User Data Object to check the password $userData = new Userdata($db); // Is SALT empty if ($userInfo['CSPRNG'] == 0) { // Check the password using a MD5 if ($userInfo['UserPassword'] != md5($password)) { setMessage(__('Username or Password incorrect')); return false; } // Now that we are validated, generate a new SALT and set the users password. $userData->ChangePassword(Kit::ValidateParam($userInfo['UserID'], _INT), null, $password, $password, true /* Force Change */); } else { // Check the users password using the random SALTED password if ($userData->validate_password($password, $userInfo['UserPassword']) === false) { setMessage(__('Username or Password incorrect')); return false; } } } // there is a result so we store the userID in the session variable $_SESSION['userid'] = Kit::ValidateParam($userInfo['UserID'], _INT); $_SESSION['username'] = Kit::ValidateParam($userInfo['UserName'], _USERNAME); $_SESSION['usertype'] = Kit::ValidateParam($userInfo['UserTypeID'], _INT); // Set the User Object $this->usertypeid = $_SESSION['usertype']; $this->userid = $_SESSION['userid']; // update the db // write out to the db that the logged in user has accessed the page $SQL = sprintf("UPDATE user SET lastaccessed = '" . date("Y-m-d H:i:s") . "', loggedin = 1 WHERE userid = %d", $_SESSION['userid']); $db->query($SQL) or trigger_error(__('Can not write last accessed info.'), E_USER_ERROR); // Switch Session ID's global $session; $session->setIsExpired(0); $session->RegenerateSessionID(session_id()); return true; } i am trying to squeeze in an alternative authentication for users on ldap as such if local authentication fails // alternativelly validate against Tivoli Directory server $ldap_host = "www.zflexldap.com:389"; $password = "password"; // Tivoli Directory DN $ldap_dn = "ou=users,ou=guests,dc=zflexsoftware,dc=com"; // connect to active directory $ldap = ldap_connect($ldap_host) or die("Couldn't connect to LDAP Server"); //username specified on post form is from TDS server // $dn = "uid=".$username.","; $dn = "uid=guest1,ou=users,ou=guests,dc=zflexsoftware,dc=com"; ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // verify user and password if($bind = @ldap_bind($ldap, $dn, $password)) all attempts thou has been breaking the application. thanks
  5. My sign in code called activation is the script called activation.php. my login page is login.php and my profile page is the landing page once a successful login in attempt is made. the activation.php is the issue as i us the form in sign.php to login but the activation.php doesn't redirect me to the sign in page once a fail attempt is made or it doesn't redirect me to my profile page once a successful login in attempt is made. The following link has the code:https://gist.github.com/confusedstudent21/410f04991691f485e6c28d1e4050e13a where is it going wrong?
  6. I am using this https://github.com/ircmaxell/password_compat I have no problem using it on a local server. But as soon as I test it on a live server, it gives me an error like this. Parse error: syntax error, unexpected '{' in /home/public_html/sub/snippets/password.php on line 19 The error is on the same line as the beginning of the code in that library. Why is this happening?
  7. I have been working on a login form, I have completed the registration side but the login form is proving to be fighting back. I have just jumped into the world of PDO and only recently PHP in a serious way. I have been trying to use the password_verify(); function but I have spent so long on it now trying to get it working I have made it more difficult than it should be and probably is. I would be grateful if someone could take a look at my code and just tell me what I am doing wrong. I have tested it with the username and password hard coded in and it returns an array however if I comment out the hard coded username and password I get an empty array. I dare say that someone will see the issue straight away but I cannot get my head round it. <?php session_start(); error_reporting(0); require '../php_inc/connection/connect.php'; require_once '../php_inc/functions.php'; $error = ''; // all error messages will use this variable $msg = 'Please fill in both fields and answer the captcha, they are all required to log in.'; if(isset($_POST['submitted'])){ $dbuname = 'dashby'; // As if check with DB - If I comment these 2 out and try to get data from DB I get empty array $hashed = '$2y$12$7hcyfm7UjboYGaNLF7vK1.qroo3YkvhKAR8EfxG1byEMkNB0oSQgi'; // As if check with DB - same password require 'Captcha.php'; $username = escape_in($_POST['username']); // Username $captcha = escape_in($_POST['captchaResult']); //Captcha $unhashed = escape_in($_POST['password']); //Password b4 hashing takes place //$submittedPassword = password_hash($unhashed, PASSWORD_DEFAULT, ['cost' => 12]); // connect to the database so the checks can be done. if($pdo){ $stmt = $pdo->prepare("select * from users where username = :username && password = :password"); $stmt->bindParam(":username", $username); $stmt->bindParam(":password", $unhashed); // If $hashed is the variable I get an array returned, as $unhashed I get an empty array echo '<pre>'; if($stmt->execute()){ $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($rows); } } echo '</pre>'; if($total == $getCaptchaResults){ //Capcha OK if(password_verify($unhashed, $hashed)){ //$msg = ''; //$error .= 'Password match'; if($username == $dbuname){ //$msg = ''; //$error .= 'Captcha, username and password ok'; // working to this point $_SESSION['username']; //header('Location: welcomelogged.php'); } else { $msg = ''; $error .= 'Denied wrong username and/or password'; } } else { $msg = ''; $error .= 'Denied wrong password and/or username'; } } else { if(($total != $getCaptchaResults)){ $msg = ''; $error .= 'Captcha Wrong'; } } }// post submitted brace ?> The if statements all work bar the password_verify when I comment out the hard coded variables out, directly under if(isset($_POST['submitted'])) {} I would be grateful if someone could steer me in the right direction. Thanks in advance.
  8. So i made a login page, but whenever i enter right, wrong, or no password at all, it always displays wrong password. I've been trying to fix it for hours, but I just can't seem to find the error. It's like it's skipping if the password is right statement and goes straight through the else statment. <?php $connection = mysql_connect("com-db-02.student-cit.local","***","***") or die (mysql_error()); if ($connection) echo "Connection successful"; else echo "Connection failed"; $db = mysql_select_db("TEAM20") or die (mysql_error()); ?> <?php $_SESSION['customeremail'] = $_POST['user']; $_SESSION['password'] = $_POST['password']; function signIn() { session_start(); if(!empty($_POST['user'])) { $query = mysql_query("SELECT * FROM customer where customeremail = '$_POST[user]' AND password = '$_POST[password]'"); $row = mysql_fetch_array($query); if(!empty($row['customeremail']) AND !empty($row['password'])) { $_SESSION['customeremail'] = $row['customeremail']; getCustDetails(); echo "Successfully login to user profile page.."; echo "<a href=userlogin.php>Profile</a>"; } else { echo "Sorry... YOU ENTERED WRONG ID AND PASSWORD"; echo "<a href=login.html>Try Again</a>"; } } } function getCustDetails() { $queryId = mysql_query("SELECT customerID, firstname FROM Customer WHERE customeremail = '$_POST[user]'"); while($rowId = mysql_fetch_array($queryId)) { $_SESSION['customerID'] = $rowId['customerID']; $_SESSION['firstname'] = $rowId['firstname']; } echo "Code: ".$_SESSION['customerID']; echo "Name: ".$_SESSION['firstname']; } if(isset($_POST['submit'])) { signIn(); } ?>
  9. Hi everyone I am building a CRM system/invoicing system in my spare time and on this system I have 2 login pages (there is a reason but its long). one for the CRM system and one for the invoicing section. They bother work perfectly well but I have a really annoying issue, If I were to store the login information to chrome passwords for example to the CRM system It would auto suggest to the other login and vice versa. This wouldn't be a problem but the CRM login is username based, the invoicing section is login by email for additional security. they're both called login.php the two files are /htdocs/login.php and /htdocs/invoicing/login.php I added a remember me cookie to the CRM system in hope that this would get around the issue but unfortunately the chrome saved information over rides this, I also tried autocomplete="off" as I am using bootstrap as a framework. How can I get around this?
  10. Hi, The 'admin' section of my website stopped working a couple of months ago and I'm just trying to fix it - I was getting an error about Session_Register being deprecated and I'm now trying to knife and fork my way around it with results from various google searches. I'm an advanced SQL user but only occasionally dabble with PHP so any help would be appreciated. So, basic set up, login page checks credentials against the DB, a session cookie is set and you're let into the admin area - my script is looping me back to the login page as my !isset is true.....because I can't figure out how to set it with the new functions! This is the login include..... <?php $host="database.lcn.com"; // Host name $username="blahblah"; // Mysql username $password="blahblah"; // Mysql password $db_name="blahblah_db"; // Database name $tbl_name="users"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['username']; $mypassword= md5($_POST['pass']); // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM users WHERE is_obv = '1' and username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" $_SESSION['username'] = $myusername; $_SESSION['pass'] = $mypassword; header("location:../admin"); } else { header("location:http://www.web.co.uk/ooops"); } ?> and this is the 'login_success' include that I include on each protected page.... <? session_start(); if(!isset($_SESSION['username'])){ header("location:http://www.web.co.uk/login"); } ?> Darren
  11. Hi Everyone So I've been recently working on a script which will store login IP's and ban them on failed attempts Although I have a little problem, for some reason it doesnt redirect to the banned page when they should be, unless there is a successful login or if they come off of the login page so they can keep bruteforcing as much as they like all the time they stay on that page. Have i got something wrong? please bear in mind I haven't put in place when login successful remove the warnings count. here is the login.php <!DOCTYPE html> <?php require ('../Functions/functions.php'); require('../database/pdo_connection.php'); //first lets get the IP that logged in $login_ip = $_SERVER['REMOTE_ADDR']; securityBanCheck($login_ip); if (isset($_POST['Login'])) { //Set session timeout to 2 weeks session_set_cookie_params(1*7*24*60*60); session_start(); $error=''; // Currently A Blank Error Message $username=$_POST['userName']; //Grab the hash $selectPasswordHash = "SELECT username,secret FROM MC_users WHERE email=email=:username OR username=:username"; $hashresult= $pdo->prepare($selectPasswordHash); $hashresult->bindParam(':username', $username); $hashresult->execute(); $row = $hashresult->fetch(PDO::FETCH_ASSOC); $hash = $row['secret']; //got the hash //lets verify it if (password_verify($_POST['password'],$hash) === true){ //login correct $login_user = $row['username']; //Set the Session $_SESSION['login_user']=$login_user; // Redirect to dashboard.php header ("Location: ../dashboard.php"); } else { $error = 'Username or Password in invalid'; $error2 = 'Try Logging in with your email instead'; //Bruteforce Detection //lets check if there is already warnings $checkWarnings = "SELECT Warning_count FROM MC_login_security WHERE Warning_count > 0 AND Login_IP=:loginIP ORDER BY Timestamp DESC"; $warningsResult = $pdo->prepare($checkWarnings); $warningsResult->bindParam(':loginIP',$login_ip); $warningsResult->execute(); $warningAmount = 1; $banTime = 0; if ($warningsResult->rowCount() > 0){ $warningRow = $warningsResult->fetch(PDO::FETCH_ASSOC); $warningRowCount = $warningRow['Warning_count']; $warningAmount = $warningRowCount + 1; securityBanCheck($login_ip); } //Lets log this in the DB $insertWarning = "INSERT INTO MC_login_security (Login_user_name,Login_IP,Warning_count,timestamp) VALUES (:loginUser,:Login_ip,:warningAmount,:dateToday)"; $insertResult = $pdo->prepare($insertWarning); $insertResult->execute(array(':loginUser'=>$username, ':Login_ip'=>$login_ip, ':warningAmount'=>$warningAmount, ':dateToday'=>date('Y-m-d H:i:s'))); } } //Lastly if the user is logged in, point them back to the Dashboard if(isset($_SESSION['login_user'])){ header("location: ../dashboard.php");} ?> the security check function which is called at the start of the login page AND if the password is entered incorrectly function securityBanCheck($login_ip){ //call the url function for redirects url(); $todaysDate = date('Y-m-d H:i:s'); require (PHP_PATH .'/database/pdo_connection.php'); $checkBan = "SELECT Warning_count,Timestamp,Ban_time FROM MC_login_security WHERE Warning_count > 4 AND Login_IP=:loginIP ORDER BY Timestamp DESC"; $checkResult = $pdo->prepare($checkBan); $checkResult->bindParam(':loginIP',$login_ip); $checkResult->execute(); if ($checkResult->rowCount() > 0){ $banRow = $checkResult->fetch(PDO::FETCH_ASSOC); $warningCount = $banRow['Warning_count']; $timeStamp = $banRow['Timestamp']; $bantime = $banRow['Ban_time']; echo "did we get here?"; //if theyre banned direct them to the banned page and stop this script from going any further if ($bantime > $todaysDate){ header('Location: '. SERVER_PATH .'banned.php'); die(); } //if theyre currently not banned check their warnings and if needed add a ban. if ($warningCount == 4){ $bantime = date('Y-m-d H:i:s', strtotime($timeStamp . '+1 hour')); echo $bantime; }elseif ($warningCount == 9){ $bantime = date('Y-m-d H:i:s', strtotime($timeStamp . '+1 day')); }elseif ($warningCount == 14){ $bantime = date('Y-m-d H:i:s', strtotime($timeStamp . '+1 month')); } //ultimately if we got to this stage we would be adding a ban $insertBanTime = "UPDATE MC_login_security SET Ban_time = :banTime WHERE Login_IP = :loginIP ORDER BY Timestamp DESC"; $banResult = $pdo->prepare($insertBanTime); $banResult->execute(array(':banTime'=>$bantime, ':loginIP'=>$login_ip));; } } Any help given is greatly appreciated and i thank everyone in advance for all the support I get form this amazing forum. thanks Mooseh
  12. I am testing to see if PHP variables can pass from previous page to present page to login, I notice it doesn't work in MySQL query from previous to present page. It is like using ID to pass the variable in link like this: "?id=" in link, but I am using submit button. I typed name="user" in previous page, that should pass variable to present, then set up the select in database, but it doesn't do that, what i did do wrong? if ($_POST['submitted']) { $username = $_POST['user']; $password = $_POST['pass']; if ($username && $password) { $log = "SELECT username, password, type FROM username WHERE username = '".$username."' AND WHERE password = '".$password."'"; $result = mysqli_query($Garydb, $log) or die("could not work"); echo "<p>".$result['username']."</p>"; } } Also, I wonder about two query in one sentence, like using 'AND' on sentence, will it works? Please advise me. Thank you in advance time. Gary P.S. how do you type in chart like notepad++ in here? I need to know how to do that, so I show you in number line that you can point much easier to read.
  13. Hi everyone, Anyone recommended me to learn how to set up the login system, it is most advanced system, even longer work. Anyone know link to website that can help me learning about login system? Video will be very appreciate... Thanks, Gary
  14. Hi, Just wondering if someone could point me in the right direction, I have a simple PHP MySQL login script which passes/stores data via sessions. It works fine, there is no problem with it. All I would like to do is pass some additional data from the users MySQL table. Currently it users just username and password, but I would like it to pass firstname and surname data as well. So when a user logs in with their username and password, on the next page it might say Welcome, Michael Smith. The script below is originally setup for the username to be a persons name, as it's used in the login welcome message in the login.php But I might change the username to be an email address, if I can pull in the additional data. config.php <?php /***************************** File: includes/config.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ // start the session before any output. session_start(); // Set the folder for our includes $sFolder = '/predictor/login'; /*************** Database Connection You will need to change the user (user) and password (password) to what your database information uses. Same with the database name if you used something else. ****************/ mysql_connect('localhost', 'root', '') or trigger_error("Unable to connect to the database: " . mysql_error()); mysql_select_db('football') or trigger_error("Unable to switch to the database: " . mysql_error()); /*************** password salts are used to ensure a secure password hash and make your passwords much harder to be broken into Change these to be whatever you want, just try and limit them to 10-20 characters each to avoid collisions. ****************/ define('SALT1', '24859f@#$#@$'); define('SALT2', '^&@#_-=+Afda$#%'); // require the function file require_once($_SERVER['DOCUMENT_ROOT'] . $sFolder . '/includes/functions.php'); // default the error variable to empty. $_SESSION['error'] = ""; // declare $sOutput so we do not have to do this on each page. $sOutput=""; ?> login.php <?php /***************************** File: login.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ require($_SERVER['DOCUMENT_ROOT'] . '/predictor/login/includes/config.php'); // If the user is logging in or out // then lets execute the proper functions if (isset($_GET['action'])) { switch (strtolower($_GET['action'])) { case 'login': if (isset($_POST['username']) && isset($_POST['password'])) { // We have both variables. Pass them to our validation function if (!validateUser($_POST['username'], $_POST['password'])) { // Well there was an error. Set the message and unset // the action so the normal form appears. $_SESSION['error'] = "Bad username or password supplied."; unset($_GET['action']); } }else { $_SESSION['error'] = "Username and Password are required to login."; unset($_GET['action']); } break; case 'logout': // If they are logged in log them out. // If they are not logged in, well nothing needs to be done. if (loggedIn()) { logoutUser(); $sOutput .= '<h1>Logged out!</h1><br />You have been logged out successfully. <br /><h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; }else { // unset the action to display the login form. unset($_GET['action']); } break; } } $sOutput .= '<div id="index-body">'; // See if the user is logged in. If they are greet them // and provide them with a means to logout. if (loggedIn()) { $sOutput .= '<h1>Logged In!</h1><br /><br /> Hello, ' . $_SESSION["username"] . ' how are you today?<br /><br /> <h4>Would you like to <a href="login.php?action=logout">logout</a>?</h4> <h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; }elseif (!isset($_GET['action'])) { // incase there was an error // see if we have a previous username $sUsername = ""; if (isset($_POST['username'])) { $sUsername = $_POST['username']; } $sError = ""; if (isset($_SESSION['error'])) { $sError = '<span id="error">' . $_SESSION['error'] . '</span><br />'; } $sOutput .= '<h2>Login to our site</h2><br /> <div id="login-form"> ' . $sError . ' <form name="login" method="post" action="login.php?action=login"> Username: <input type="text" name="username" value="' . $sUsername . '" /><br /> Password: <input type="password" name="password" value="" /><br /><br /> <input type="submit" name="submit" value="Login!" /> </form> </div> <h4>Would you like to <a href="login.php">login</a>?</h4> <h4>Create a new <a href="register.php">account</a>?</h4>'; } $sOutput .= '</div>'; // lets display our output string. echo $sOutput; ?> functions.php <?php /***************************** File: includes/functions.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ /*********** bool createAccount (string $pUsername, string $pPassword) Attempt to create an account for the passed in username and password. ************/ function createAccount($pUsername, $pPassword, $pFirstname, $pSurname) { // First check we have data passed in. if (!empty($pUsername) && !empty($pPassword) && !empty($pFirstname) && !empty($pSurname)) { $uLen = strlen($pUsername); $pLen = strlen($pPassword); $fLen = strlen($pFirstname); $sLen = strlen($pSurname); // escape the $pUsername to avoid SQL Injections $eUsername = mysql_real_escape_string($pUsername); $sql = "SELECT username FROM users WHERE username = '" . $eUsername . "' LIMIT 1"; // Note the use of trigger_error instead of or die. $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // Error checks (Should be explained with the error) if ($uLen <= 4 || $uLen >= 11) { $_SESSION['error'] = "Username must be between 4 and 11 characters."; }elseif ($pLen < 6) { $_SESSION['error'] = "Password must be longer then 6 characters."; }elseif (mysql_num_rows($query) == 1) { $_SESSION['error'] = "Username already exists."; }else { // All errors passed lets // Create our insert SQL by hashing the password and using the escaped Username. $sql = "INSERT INTO users (`username`, `password`, `firstname`, `surname`) VALUES ('" . $eUsername . "', '" . hashPassword($pPassword, SALT1, SALT2) . "', '" . $pFirstname . "', '" . $pSurname . "');"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); $sql2 = "INSERT INTO predictions (userID, predictionID, week) SELECT LAST_INSERT_ID(), id, week FROM fixtures"; $query = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error()); if ($query) { return true; } } } return false; } /*********** string hashPassword (string $pPassword, string $pSalt1, string $pSalt2) This will create a SHA1 hash of the password using 2 salts that the user specifies. ************/ function hashPassword($pPassword, $pSalt1="2345#$%@3e", $pSalt2="taesa%#@2%^#") { return sha1(md5($pSalt2 . $pPassword . $pSalt1)); } /*********** bool loggedIn verifies that session data is in tack and the user is valid for this session. ************/ function loggedIn() { // check both loggedin and username to verify user. if (isset($_SESSION['loggedin']) && isset($_SESSION['userID']) && isset($_SESSION['username'])) { return true; } return false; } /*********** bool logoutUser Log out a user by unsetting the session variable. ************/ function logoutUser() { // using unset will remove the variable // and thus logging off the user. unset($_SESSION['username']); unset($_SESSION['userID']); unset($_SESSION['loggedin']); return true; } /*********** bool validateUser Attempt to verify that a username / password combination are valid. If they are it will set cookies and session data then return true. If they are not valid it simply returns false. ************/ function validateUser($pUsername, $pPassword) { // See if the username and password are valid. $sql = "SELECT * FROM users WHERE username = '" . mysql_real_escape_string($pUsername) . "' AND password = '" . hashPassword($pPassword, SALT1, SALT2) . "' LIMIT 1"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // If one row was returned, the user was logged in! if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $_SESSION['username'] = $row['username']; $_SESSION['userID'] = $row['userID']; $_SESSION['password'] = $row['password']; $_SESSION['loggedin'] = true; return true; } return false; } ?> USERS TABLE ID username password firstname surname 1 rich 12345 Richard Branson 2 alan 67898 Lord Sugar
  15. Im having a problem with login system. its telling me my username and password are wrong when i know they are not. here is my login.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="UTF-8"> <title>Server 2 Server | Log in</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'> <!-- Bootstrap 3.3.4 --> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <!-- Font Awesome Icons --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <!-- Theme style --> <link href="dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" /> <!-- iCheck --> <link href="plugins/iCheck/square/blue.css" rel="stylesheet" type="text/css" /> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="login-page"> <div class="login-box"> <div class="login-logo"> <a href="../../index2.html"><b>Server</b>2SERVER</a> </div><!-- /.login-logo --> <div class="login-box-body"> <p class="login-box-msg">Sign in to view the control panel</p> <?php if(!empty($_GET['msg'])) { $msg = $_GET['msg']; //GET the message if($msg!=''): echo '<p>'.$msg.'</p>'; endif; } ?> <form action="check_login.php" method="post"> <div class="form-group has-feedback"> <input type="text" class="form-control" placeholder="Email" name="username" id="username"/> <span class="glyphicon glyphicon-envelope form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="password" class="form-control" placeholder="Password" name="password" id="password"/> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-8"> </div><!-- /.col --> <div class="col-xs-4"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div><!-- /.col --> </div> </form> <a href="#">I forgot my password</a><br> </div><!-- /.login-box-body --> </div><!-- /.login-box --> <!-- jQuery 2.1.4 --> <script src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script> <!-- Bootstrap 3.3.2 JS --> <script src="../../bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <!-- iCheck --> <script src="../../plugins/iCheck/icheck.min.js" type="text/javascript"></script> <script> $(function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); }); </script> </body> </html> check_login.php <?php define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file $username = $_POST['username']; //Set UserName $password = $_POST['password']; //Set Password $msg =''; if(isset($username, $password)) { ob_start(); include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($username); $mypassword = stripslashes($password); $myusername = mysqli_real_escape_string($dbC, $myusername); $mypassword = mysqli_real_escape_string($dbC, $mypassword); $sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA('$mypassword')"; $result=mysqli_query($dbC, $sql); // Mysql_num_row is counting table row $count=mysqli_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "dashboard.php" session_register("admin"); session_register("password"); $_SESSION['name']= $myusername; header("location:dashboard.php"); } else { $msg = "Wrong Username or Password. Please retry"; header("location:login.php?msg=$msg"); } ob_end_flush(); } else { header("location:login.php?msg=Please enter a username and password"); } ?> it just keeys telling my my password and user and incorrect please help
  16. Unfortunately my ideas out pace my skills. I have a database that I would like certain people to access their own info, but nobody else's. It's not super sensitive info and won't mean much to anyone other than the end user but we don't like the idea of others accessing it so we'd like to put some protection on it. What I was hoping for is a dropdown list (there's about 30 or so clients that would be in a mysql table) where they can pick out their name, then text box for the password. When they hit submit button it would lead them to their own page with a table and their own info from a mysql table. I can get each one of these details to work separately, but I'm having trouble putting them all together (the password is where things get muddled). Can anyone point me to a place where they've already figured this out? Thanks!
  17. Hi, I've been going out of my mid for almost a week now trying to figure out how to make this work... I want multiple users to have their own individual usernames and passwords and be able to log in and view certain pages that non-registered guests can't see. I've set up my databases and usernames and passwords. I've actually gotten my login code to work now and then, but in trying to get sessions to work and not allow just anyone to manually type in the addresses of certain pages I've managed to mess that up and it doesn't work now either. I've been to MANY different sites and used examples but just can't get the login to work properly nor figure out how to get the sessions to check for a logged in user. My code so far...I've taken out my real password login,php <?php $connection = mysql_connect('localhost', 'root', 'mypassword'); if (!$connection){ die("Database Connection Failed" . mysql_error()); } $select_db = mysql_select_db('login'); if (!$select_db){ die("Database Selection Failed" . mysql_error()); } if (isset($_POST['username']) and isset($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $query = mysql_query("select * from members where password='$password' AND username='$username'", $connection); $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_register("username"); session_register("password"); $_SESSION["authorized"] = true; header("location:membersarea.php"); } else header ("Location: login.html"); } ?> And this is what I put at the top of each secured page... membersarea.php <?php session_start(); if ($_SESSION["authorized"] = true) { } else { header("Location: login.html"); } ?> Thanks in advance!
  18. 1. HTML FORM #for user to enter the data <html> <title>reg</title> <style type="text/css"> body { background-color: rgb(200,200,200); color: white; padding: 20px; font-family: Arial, Verdana, sans-serif;} h4 { background-color: DarkCyan; padding: inherit;} h3 { background-color: #ee3e80; padding: inherit;} p { background-color: white; color: rgb(100,100,90); padding: inherit;} </style> <form method="POST" action="login_back.php" enctype="multipart/form-data"></br> &nbsp<font color="DarkCyan"> Choose a user name:</font> <input type="text" name="username"> </br></br> &nbsp<font color="DarkCyan"> First name:</font> <input type="text" name="firstname"/> </br></br> &nbsp<font color="DarkCyan"> Last name:</font><input type="text" name="lastname"/> </br></br> &nbsp<font color="DarkCyan"> File: <input type="file" name="image"></font> </br></br> <input type="submit" value="Save and Proceed"> </form> </html> ---------- 2 STORING IN DATABASE #backend processing to store and retrieve data from db <?php error_reporting(0); #echo "<body style='background-color:rgb(200,200,200)'>"; session_start(); #if( isset($_POST['username']) && isset($_FILES['image']) ) #{ $_SESSION['username']=$_POST['username']; $_SESSION['firstname']=$_POST['firstname']; $lastname=$_POST['lastname']; $file=$_FILES['image']['tmp_name']; $image_size=getimagesize($_FILES['image']['tmp_name']); if(!isset($file)) echo"please select an image"; else { #$image=$_FILES['image']['tmp_image']; //grabing the file content $image_name=$_FILES['image']['name']; //grabing image name $image_size=getimagesize($_FILES['image']['tmp_name']); //getting image size } echo "</br>"; #connection to db mysql_connect("localhost","root","")or die(mysql_error()); mysql_select_db("wordgraphic")or die(mysql_error()); #checking the available username $query = mysql_query("SELECT * FROM userdata WHERE username = '" . $_SESSION['username'] . "'" ); $ans=mysql_num_rows($query); if ($ans > 0) { echo "Username already in use please try another."; } else if($image_size==FALSE) { echo"That's not an image."; } else { #Insert data into mysql #1.Inserting user name & image into db $sql="INSERT INTO userdata(username, firstname, lastname, image)VALUES('" . $_SESSION['username'] . "', '" . $_SESSION['firstname'] . "', '$lastname','$image')"; $result1=mysql_query($sql); if($result1) { echo "</br>"; echo "Registration successful"; echo "</br>"; //displaying image $lastid=mysql_insert_id();//get the id of the last record echo "uploaded image is :"; echo "<img src='get.php?id=".$lastid."'>"; > this command has some mistake }#if insertion into db successful else { echo "Problem in database operation"; } }# else block of unique username n img }#end of isset ?> ---------- 3. GET.PHP #additional file that retrieve image from database <?php #connection to db mysql_connect("localhost","root","")or die(mysql_error()); mysql_select_db("wordgraphic")or die(mysql_error()); if(isset($_REQUEST['id']) ) > this block of code is not running { $mid=(int)($_REQUEST['id']); $image=mysql_query("SELECT * FROM userdata WHERE id=$mid") or die("Invalid query: " . mysql_error()); $image=mysql_fetch_assoc($image); $image=$image['image']; header("Content-type: image/jpeg"); echo $image; } else echo"error"; ?>
  19. Hi, wish somebody can help me T_T I'm little bit confused how to make user log-in based on country or territory, what I'm talking about is like this: The User table is: id_user | username | password | level | id_country The Country table is: id | country_name And when user login, there's a data entry form and there is a drop-down/combo-box in a form, that filled with user countries, like this: Country: [____] --> This part is automatically filled/disabled field if a user log-in with their username based on level and countries. Province: [____] --> This is a chained combo-box from countries City: [____] --> Also this chained to Province What I mean is, when user's log-in with their country id, so the "Country Combo-Box" will be automatically filled and disabled. So user can't choose another country, only their country based on username and territories. Thank you for all your help. Best regards, Kris I have this scripts: login_form.php <div><center> <form name="logForm" method="post" action="login_validation.php"> <table class="table-list" width="500" border="0" cellpadding="2" cellspacing="1" bgcolor="#999999"> <tr> <td width="106" rowspan="5" align="center" bgcolor="#CCCCCC"><img src="images/padlock.png" width="116" height="75" /></td> <th colspan="2" bgcolor="#CCCCCC"><b>LOGIN FORM </b></td> </tr> <tr> <td width="117" bgcolor="#FFFFFF"><b>Username</b></td> <td width="263" bgcolor="#FFFFFF"><b>: <input name="txtUser" type="text" size="30" maxlength="20" /> </b></td> </tr> <tr> <td bgcolor="#FFFFFF"><b>Password</b></td> <td bgcolor="#FFFFFF"><b>: <input name="txtPassword" type="password" size="30" maxlength="20" /> </b></td> </tr> <tr> <td bgcolor="#FFFFFF"><b>Access Level</b></td> <td bgcolor="#FFFFFF"><b>: <select name="comboLevel"> <option value="BLANK">- Choose -</option> <?php $level = array("operator", "admin"); foreach ($level as $p) { if ($_POST['comboLevel']==$p) { $check="selected"; } else { $check = ""; } echo "<option value='$p' $check>$p</option>"; } ?> </select> </b></td> </tr> <tr> <td bgcolor="#FFFFFF"> </td> <td bgcolor="#FFFFFF"><input type="submit" name="btnLogin" value=" Login " /></td> </tr> </table> </form> </center></div> and this validation script: login_validation.php <?php if(isset($_POST['btnLogin'])){ $msgError = array(); if ( trim($_POST['txtUser'])=="") { $pesanError[] = "Username </b> cannot empty !"; } if (trim($_POST['txtPassword'])=="") { $msgError[] = "Password </b> cannot empty !"; } if (trim($_POST['comboLevel'])=="BLANK") { $msgError[] = "Level</b> not picked !"; } $txtUser = $_POST['txtUser']; $txtUser = str_replace("'","´",$txtUser); $txtPassword=$_POST['txtPassword']; $txtPassword= str_replace("'","´",$txtPassword); $comboLevel =$_POST['comboLevel']; if (count($msgError)>=1 ){ echo "<div class='mssgBox'>"; echo "<img src='images/exclamation.png'> <br><hr>"; $noMsg=0; foreach ($msgError as $index=>$show_msg) { $noMsg++; echo " $noMsg. $show_msg<br>"; } echo "</div> <br>"; include "login.php"; } else { $loginSql = "SELECT * FROM user WHERE username='".$txtUser."' AND password='".md5($txtPassword)."' AND level='$comboLevel'"; $loginQry = mysql_query($loginSql, $conndb) or die ("Query Error : ".mysql_error()); if (mysql_num_rows($loginQry) >=1) { $loginData = mysql_fetch_array($loginQry); $_SESSION['SES_LOGIN'] = $loginData['id_user']; $_SESSION['SES_USER'] = $loginData['username']; if($comboLevel=="admin") { $_SESSION['SES_ADMIN'] = "admin"; } if($comboLevel=="operator") { $_SESSION['SES_OPERATOR'] = "operator"; } // Refresh echo "<meta http-equiv='refresh' content='0; url=?page=Main-Page'>"; } else { echo "You Not Login As ".$_POST['comboLevel']; } } } ?> Thank you for all help.... T_T thank you..
  20. hey guys, HOpe you can help me. I need a code about "Lock out after serveral attemps", and "Change password after first login"
  21. I am trying to create a remote login to one website using mine. The users will need to enter their username and password on my site, and if they are registered to my website, their login credentials will be sent to another website and a page will be retrieved. I am stuck at sending the users' data to the original site. The original site's viewsource is this.. <form method=post> <input type="hidden" name="action" value="logon"> <table border=0> <tr> <td>Username:</td> <td><input name="username" type="text" size=30></td> </tr> <tr> <td>Password:</td> <td><input name="password" type="password" size=30></td> </tr> <td></td> <td align="left"><input type=submit value="Sign In"></td> </tr> <tr> <td align="center" colspan=2><font size=-1>Don't have an Account ?</font> <a href="?action=newuser"><font size=-1 color="#0000EE">Sign UP Now !</font></a></td> </tr> </table> I have tried this code, but not works. <?php $username="username"; $password="password"; $url="http://www.example.com/index.php"; $postdata = "username=".$username."&password=".$password; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20070725 Firefox/"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_REFERER, $url); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); header('Location: track.html'); //echo $result; curl_close($ch); ?> Any help would be appreciated, Thanks in advance.
  22. Hi, I am trying to create a login system in PHP, but I am not the greatest at PHP so I am using a source code which I found online as I found it to be more secure as it uses things like salted passwords. Anyway I am trying to add more fields to the register system so it adds them to the mysql, the source has a way to do this with arrays, but it is quite complicated so I am just using variables from the original file. There are 2 files: register.php and class.loginsys.php which contains all the functions. At first the query syntax was incorrect so I decided to use the variables created in register.php in the class.loginsys, but now it's giving me an out of memory error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 28672 bytes) in C:\xampp\htdocs\ls\class.loginsys.php on line 34 Which I am unsure of how to fix. I have tried using different variable names, checking the line, checking the whole register.php file for anything rogue. Here is the code: Top part of register.php <?php include "config.php"; ?> Config.php: <?php require "class.loginsys.php"; $LS=new LoginSystem(); ?> Then actual register part from register.php: <?php if( isset($_POST['submit']) ){ $firstname2 = $_POST['firstname']; $lastname2 = $_POST['lastname']; $user2 = $_POST['username']; $sex2 = $_POST['sex']; $country2 = $_POST['strCountryChoice']; $email2 = $_POST['email']; $pass2 = $_POST['pass']; $pass3 = $_POST['pass2']; $birthdate2 = $_POST['birthdate']; $created2 = date("Y-m-d H:i:s"); //need to add a lot more validation functions.. AKA Check if email exists and username. Password > 5 chars if( $user2=="" || $email2=="" || $pass2=='' || $pass3=='' || $firstname2=='' || $lastname2=='' || $sex2=='' || $country2=='' || $birthdate2=='' ){ echo "Fields Left Blank","Some Fields were left blank. Please fill up all fields."; exit; } if( !$LS->validEmail($email2) ){ echo "E-Mail Is Not Valid", "The E-Mail you gave is not valid"; exit; } if( !ctype_alnum($user2) ){ echo "Invalid Username", "The Username is not valid. Only ALPHANUMERIC characters are allowed and shouldn't exceed 10 characters."; exit; } if($pass2 != $pass3){ echo "Passwords Don't Match","The Passwords you entered didn't match"; exit; } $createAccount2 = $LS->register($user2, $pass2, array( "email" => $email2, "name" => $firstname2, "lastname" => $lastname2, "gender" => $sex2, "country" => $country2, "DOB" => $birthdate2, "created" => date("Y-m-d H:i:s") // Just for testing ) ); //$createAccount = $LS->register($firstname,$lastname,$user,$sex,$country,$email,$pass,$birthdate,$created); if($createAccount2 === "exists"){ echo "User Exists."; }elseif($createAccount2 === true){ echo "Success. Created account."; } } ?> And the function from the class: /* A function to register a user with passing the username, password and optionally any other additional fields. */ public function register( $id, $password, $other = array() ){ if( $this->userExists($id) && (isset($other['email']) && $this->userExists($other['email'])) ){ return "exists"; }else{ $randomSalt = $this->rand_string(20); $saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$randomSalt}"); if( count($other) == 0 ){ /* If there is no other fields mentioned, make the default query */ //old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)"); //new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)"); $sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)"); }else{ /* if there are other fields to add value to, make the query and bind values according to it */ //old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)"); //new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)"); $keys = array_keys($other); $columns = implode(",", $keys); $colVals = implode(",:", $keys); //l= $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)"); //INSERT INTO MyGuests (firstname, lastname, email)cLUES ('John', 'Doe', 'john@example.com') $sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (username,email,password,password_salt,name,lastname,created,gender,country,DOB) VALUES ('$username2','$email2','$pass2','$saltedPass','$firstname2','$lastname2','$created2','$gender2','$country2','$birthdate2')"); print($sql); foreach($other as $key => $value){ $value = htmlspecialchars($value); $sql->bindValue(":$key", $value); } } /* Bind the default values */ $sql->bindValue(":username", $id); $sql->bindValue(":password", $saltedPass); $sql->bindValue(":passwordSalt", $randomSalt); $sql->execute(); return true; } } Thanks for your help. I am doing this because for a hobby I am trying to create a browser based game in which I use this login system to login the user to a main page then code all of the other pages myself. I have posted on stackoverflow and someone on their suggested that I should use a framework. If this is the case, can someone point me in the right direction? Thanks again, if you need any info ask.
  23. Sorry for many posts, trying to make my website When I press the register button on my website it will just act as if the page is refreshing and not send any information to mysql I believe I have connected everything up correctly, can anyone tell my what I have done wrong please? If you want to check out the website to see what is going on check out www.jokestary.comli.com <?php //This function will display the registration form function register_form(){ $date = date('D, M, Y'); echo "<form action='?act=register' method='post'>" ."Username: <input type='text' name='username' size='30'><br>" ."Password: <input type='password' name='password' size='30'><br>" ."Confirm your password: <input type='password' name='password_conf' size='30'><br>" ."Email: <input type='text' name='email' size='30'><br>" ."<input type='hidden' name='date' value='$date'>" ."<input type='submit' value='Register'>" ."</form>"; } //This function will register users data function register(){ //Connecting to database include('connect.php'); if(!$connect){ die(mysql_error()); } //Selecting database $select_db = mysql_select_db("database", $connect); if(!$select_db){ die(mysql_error()); } //Collecting info $username = $_REQUEST['username']; $password = $_REQUEST['password']; $pass_conf = $_REQUEST['password_conf']; $email = $_REQUEST['email']; $date = $_REQUEST['date']; //Here we will check do we have all inputs filled if(empty($username)){ die("Please enter your username!<br>"); } if(empty($password)){ die("Please enter your password!<br>"); } if(empty($pass_conf)){ die("Please confirm your password!<br>"); } if(empty($email)){ die("Please enter your email!"); } //Let's check if this username is already in use $user_check = mysql_query("SELECT username FROM users WHERE username='$username'"); $do_user_check = mysql_num_rows($user_check); //Now if email is already in use $email_check = mysql_query("SELECT email FROM users WHERE email='$email'"); $do_email_check = mysql_num_rows($email_check); //Now display errors if($do_user_check > 0){ die("Username is already in use!<br>"); } if($do_email_check > 0){ die("Email is already in use!"); } //Now let's check does passwords match if($password != $pass_conf){ die("Passwords don't match!"); } //If everything is okay let's register this user $insert = mysql_query("INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')"); if(!$insert){ die("There's little problem: ".mysql_error()); } echo $username.", you are now registered. Thank you!<br><a href=login.php>Login</a> | <a href=index.php>Index</a>"; } switch($act){ default; register_form(); break; case "register"; register(); break; } ?> Here is the connect.php code <?php $hostname="mysql6.000webhost.com"; //local server name default localhost $username="a5347792_users"; //mysql username default is root. $password=""; //blank if no password is set for mysql. $database="a5347792_users"; //database name which you created $con=mysql_connect($hostname,$username,$password); if(! $con) { die('Connection Failed'.mysql_error()); } mysql_select_db($database,$con); ?>
  24. Hi experts,I have the following problem.I have a file login.php which is used to allow users to log in.When the form is submitted it is redirected to checkuserlogin.php.If the credentials are right he is redirected to main.php.But in main.php if the user clicks back browser button,he is redirected to login.php and in login.php if he presses forward button,he is redirected to main.php.Can any one tell he how to make sure the application is not redirected to main.php when user presses forward button and how to make sure the application is not redirected to login.php when user presses back button.
  25. Hi could you help me get this login page working? I made a form which posts to login.php the "user" and "pass". Then this is my code for login.php: <?php include("mysql_connect.inc.php"); ?> <?php $user = $_POST['user']; $pass = $_POST['pass']; session_start(); $query = mysqli_query("SELECT * FROM users WHERE username='$user'"); $results = mysqli_query($con, $query) or die(mysqli_error($con)); $resultsarray = mysql_fetch_array($userresults); if (isset($_POST['user']) && $_POST['user'] == $query && isset($_POST['pass']) && $_POST['pass'] == $query) { $_SESSION['username'] = $_POST['user']; echo "<p>Login success. You are logged in as: " . $_SESSION['username'] . "</p>Return to mainpage, click <a href='index.php'>here</a>!"; } else { echo "<p>Wrong username or password.</p>"; } mysqli_close($con); ?>
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.