PHP - How To Safely Store Passwords
What do I need to do to *safely* capture and store User Passwords in a Registration Form?
There was a thread that I started a few months ago where someone had given a really good response talking about "Salt" and so on, but for the life of me I cannot find that info. Nonetheless, I need some help getting my head back into this topic! My Registration Form is complete, and the last thing I need to do is make sure Users enter a "Strong Password" and then I need to store that somewhere, somehow, in the most *secure* manner possible... Thanks, Debbie Similar TutorialsI'm incorporating a dynamic salt into my user system, but I'm not sure how to store the salt itself. The password is hashed and added to the database, but wouldn't you need to store the salt as plain text in the database in order to verify the login later? Also, I've read that using both a dynamic and static salt is good practice. If this is the case, is the static salt simply defined within the PHP? Or is there another method to storing it? Thanks for the help I just finished adding the ability to add Comments after Articles on my website. Now it would be nice if people could Quote other Posts/Comments juts like you can do here on PHPFreaks. The problem is that I have this code to eliminate any security issues with HTML... echo ' <div class="userPost"> <span class="commentDate">Posted on: ' . date('Y-m-d g:ia', strtotime($createdOn)) . '</span> <span class="commentNo">#' . $commentCount . '</span> <p>' . nl2br(htmlentities($comments, ENT_QUOTES)) . '</p> </div>'; Any suggestions to have it both ways? Thanks, Debbie On my website, I have Sticky Forms that use the following style code... <input id="firstName" name="firstName" type="text" maxlength="30" value="<?php if(isset($firstName)){echo htmlspecialchars($firstName, ENT_QUOTES);} ?>" /><!-- Sticky Field --> Do I need to use htmlspecialchars($firstName, ENT_QUOTES); anytime I output data to the screen?? For example, in this code do I need to wrap $username?? echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . $username . '</strong> </a>'; Debbie What is the latest and greatest way to hash data in PHP? I produce a series of php variables in a php strict (mostly come from mysql), and I want to save them as a php file. To be use for "include". What is the safest way to write them in a php file? I tried to save them in the manner of saving a text file with fwrite as Code: [Select] $data='<?php $cat=array('array created in the text'); $string='some value';?>'; $fh = fopen("file.php", 'w'); fwrite($fh, $data); Now, file.php is a normal php file and I can call it with "include"; but the problem is that this method is not safe. For example, if the string is "There's something", php gives error for the presence of ' in the string. I can skip ' and " by backslash; but this method is costy, as I need to perform this process for all strings to be saved. Moreover, there might be other source of errors too (that I have not encountered yet). Is there a safe way for writing a php code to file? I came across this amazing (not) blog to allow the user to reset their password. It basically does:
User submits their email to server and requests new password.
Server gets their users_id from the DB based on their email, and emails them with a link which contains ?encrypt=md5(1290*3+USERS_ID).
When clicked, server retrieves user where md5(90*13+USERS_ID)=$_GET['encrypt'], and display a form. I think the math is a typo.
When the form is submitted, the password is changed.
What is the correct way to do this?
Hey all, I posted a few months ago trying out my first salted password and I utterly failed lol. This is a small snippet from my current attempt. Code: (php) [Select] $salt = md5(uniqid(rand())); $Pass_S = md5($pass.$salt); This is only the password and salt generation part. I'm sure the salt generation is probably too simple so please feel free to give your thoughts on that part. Also the salt is stored on the database to be pulled up later for login uses. Thanks all! Hey, I know this questions get asked a lot but here is a different version of it. What is a simple and secure method for storing data/passwords? I know there is a lot of debate in this subject but I run a browser game off my server and just want the data to be encrypted. is this good enough or is this easy to crack? Code: [Select] <?php $password = 'abcdefg'; $salt = 'whateversecrethash'; $pw_hash = md5($salt.$password); ?> or I just found this tutorial is this up to date and actually a good method? http://webhole.net/2010/10/30/php-password-encryption-with-salt/ This is my code it's not working.
$username = $_POST['username']; $password = $_POST['password']; $encrypt_password = md5($password); $email = $_POST['email']; $usrsql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$encrypt_password'"; //--> Below is the INSERT Code $query = "INSERT INTO `x_users` (username, password, email) VALUES ('$username', '$encrypt_password', '$email')"; $result = mysql_query($query); if($result == 1) { print("Thank you, your accout has been created!"); }Can anyone tell me why the md5() function is not working? Edited by Tom8001, 28 November 2014 - 07:49 PM. I'll start by apologizing for the stupid decision that led to this question. A few years ago, I created a PHP/Myysql site with a login system and I created a field in the MySQL called "password" and it stored literally the exact password people entered (I know, I know).
The site has proven to have nice traffic potential, so I am going to re-vamp everything, including storing passwords properly (i.e. hashed).
My first question... Is there a way to convert regular text passwords to hashed passwords? For example, I could create a new field in the "User" table for "hashedpassword" and write a script that takes all the insecure passwords and turns them into hashed passwords. Then deleted the previous "bad" password field from the database. This would allow me to do it without the customer every knowing anything changed.
Quick googling appears to support that it IS doable rather easily, with something like...
UPDATE mytable SET password = MD5(password)If not, I guess I would have to create a thing where the first time omeone logged in after I put hashing in place, the site would force them to change their password. I'd rather not annoy the visitors if it all possible. Second question, what is the proper/recommended hashing method to use? Some people seem to poo-poo MD5. If you agree, should I use: MD5 SHA MD5 with a salt SHA with a salt Something else i never heard of NOTE: My site is a fantasy sports site, so the data involved is not overly important. Maybe a salt is overkill? Or is being overly safe never a bad thing? Lastly, don't need to address this, but if anyone can explain it like I'm 5 that would be great because i must be missing something... if you can easily turn a regular password into a hashed password, couldn't hackers easily do the reverse, which would render the hashing almost useless? I get that salting helps, but before salting (i.e. doing ONLY MD5), I don't see how hashing helped that much (if you could reverese figure out the password). What am I missing? Thanks! Greg Edited by galvin, 13 November 2014 - 09:44 AM. Hey All, I'm tryin to make a log-in system for multiple usernames and passwords, but I don't really know how many if statements i'd need for it.. I'm also a noob.. Code: [Select] <?php session_start(); $users = array("user1" =>"3202", "user2" =>"2002", "user3" =>"1061", "user4"=>"1400", "user5"=>"1001"); if($_REQUEST['username'] == "infs" && $_REQUEST['password'] == "3202"){ $_SESSION['username'] = "user1" ; $_SESSION['password'] = "3202" ; $_SESSION['username'] = "user2" ; $_SESSION['password'] = "2002" ; $_SESSION['username'] = "user5" ; $_SESSION['password'] = "1001" ; $_SESSION['username'] = "user3" ; $_SESSION['password'] = "1061" ; $_SESSION['username'] = "user4" ; $_SESSION['password'] = "1400" ; header("Location: home.php "); }else{ After checking if the matching username and password exist in my array then save them in a session... What's the best way of doing it? Hi there I have a problem here, I think I may know what it is but just wanted some guidance on this issue. I took the logic from a previous help from the people on this forum and here is my landing page: <?php // ini_set("display_errors", 1); // randomly starts a session! session_name("jeremyBasicLogin"); session_start(); if(isset($_SESSION['username'])) { // display whatever when the user is logged in: echo <<<ADDENTRY <html> <head> <title>User is now signed in:<title> </head> <body> <h1>You are now signed in!</h1> <p>You can do now what you want to do!</p> </body> </html> ADDENTRY; } else { // If anything else dont allow access and send back to original page! header("location: signin.php"); } ?> This is where the user goes to when they go to this system (not a functional system, ie it doesnt actually do anything its more for my own theory. As you wont have a session on the first turn to this page it goes to: signin.php which contains: <?php // ini_set("display_errors", 1); require_once('func.db.connect.php'); if(array_key_exists('submit',$_POST)) { dbConnect(); // connect to database anyways! // Do a procedure to log the user in: // Santize User Inputs $username = trim(stripslashes(mysql_real_escape_string($_POST['username']))); // cleans up with PHP first! $password = trim(stripslashes(mysql_real_escape_string(md5($_POST['password'])))); // cleans up with PHP first! $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); if(mysql_num_rows($result) == 1) { session_name("jeremyBasicLogin"); session_start(); $_SESSION['is_logged_in'] = true; $_SESSION['username'] = $username; //print_r($_SESSION); // debug purposes only! $_SESSION['time_loggedin'] = time(); // this is adding to the array (have seen the output in the SESSION vars! // call function to update the time stamp in MySQL? header("location: index.php"); } else if(mysql_num_rows($result) != 1) { $message = "You typed the wrong password or Username Please retry!"; } } else { $message = ""; } // displays the login page: echo <<<LOGIN <html> <body> <h1>Example Login</h1> <form id="login" name="login" action="{$_SERVER['PHP_SELF']}" method="post"> <label for="username">Username: </label><input type="text" id="username" name="username" value="" /><br> <label for="password">Password: </label><input type="text" id="password" name="password" value="" /><br> <input type="submit" id="submit" name="submit" value="Login" /> </form> LOGIN; echo "<p>" . $message . "</p>"; echo <<<LOGIN <p>Please Login to View and Edit Your Entries</p> <p><a href="register.php">Click Here To Signup</a><p> </body> </html> LOGIN; ?> This checks through user inputs and hopefully logs them in, when Ive inserted the data into the database itself it works, if I try and login but if a user fills in this form: signup.php: <?php //ini_set("display_errors", 1); $message =''; require_once('func.db.connect.php'); if(array_key_exists('submit',$_POST)) { dbConnect(); // connect to database anyways! // do some safe protecting of the users variables, apply it to all details! $username = trim(stripslashes(mysql_real_escape_string($_POST['username']))); // cleans up with PHP first! $email = trim(stripslashes(mysql_real_escape_string($_POST['email']))); // cleans up with PHP first! $password = trim(stripslashes(mysql_real_escape_string(md5($_POST['password'])))); // does as above but also encrypts it using the md5 function! $password2 = trim(stripslashes(mysql_real_escape_string(md5($_POST['password2'])))); // does as above but also encrypts it using the md5 function! if($username != '' && $email != '' && $password != '' && $password2 != '') { // do whatever when not = to nothing/empty fields! if($password === $password2) { // do database stuff to enter users details $sql = "INSERT INTO `test`.`users` (`id` ,`username` ,`password`) VALUES ('' , '$username', MD5( '$password' ));"; $result = mysql_query($sql); if($result) { $message = 'You may now login by clicking <a href="index.php">here</a>'; } } else { // echo out a user message says they got their 2 passwords incorrectly typed: $message = 'Pleae re enter your password'; } } else { // they where obviously where empty $message = 'You missed out some required fields, please try again'; } } echo <<<REGISTER <html> <body> <h1>Register Form</h1> <p>Please fill in this form to register</p> <form id="register" name="register" action="{$_SERVER['PHP_SELF']}" method="post"> <table> <tr> <td><label for="username">Username: </label></td> <td><input type="text" id="username" name="username" value="" /></td> </tr> <tr> <td><label for="email">Email: </label></td> <td><input type="text" id="email" name="email" value="" /></td> </tr> <tr> <td><label for="password">Password: </label></td> <td><input type="text" id="password" name="password" value="" /></td> </tr> <tr> <td><label for="password">Confirm Password: </label></td> <td><input type="text" id="password2" name="password2" value="" /></td> </tr> <tr> <td><input type="submit" id="submit" name="submit" value="Register" /></td> </tr> <table> REGISTER; echo "<p>" . $message . "</p>"; echo <<<REGISTER </form> </body> </html> REGISTER; ?> As I said when the user signs up when submitting the above form, it doesnt work, keeps coming up with a different value for the password, so I am about 99% certain its the password, but I have been maticulous about copying in the sanitize function for SQL injections and it just doesnt still work, really puzzled now. Any helps appreciated, Jeremy. Hello, I have a variable called $Price, We are getting it through Mysql Database using While loop. We getting the data from database in ordered by ID. Now then i have requirement to store that data into Low to High form ... Like we are receiving $price lke unordered form .. 50 14 35 25 00 145 52 Here i just want to store it in Low to high form like 00, 14,25,35 ... and so on .. Please suggest me the appropriate code. While($myrow=mysql_fetch_array($result, MYSQL_ASSOC)) { some codes return value $price. // want to store in array } $array($price) // here want to store in Low to high with key value. Well, I am storing some of images on my server, but I have to type in the name myself which gets a bit boring and I may overwrite an old image by accident, so, I was thinking of having mysql auto increment the image names. But will this be suitable for images, or should it be text. Hi, I am writing a advertisement system, where i have two fields Ad_Start_date Ad_End_Date i was always confused, in doing this things regarding date whether to use datetime or timestamp in mysql Thanks, Hi, I want to maintain users who log in a webpage and each time they leave, I want to record the current time, so this sounds silly but do I just set in my db table in a field that tracks a user's last log in with DEFAULT: CURRENT_TIMESTAMP? db structu user_id lastActivity lastSession (stores TIMESTAMP of last time user logged in) Any help much appreciated It seems that in the following script I am not able to make $page contain some values as it always acts as it contains 0. The script will give you more idea about what I wanna do with it. Code: [Select] <?php include('dbinfo.inc'); session_start(); $connect= mysql_connect($host,$dbuser,$password) or die("connect to database fails"); mysql_select_db($dbname, $connect); //This will set the number of messages we want to display on each page $rows_per_page = 5; function show_msg() { echo "<tr align='center'> <td>$row[message]</td> </tr> <tr><td><strong>Sent By: $_SESSION[username] ON Date: $row[date]</strong></td></tr> <tr><td></td></tr>"; } //This will set the necessay variables required to set the page layout function page_vars() { $sql = "select * from msgs"; $result = mysql_query($sql, $connect); $numrows = mysql_num_rows($result); $total_pages = ceil($numrows/$rows_per_page); //Check whether page is given or not if(isset($_GET["page"])) { $page = $_GET["page"]; } else { $page = 1; } if($page < 1): { $page = 1; } elseif($page > $total_pages): { $page = $total_pages; } endif; } if($_SESSION[loggedin] == TRUE && $_SESSION[actype] == lecturer) { echo "<form action='postmsg.php' method='POST'>"; echo "<table width='80%' border='1'><tr align='center'><td><strong>To send a new message type it in the below box and press SUBMIT</strong> </td></tr>"; echo "<tr align='center'> <td><textarea name='msgarea' cols='40' row='5'></textarea></td> </tr> <tr align='center'> <td><input type='submit' value='Send Message' /></td> </tr> </table>"; $limit .= 'LIMIT '.($page - 1)*$rows_per_page.', '.$rows_per_page; echo $limit; $sql = "select * from 'msgs' $limit"; $result = mysql_query($sql); echo "<table width='80%' border='1'>"; $row = mysql_fetch_assoc($result); while($row) { show_msg(); } } else { page_vars(); $limit .= 'LIMIT '.($page - 1)*$rows_per_page.', '.$rows_per_page; $sql = "select * from msgs $limit"; $result = mysql_query($sql,$connect); echo "<table width='80%' border='1'>"; while($row = mysql_fetch_assoc($result)) { show_msg(); } echo "<tr align='center'> <td> <a href='$_SERVER[php_self]?page=1'>First Page</a> <a href='$_SERVER[php_self]?page=($page - 1)'>$page</a> <a href='$_SERVER[php_self]?page=$page'>$page</a> <a href='$_SERVER[php_self]?page=($page + 1)'>$page</a> <a href='$_SERVER[php_self]?page=($total_pages)'>>>>Last Page</a> </td> </tr>"; echo "</table>"; } ?> now when i echo $limit it always shows "-5, 5" , that's not what i want from this script. Instead I want limit to store "0, 1" with the same concept not direct because it will change according to what $_GET[page] holds. Hope I will get the solution here.... how do i get a drop down value and store it in a another table as of now i am getting the value from one table showing it on drop down now once that is selected i need to insert it into another table. <html> <?php mysql_connect('localhost','root','') or die('Could not connect to mysql ' . mysql_error()); mysql_select_db("dbtest") or die(mysql_error()); if(isset($_POST['submit'])) { //$name=$_POST['val']; $id = $_POST['select']; $id=$row['name']; ?> <input type="text" name="name2" value="<?php echo $row['name'] ?>"><br /> <?php $query = "INSERT INTO sub (`sub`) values('" . $id . "')"; $result = mysql_query($query); if($query) { echo "query executed"; } } ?> <form id="name" action="<?php $_POST['SERVER_SELF'] ?>" method="POST" > <input type="text" name="name1"><br /> <select name="select" id="select"> <?php $query = "SELECT name,id FROM main"; $result = mysql_query($query); if($query) { while($row = mysql_fetch_array($result)) { $options .= '<option value="' . $row['name'] . '">' . $row['name'] . '</option>'; // $out .= "<option value=\" . $row['name'] . \" >' . $row['name'] . '</option>"; } } echo $options; ?> </select> <input type="submit" name="submit1"> </form> </html> Thanks the above seem to work. Hi,
I am building a website that will contain listings, there will be a categories page which will bring the user to the subcategories for that category then the user can see all listings linked to that subcategory. At the minute I am just linking each page using basic href tags to go to the page name.php and all my pages end up being homepage.com/clickedlink.php.
How do I change my URL's so that if i click on a certain category the url changes to page name.php?category=chosen category?
Thanks
I added the ability for Users to "preview" their Comments before submitting them. I just realized that when they click "Preview" that their Comments appear above the Comments form box - similar to how PHPFreaks works - but that the Comments form box loses it's data since the page reload causes this to lose things... <li> <label for="comments">Comments:</label> <textarea id="comments" name="comments" cols="50" rows="15"><?php if (isset($comments)){echo nl2br(htmlentities($comments, ENT_QUOTES));} ?></textarea> <?php if (!empty($errors['comments'])){ echo '<span class="error">' . $errors['comments'] . '</span>'; } ?> </li> What is the easiest way to maintain form persistence? (I really would like to avoid having to store things in my database during the preview.) How does PHPFreaks do things? I was going to use a SESSION, but since this is a Comments field that can take up to 65,535 characters, that probably won't work?! Any ideas? Debbie |