PHP - Using A Database To Store Username/password Combos.
Hi,
my goal is to be able to create a web based interface for someone who has no programming skills or interest to be able to maintain a list of usernames and passwords for protecting a page of links on a website. so, I've created a page that can write to a database, and I can see that it is working, I can read entries, etc. now, I need to know how to make a script that will check against that database for valid UN/PW combinations. what is the best method for this? James Similar TutorialsI have had a load of people who are silly enought to forget their username and or password so wish to add in the option for them to save their details in a cookie, and break my number one rule, never to use them!!! can anyone suggest how i can do this so it is stored safely like most websites do it. Alright, I've been assigned a project at work. I did not develop the application and the individual who did used CodeIgnited framework and mysql as the db.
Here's the problem, I'm not given much OT to do this and in our meeting the best way to proceed was to replicate the database for different parts of the organization. Basically we are a subsidiary and have been using an application that other groups within the organization want to use. Usually I would reconfigure the db schema and add org ids and in the user table add the appropriate organization to go to. However, they are not giving me enough time to do that.
So what I'm thinking is to just create a copy of the database we use (just the structure) and create a new database.
What I want to know is how to use mysql to check to see if a user exists in one database and if they don't then to go on to the next database. I understand this is a very sloppy way to do it, but it's the way we are moving forward.
I found the code to connect to the db in CodeIgnitor... how can I connect to a database, check to see if the user exists, then close that db connection and try the next database?
/** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return @mysql_select_db($this->database, $this->conn_id); }Thanks in advance. Code: [Select] <?php session_start(); include("global-settings.php"); mysql_connect($dbhost, $dbuser, $dbpass)or die("Could Not Connect: " . mysql_error()); mysql_select_db($dbname) or die(mysql_error()); $email = mysql_real_escape_string(strip_tags($_POST["email"])); $password = sha1($_POST["password"]); $result = mysql_query("SELECT * FROM users WHERE email = '{$email}' AND password = '{$password}'"); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result); $_SESSION["userid"] = $row['user_pid']; echo "logged in"; } else { $userid_generator = uniqid(rand(), false); mysql_query("INSERT INTO users (user_pid, email, password, datetime_registered, is_leader) VALUES ('$userid_generator', '{$email}', '{$password}', NOW(), 'no')"); $id = mysql_insert_id(); $leaders = mysql_query("SELECT * FROM users WHERE is_leader LIKE '%yes%'"); while($rows = mysql_fetch_array($leaders)) { if ($rows['is_leader'] == 'yes') { $leader_id = $rows['user_pid']; mysql_query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type) VALUES('$leader_id', '$userid_generator', NOW(), 'full')"); $_SESSION["userid"] = $userid_generator; echo "new user created and logged in"; if(is_dir($userid_generator)) { echo "Something wen't wrong. A bug report has been sent and we are doing what we can to fix it."; $message = 'Registration problem on account number $userid_generator. The user succesfully registered, but there is already a directory with the account id of $userid_generator.'; mail($bug_report_email, "Registration Bug!", $message); } else { mkdir('../media/User-PID{' . $userid_generator . '}', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/photos', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/backups', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/videos', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/documents', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/developer', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/developer/apps', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/developer/themes', 0777); mkdir('../media/User-PID{' . $userid_generator . '}/xml', 0777); } } } } ?> It logs in fine. It even registers fine, but how do I code it to do something if username is correct but password isn't correct? There is a login page called login.php, after user type their username and password into textbox, then the page direct it to the page validate, which is validate.php. In validate.php, if user do not type anything, then direct it to the login.php again; if user type their username and password worng less than 3 times, then direct it to the login.php also. However, if user type their username and password more than 3 times, then direct it to the register.php.
Question: i don't know how to make 3 attempts (maybe there are something worng in my page), it doesn't work, Please help, here is my validate.php
<?php $loginErrorV = false; $loginErrorW = false; if(!empty($_POST['username']) && !empty($_POST['password']) && strlen($_POST['username'])!=0 && strlen($_POST['password'])!=0) { // $username = $_POST['username']; $password = $_POST['username']; //Connect to Database $conn = mysql_connect("localhost", "root", ""); if(!$conn){ die('Could not connect:'.mysql_error()); } mysql_select_db("logindb", $conn); // $sql = "Select count(username) as user_exist from logint where username = '$username' and password = '$password'"; $result = mysql_query($sql, $conn); $row = mysql_fetch_assoc($result); // if($row['user_exist'] == 1){ session_start(); $_SESSION['username'] = $username; header('Location: 10586740.html'); mysql_close($conn); } else { $loginErrorV = true; } } else { $loginErrorW = true; } if($loginErrorV){ if(isset($_COOKIE['login'])){ if($_COOKIE['login']<3){ header('Location:login.php'); $attempts = $_COOKIE['login'] + 1; } else { header('Location:register.php'); } } } if($loginErrorW){ header('Location:login.php'); } ?> Took Skoglund's Lynda course on creating a CMS for a project I am doing for a customer. I was extremely careful to set up the database, and pretty much copying everything he was doing in the course. So, I try to create a user in the database, and....crickets. Name and password don't come up. No error messages from the site. Just, nothing. So I'm sure it's pretty simple to fix, otherwise, there would have been chaos, right? For the page: hawcreekrenovations.com/new_user.php We know the page is correctly connecting to the MySQL because the drop down in the form is populated by the user-types in the database. So, I guess, you need the pertinent code: Code: [Select] // START FORM PROCESSING if (isset($_POST['submit'])) { //Form has been submitted $errors = array(); // perform validations on the form data $required_fields = array('username', 'password', 'user_type_id' ); $errors = array_merge($errors, check_required_fields($fields_with_lengths, $_POST)); $fields_with_lengths = array('username' => 30, 'password'=> 30); $errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST)); $username = trim(mysql_prep($_POST['username'])); $password = trim(mysql_prep($_POST['password'])); $hashed_password = sha1($password); $user_type_id = trim(mysql_prep($_POST['user_type_id'])); if ( empty($errors) ) { $query = "INSERT INTO users ( username, hashed_password, user_type_id ) VALUES ( '{$username}', '{$hashed_password}', '{$user_type_id}' )"; $result = mysql_query($query, $connection); if ($result) { $message = "The user was successfully created."; } else { $message = "The user could not be created."; $message .= "<br />" . mysql_error(); } } else { if (count($errors) == 1) { $message = "There was 1 error in the form."; } else { $message = "There were " . count($errors) . " erros in the form."; } } } else { // Form has not been submitted. $username = ""; $password = ""; } ?> And the form: Code: [Select] <form action="new_user.php" method "post"> <table> <tr> <td>Username:</td> <td><input type="text" name="username" maxlength="30" value="<?php echo htmlentities($username); ?>" /></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" maxlength="30" value="<?php echo htmlentities($password); ?>" ? /></td> </tr> <tr> <td>User Type:</td> <td><?php // 3. Perform database query $result = mysql_query("SELECT * FROM user_type", $connection); if (!$result) { die("Database query failed: " . mysql_error()); } // 4. Use returned data (if any) echo "<select name='type'>"; while ($row = mysql_fetch_array($result)) { echo "<option value=\"".$row["user_type_id"]."\">".$row["type"] . "</option>"; } echo "</select>"; ?></td> </tr> <tr> <td colspan="2"><input type="submit" name="submit" value="Create user" /></td> </tr> </table> </form> hi, i have a password array system and i want to be able to make a php to add a username, password and a homepage, the same as the username just at the end of a URL: The array file code looks like this: Code: [Select] <?php //My Login Page //u //u //u //Users and Settings $domain_code = 'blogger123'; //Alpha Numeric and no space $random_num_1 = 213; //Pick a random number between 1 to 500 $random_num_2 = 754; //Pick a random number between 500 to 1000 $random_num_3 = 2; //Pick a random number between 1 to 3 //Usernames can contain alphabets, numbers, hyphens and underscore only //Set users below - Just add '' => '' with the first '' being //the username and the second '' after the => being the password. //Its an array so add an , after every password except for the //last one in the list. As shown below //Eg. $users = array( // 'user1' => 'password', // 'user2' => 'password' // ); $users = array( array('user1', 'test', '/users/1/'), array('user2', 'test', '/users/2/') array('user2', 'test', 'tusers/2/') array('user2', 'test', '/users/4/') array('user2', 'test', '/users/5/') array('user2', 'test', '/users/6/') array('user2', 'test', '/users/7/') array('user2', 'test', '/users/8/') array('user2', 'test', '/users/9/') array('user2', 'test', '/users/10/') array('user2', 'test', '/users/11/') array('user2', 'test', '/users/12/') array('user2', 'test', '/users/13/') array('user2', 'test', '/users/14/') ); ?> thanks in advance I need to come up with a better way to do this. Currently I have a script which is a form and the user enters their email address, and their password in the database is sent to the email address. Problem is the password is MD5 hashed, so it's hashed when sent to their email. I am sure there is a better way to do this. Also, I am capturing a Security Question and Answer in the initial profile form that the user fills out, so I need to incorporate this as an extra layer of security. Please let me know of the methods for doing this. Thanks in advance! I've never actually done a username password, retrieval script before so need a little help. In the profile form the user is submitting username/password/name/email etc. into a MySQL DB along with a security question and answer. Is it just a matter of creating a form which does a check against the database and sends out an email to the user with their password? The password is hashed with MD5, so how would I send out an un-hashed PW? thanks! I have a div on my webpage that will contain an error message, basically 'username or password incorrect.' At the moment on the login page I have the div containing: Code: [Select] <div id="errorMessage"><?php echo $errorMessage; ?></div> and in the php code i have: Code: [Select] $errorMessage = ""; if(isset($_POST['username'])) { // check if username and password exists // else $errorMessage = "username or password incorrect"; } but unfortunately this doesn't seem to show on the page, any ideas? Dear all, Can somebody help me please? Instead of ‘username’ and 'password', I need random values from CSV file. Can somebody show me how can I do this? My CSV file looks like this: user001,userpass001 user002,userpass002 user003,userpass003 My script looks like this: <?php $t= new post(); $t->username='username'; $t->password='password'; $res = $t->update('This is some text.'); ?> Thank you very much advance. Hi all,
I have been reading in almost everywhere that we should not use our own custom login and password validations ( like regex etc.) but instead use the filter_var and filter_input built in functions provided by PHP 5 and above. However even after searching for more than an hour for with different search strings, I have not found even a single example that shows how we may validate for a username/login and password in a login form. Can someone be kind enough to provide a strong secure validations for username and login.
Additionally I would also like to clarify if the username and login fields in a Login form be manipulated in any manner to pose a security threat? I mean can a hacker craft a username/login or password in such a manner as to pose an injection or any other threat?
Thanks all.
I am trying to validate username and password fields. I want to use preg match, but have little knowledge of this function. I want the password to only contain A-z 0-9 and with at least one letter and one number. Username needs to only include "A-z 0-9 _ -" no spaces in any of these. Here is what I have so far: $username= $_POST['username']; $password = $_POST['password']; $password2 = $_POST['password2']; if($password==$password2){ if( preg_match("[A-z0-9]", $password) || strlen($password)>6 // at least 7 chars || strlen($password)<26 // at most 20 chars ){$errors[] = 'Password must contain at least one number and letter plus be between 7-25 characters. May only contain alphanumeric characters, _ and .';} }else{$errors[] = 'Your Passwords did not Match';} if( preg_match("[A-z0-9_-]", $username) || strlen($username)>5 // at least 6 chars || strlen($username)<26 // at most 25 chars ){ $errors[] = 'Username must be 6-25 characters and contain only alphanumeric characters, _ and .'; } I'm having a little issue with this script. It's returning: "Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/zyquo/public_html/makethemoviehappen.com/forgot_password.php on line 89" (Line 89 is: $num_rows1 = mysql_num_rows($result1) and "New password could not be generated. If you continue to have issues, please email general@makethemoviehappen.com for assistance." I checked the database and the random password generation did run, and it was inserted into the database. So it's just not detecting that it ran, so it's not sending the email. Any ideas on why? I also checked what is returned in the $result1 variable and it's the number 1. Code: [Select] elseif($_GET['forgot']=="password"){ function &generatePassword($length=9, $strength=0) { $vowels = 'aeiuy'; $consonants = 'bcdfghjkmnpqrstwz'; if ($strength & 1) { $consonants .= 'BCDFGJLMNPQRSTVXZ'; } if ($strength & 2) { $vowels .= "AEIUY"; } if ($strength & 4) { $consonants .= '23456789'; } if ($strength & 8) { $consonants .= '@#$%'; } $password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { if ($alt == 1) { $password .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $password .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } } return $password; } $new_password =& generatePassword(); $username=$_POST['username']; $sql="SELECT * FROM $tbl_name WHERE Username='$username' AND Email='$email' AND Amount='$donation_amount'"; $result=mysql_query($sql); $num_rows = mysql_num_rows($result); if($num_rows==1){ $sql1="UPDATE $tbl_name SET Password='$new_password' WHERE Username='$username' AND Email='$email' AND Amount='$donation_amount'"; $result1=mysql_query($sql1); $num_rows1 = mysql_affected_rows($result1); if($num_rows1==1){ $content.='<p class="center">New password generated. It has been emailed to the email address provided.</p><br />'; $message='Some one (hopefully you) requested a new password be generated for your account on Make the Movie Happen. Below is the newly generated password: Password: '.$new_password.' Once you log-in, please change your password. Thank You, Make the Movie Happen Support Team '; mail($email, 'Make the Movie Happen - New Password', $message, 'From: general@makethemoviehappen.com'); } else{ $content.='New password could not be generated. If you continue to have issues, please email <a href="mailto:general@makethemoviehappen.com">general@makethemoviehappen.com</a> for assistance.'; } } else{ header("Location: ./index.php?forgot&e=1"); } } Hi Guys,
I have a very simple table called: registered_users
there is only 4 columns
column 1 = id
column 2 = username
column 3 = password
column 4 = salt
the password is hashed and salted when it's added to the table.
The problem is, that my username and password isn't being "seen" by the code so it's not sending me to the next page, it is only sending me back to the login page - not validated.
Please could you help me understand what i may be doing wrong here, it all looks okay to me but that's not obviously the case?
Here is the validation for username and password to login:
/* validate the username and the password */ if((!isset($_POST['username'])) || (strlen(trim($_POST['username'])) <5) || (trim($_POST['username']) != preg_replace("/[^a-zA-Z0-9\_]/", "", trim($_POST['username'])))) { /* if is bad */ $my_error = 1; }else{ $username = mysql_real_escape_string(trim($_POST['username'])); } /* END validating username */ /* validate the password */ if((!isset($_POST['password'])) || (strlen(trim($_POST['password'])) <5) || (trim($_POST['password']) != preg_replace("/[^a-zA-Z0-9\_]/", "", trim($_POST['password'])))){ /* if is bad */ $my_error = 1; }else{ $password = trim($_POST['password']); } /* END validating password */ /* if any of the post variables are invalid send back to the form page */ if($my_error != 0) { $_SESSION['error_message'] =$error_message; header("Location: index.php"); exit(); } /* FUNCTION TO CREATE SALT */ function createSalt(){ $string = md5(uniqid(rand(), true)); return substr($string, 0, 3); } /* check to see if username is in the table if not send back to login */ $query01 = "SELECT * FROM registered_users WHERE username = '$username'"; $result01 = mysql_query($query01) or die(mysql_error()); if(mysql_num_rows($result01) != 1) { header("Location: index.php"); exit(); } $row = mysql_fetch_array($result01); $salt = $row['salt']; $hash = hash('sha256', $salt, $password); $query02 = "SELECT id FROM registered_users WHERE username = '$username' AND password = '$hash'"; $result02 = mysql_query($query02) or die(mysql_error()); if(mysql_num_rows($result02) !=1){ header("Location: index.php"); exit(); } $_SESSION['id'] = $row['id']; $_SESSION['valid_user'] = "yes"; header("Location: admin02.php"); exit(); ?>Thanks Andy Edited by Ch0cu3r, 05 July 2014 - 09:14 AM. how could we put this into a form? Code: [Select] $username = "@yahoo.com"; $password = "pass"; // do login to facebook $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "https://login.facebook.com/login.php?m&next=http://m.facebook.com/home.php"); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_POSTFIELDS, "email=" . $username . "&pass=" . $password . "&login=Log In"); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl, CURLOPT_COOKIEJAR, getcwd() . '/cookies_facebook.cookie'); $curlData = curl_exec($curl); curl_close($curl); // do get post url $urlPost = substr($curlData, strpos($curlData, "action=\"/a/home") + 8); $urlPost = substr($urlPost, 0, strpos($urlPost, "\"")); $urlPost = "http://m.facebook.com" . $urlPost; // do get some parameters for updating the status $fbDtsg = substr($curlData, strpos($curlData, "name=\"fb_dtsg\"")); $fbDtsg = substr($fbDtsg, strpos($fbDtsg, "value=") + 7); $fbDtsg = substr($fbDtsg, 0, strpos($fbDtsg, "\"")); $postFormId = substr($curlData, strpos($curlData, "name=\"post_form_id\"")); $postFormId = substr($postFormId, strpos($postFormId, "value=") + 7); $postFormId = substr($postFormId, 0, strpos($postFormId, "\"")); // do update facebook status $statusMessage = "Status updated :-)"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $urlPost); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "fb_dtsg=" . $fbDtsg . "&post_form_id=" . $postFormId . "&status=" . $statusMessage . "&update=Update Status"); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl, CURLOPT_COOKIEFILE, getcwd() . '/cookies_facebook.cookie'); curl_setopt($curl, CURLOPT_COOKIEJAR, getcwd() . '/cookies_facebook.cookie'); $curlData = curl_exec($curl); curl_close($curl); echo "Your Facebook status already updated with '" . $statusMessage . "'"; Hey guys I have a simple question, I have a Config.php file that connects to mysql database on my server... Something like this (modified data, of course): <?php // database information $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = '******'; $dbname = 'databasename'; ?> Can a hacker access those variables? How can I protect this? Ideas, suggestions? Thanks in advance! Hi there
I am just finalising my first ever PHP/MYSQL project and I am worried about where to safely keep my connection credentials for the SQL DB.
Currently, I am storing them in ../php/config.php and this works fine, but I am worried as to the security of this
Can anyone advise please
Thanks
Hi guys Can someone help me about this: The php code can be revise username and password with CURL then check database and if username & password is correct return true else false. Thanks Can someone tell me why my php code isn't inserting users into the database. My database is made and table is made. I created a register form so my visitors can register but im getting a blank page. I has something to do with the following code
$statement = $connection->prepare('INSERT INTO users (username, email, password) VALUES (:usernamebox, :emailbox, :passwordbox)');
if ($result) {
Why is there the " : " before the usernamebox
Heres how my form looks like
<form action="register-clicked.php" method="POST"> I have developed a code for a login and seems to work well (No syntax error according to https://phpcodechecker.com/ but when I enter a username and a password in the login form, I get an error HTTP 500. I think that everything is ok in the code but obviously there is something that I am not thinking about. The code (excluding db connection): $id="''"; $username = $_POST['username']; $password = md5($_POST['password']); $func = "SELECT contrasena FROM users WHERE username='$username'"; $realpassask = $conn->query($func); $realpassaskres = $realpassask->fetch_assoc(); $realpass= $realpassaskres[contrasena]; $func2 = "SELECT bloqueado FROM users WHERE username='$username'"; $blockedask = $conn->query($func2); $blockedres = $blockedask->fetch_assoc(); $bloqueado = $blockedres[bloqueado];
//Login if(!empty($username)) { // Check the email with database |