PHP - Safe Password Hash
Hi,
Recently I've been trying writing a safe password hash and I wanted to know that if I use an MD5 hash at the end, just so it will be like some short of "packed",so instead of saving a 128 string, I'll use md5 to "pack" it into 32 characters and save up to 96 characters.
I know MD5 isn't safe and all, but the question is, does it lower the security ?
Also, would be happy for feedbacks about my password hash
function hash_($input,$key) { $op=hash("whirlpool",hash("sha512",$key) . "$" . $input . "$" . hash("sha512",$key)); Similar TutorialsI have a login system Username and Password.
My password is encrypted with bcrypt, if it okay to store that bcrypt in a session as $_SESSION["hash"]
To verify that the user is who they say they are?
Or do i only need to do
$_SESSION["username"]
Hi,
I am trying to get this script to execute as an administrator of an online system. If a user has forgotten their password, I enter their username and enter a new password which they can update later. I am not sure why this is not updating the password for the username entered?
<?php // Initialize the session session_start(); // Check if the user is logged in, if not then redirect to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: login.php"); exit; } // Include config file require_once "config.php"; // Define variables and initialize with empty values $new_password = $confirm_password = ""; $new_password_err = $confirm_password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate new password if(empty(trim($_POST["new_password"]))){ $new_password_err = "Please enter the new password."; } elseif(strlen(trim($_POST["new_password"])) < 6){ $new_password_err = "Password must have atleast 6 characters."; } else{ $new_password = trim($_POST["new_password"]); } // Validate confirm password if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = "Please confirm the password."; } else{ $confirm_password = trim($_POST["confirm_password"]); if(empty($new_password_err) && ($new_password != $confirm_password)){ $confirm_password_err = "Password did not match."; } } // Check input errors before updating the database if(empty($new_password_err) && empty($confirm_password_err)){ // Prepare an update statement $sql = "UPDATE User_Accounts_ SET password = ? WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ss", $param_password, $username); // Set parameters $param_password = password_hash($new_password, PASSWORD_DEFAULT); $username = $_POST['username']; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Password updated successfully. Destroy the session, and redirect to login page session_destroy(); header("location: login.php"); exit(); } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Close connection mysqli_close($link); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Reset Password</title> <style type="text/css"> body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } </style> </head> <body> <div class="wrapper"> <h2>Reset Password</h2> <p>Please fill out this form to reset your password.</p> <p><strong>Username</strong> <input type="text" name="username" class="form-control"> </p> <p> </p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($new_password_err)) ? 'has-error' : ''; ?>"> <label>New Password</label> <input type="password" name="new_password" class="form-control" value="<?php echo $new_password; ?>"> <span class="help-block"><?php echo $new_password_err; ?></span> </div> <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>"> <label>Confirm Password</label> <input type="password" name="confirm_password" class="form-control"> <span class="help-block"><?php echo $confirm_password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit"> <a class="btn btn-link" href="welcome.php">Cancel</a> </div> </form> </div> </body> </html>
Hi guys I have a script which i've been playing around with thanks to Spiderwell: http://www.phpfreaks.com/forums/index.php?action=profile;u=35078 I have sort of merged it with another 'member managment' script which is working great. Now i can't seem to correctly create a login page to pass the hashed password using (sha1). Now all i want to do is verify the username and the (hashed) password according to the database and allow the user in. The script i am using to check login works fine without a hashed password in the database. But ideally i'd like to use a hashed form of password. Can somebody show me what change i need to make in this script below in order to pass a sha1 hashed password? I'm guessing it's a really small change from the examples i've seen online, but i just cant seem to get mine to work. :| Your help would be much appreciated. Login Page PHP: Code: [Select] <form name="login" method="post" action="check_login.php3"> <p><strong>Secured Area User Log-in</strong></p> <p>Username: <input name="bioname" type="text" id="bioname"></p> <p>Password: <input name="biopass" type="password" id="biopass"></p> <p> </p> <p><input type="submit" name="Submit" value="Login"></p> </form> Check Login Processor (which is the file i that needs the sha1 added somewhere i think) Code: [Select] <?php require_once('config.php3'); // Connect to the server and select the database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db")or die("Unable to select database"); // $loginusername = false; $loginpassword = false; $err = false; // default error message is empty // The username and password sent from login.php //the isset() basically means if its there get it, otherwise dont bother if (isset($_POST['bioname'])) $loginusername=$_POST['bioname']; if (isset($_POST['biopass']))$loginpassword=$_POST['biopass']; // if either isnt filled in, tell the user, a very basic bit of validation if (!$loginusername || !$loginpassword) $err = "please complete the form"; if (!$err) //if no error continue { //The following bit of coding protects from MySQL injection attacks $loginusername = stripslashes($loginusername); $loginpassword = stripslashes($loginpassword); $loginusername = mysql_real_escape_string($loginusername); $loginpassword = mysql_real_escape_string($loginpassword); //you could add other things like check for text only blah blah $sql="SELECT * FROM $tbl WHERE bioname='$loginusername' and biopass='$loginpassword'"; $result=mysql_query($sql); // Count how many results were pulled from the table $count=mysql_num_rows($result); // If the result equals 1, continue if($count==1) { session_start(); $_SESSION['user'] = $loginusername; // store session data //please see I have used a session variable that is generic not specific, otherwise you will have to make this page different for every user //that would be a pain in the ass, you don't need to have user1 or user2, its the value stored that relevant, not what the variable name is header("Location: {$loginusername}/index.php3"); } else { $err = "Wrong Username or Password"; } }// end login if statement if ($err) // show error message if there is one { echo $err; echo "<br>Please go back in your browser and try again"; } ?> The secure page: Code: [Select] <?php session_start(); $mypath = $_SERVER["REQUEST_URI"]; //echo $mypath; // for debugging //now we have the path lets see if the username is in that path, i.e. test2 is inside /something/test2/index.php //use the built in strpos() function, which returns position of the last occurance of the string you are looking for inside another string. //http://php.net/manual/en/function.strrpos.php if(strpos($mypath,"/".$_SESSION['user']."/"))//on testing it failed initially as username test is found in path /test2/ so i added the slashes to stop that. so /test/ doesnt get found in /test2/ { echo "congratulations you are the right person in the right place"; } else { session_destroy(); //kill the session, naughty person trying to come here header("Location: ../login.php3"); die();// stop page executing any further } ?> <html> <body> </body> </html> Thanks and i look forward to your replies. Alright, I have created a hash password checker and here is my code: include("include.php"); // include the mySQL info! $users = mysql_query(" SELECT * FROM User "); // Select all from the users table in the database! while($row = mysql_fetch_array($users)) // While it fetches the users do the following... { if (hash("sha256", $password) == $row["Password"]) echo "Congratulations! The Hash matches the password entered into the database!"; } elseif (hash("sha256", $password) != $row["Password"]) { echo "Your Hash failed to match the password entered!"; } Now for some reason this displays a totally blank page. When I turn error display on I get the error "Unexpected T_ELSEIF" on this line elseif (hash("sha256", $password) != $row["Password"]) Any help is appreciated... Hi, I am limbo with this one. What I have makes sense to me, but I know I'm missing something or doing something wrong I have been able to hash passwords with salt by new people registering to my site by doing this: if(!$error) { $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz1234567890"; $rand = str_shuffle($alpha); $salt = substr($rand,0,40); $hashed_password = sha1($salt . $_POST['password']); $query = "INSERT INTO `cysticUsers` ( `FirstName`, `LastName`, `Email`, `Password`, `salt`, `RelationshipToCF`, `State`, `Gender`, `Birthday`, `Status` )VALUES( '" . mysql_real_escape_string($_POST['firstName']) . "', '" . mysql_real_escape_string($_POST['lastName']) . "', '" . mysql_real_escape_string($_POST['email']) . "', '" . $hashed_password . "', '" . $salt . "', '" . mysql_real_escape_string($_POST['RelationToCF']) . "', '" . mysql_real_escape_string($_POST['State']) . "', '" . mysql_real_escape_string($_POST['sex']) . "', '" . mysql_real_escape_string($_POST['DateOfBirth_Year'] . "-" . $_POST['DateOfBirth_Month'] . "-" . $_POST['DateOfBirth_Day']) . "', 'pending' )"; mysql_query($query, $connection); I have been able to to update EXISTING users passwords by doing this: $query = "SELECT * FROM `cysticUsers`"; $request = mysql_query($query,$connection); while($result = mysql_fetch_array($request)) { $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz1234567890"; $rand = str_shuffle($alpha); $salt = substr($rand,0,40); $hashed_password = sha1($salt . $result['Password']); $user = $result['id']; $query2 = "UPDATE `cysticUsers` SET `salt` = '$salt' WHERE `id` = '$user'"; $request2 = mysql_query($query2,$connection) or die(mysql_error()); $query3 = "UPDATE `cysticUsers` SET `encrypted_passwords` = '$hashed_password' WHERE `id` = '$user'"; $request3 = mysql_query($query3,$connection) or die(mysql_error()); } Now, I want to be able to SIGN BACK IN with the existing password and I am failing miserably by doing this: $query = "SELECT `salt`,`id`,`email`,`password` FROM `cysticUsers` WHERE `Email` = '" . $email . "' AND `Password` = '" . $password . "' && `Status` = 'active' LIMIT 1"; $request = mysql_query($query,$connection) or die(mysql_error()); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); if(@mysql_num_rows($request)) { $row = mysql_fetch_assoc($request); if (sha1($row['salt'] . $_POST['password']) === $row['Password']) { $_SESSION['CLIFE']['AUTH'] = true; $_SESSION['CLIFE']['ID'] = $result['id']; // UPDATE LAST ACTIVITY FOR USER $query = "UPDATE `cysticUsers` SET `LastActivity` = '" . date("Y-m-d") . " " . date("g:i:s") . "' WHERE `id` = '" . mysql_real_escape_string($_SESSION['CLIFE']['ID']) . "' LIMIT 1"; mysql_query($query,$connection); if(!empty($_POST['return'])) { header("Location: " . $_POST['return']); }else{ header("Location: CysticLife-Dashboard.php?id=" . $_SESSION['CLIFE']['ID']); } } }else{ $_SESSION['CLIFE']['AUTH'] = false; $_SESSION['CLIFE']['ID'] = false; } } I've been scouring resources and am stuck on this. I have a deadline to meet that I am behind on. Needless to say I'm pulling my hair out and some help with this would be GREATLY appreciated. Thank you in advance! Hello PhP Freaks forum In the past weeks ive been trying to make a website, where you can register. Everything seems to work except my cherished Change password feature. Everytime you try to change the password, it just resets it to nothing. Here is the code below. <?php if(isset($_SESSION['username'])) { $username = $_SESSION['username']; $lastname = $_SESSION['lastname']; $firstname = $_SESSION['firstname']; $email = $_SESSION['email']; echo " <h4>Options for:</h4> $username <br /> <br /> First name: $firstname <br />Last name: $lastname <br /><br /><h3>Want to change your password:</h3><br /> <form action='?do=option' method='post'> Old password <input type='password' placeholder='Has to be between 5-15 digits' name='password' size='30' value='' /><br /> <br /> New Password<input type='password' placeholder='Has to be between 5-15 digits' name='newpass' size='30' value='' /><br /> <br /> Confirm new password <input type='password' placeholder='Has to be between 5-15 digits' name='passconf' size='30' value='' /><br /> <center></div><input type='submit' value='Submit'/></center></form>"; }else{ echo 'Please login to view your options!'; } $password = $_REQUEST['password']; $pass_conf = $_REQUEST['newpass']; $email = $_REQUEST['passconf']; $connect = mysql_connect("Host", "User", "Password"); if(!$connect){ die(mysql_error()); } //Selecting database $select_db = mysql_select_db("My Database", $connect); if(!$select_db){ die(mysql_error()); } //Find if entered data is correct $result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'"); $row = mysql_fetch_array($result); $id = $row['id']; mysql_query("UPDATE users SET password='$newpass' WHERE username='$user'") ?> And i do know that i dont have a if(Empty($newpass)){ Die(Please fill out the new password) } Or any security on the others, but the problem just seems that it resets the password into nothing Hope i can get this fixed Best Regards William Pfaffe This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=353345.0 <?php
require_once('upper.php'); require_once('database.php'); echo $error_msg=''; if(isset($_POST['submit'])) { $LoginId=mysqli_real_escape_string($dbc,trim($_POST['LoginId'])); $Password1=mysqli_real_escape_string($dbc,trim($_POST['Password1'])); $Password2=mysqli_real_escape_string($dbc,trim($_POST['Password2'])); $Name=mysqli_real_escape_string($dbc,trim($_POST['Name'])); $Age=mysqli_real_escape_string($dbc,trim($_POST['Age'])); $BloodGroup=mysqli_real_escape_string($dbc,trim($_POST['BloodGroup'])); if(!isset($_POST['Sex'])) { echo 'Please enter Sex<br>'; } else{ $Sex= mysqli_real_escape_string($dbc,trim($_POST['Sex'])); } $Qualification=mysqli_real_escape_string($dbc,trim($_POST['Qualification'])); $ContactNumber=mysqli_real_escape_string($dbc,trim($_POST['ContactNumber'])); $Email=mysqli_real_escape_string($dbc,trim($_POST['Email'])); $Address=mysqli_real_escape_string($dbc,trim($_POST['Address'])); $AboutYourself=mysqli_real_escape_string($dbc,trim($_POST['AboutYourself'])); //$countCheck=count($_POST['checkbox']); //echo $countCheck; //$checkbox=$_POST['checkbox']; //$countCheck=count($checkbox); if(empty($LoginId)){echo 'Please enter Login Id';} elseif(empty($Password1)){echo 'Please enter Password';} elseif(empty($Password2)){echo 'Please confirm Password';} elseif($Password1!==$Password2){echo 'Password didn\'t match';} elseif(empty($Name)){echo 'Please enter Name';} elseif(empty($Age)){echo 'Please enter Age';} elseif(!isset($_POST['Sex'])){} elseif(empty($Qualification)){echo 'Please enter Qualification';} elseif(empty($ContactNumber)){echo 'Please enter Contact Number';} elseif(empty($Email)){echo 'Please enter Email';} elseif(empty($Address)){echo 'Please enter Address';} elseif(empty($AboutYourself)){echo 'Please enter About Yourself';} elseif(!isset($_POST['checkbox'])){ echo 'You have to register at least one activity.';} elseif(!isset($_POST['TermsAndConditions'])){ echo 'You have to agree all Terms and Conditions of Elite Brigade.';} else { require_once('database.php'); $query="select * from registration where LoginId='$LoginId'"; $result=mysqli_query($dbc,$query); if(mysqli_num_rows($result)==0) { $checkbox=$_POST['checkbox']; $countCheck=count($_POST['checkbox']); $reg_id=' '; for($i=0;$i<$countCheck;$i++) { $reg_id=$reg_id.$checkbox[$i].','; $query="insert into activity_participation (LoginId,Title,Date) values ('$LoginId','$checkbox[$i]',CURDATE())"; $result=mysqli_query($dbc,$query) or die("Not Connected"); } $query="insert into registration (LoginId,Password,Name,Age,BloodGroup,Sex,Qualification,ContactNumber,Email,Address,AboutYourself,Activity)values ('$LoginId'[B],SHA('$Password1'),[/B]'$Name','$Age','$BloodGroup','$Sex','$Qualification','$ContactNumber','$Email','$Address','$AboutYourself',',$reg_id')"; $result=mysqli_query($dbc,$query) or die("Not Connect"); echo ' Dear '.$Name.'.<br>Your request has been mailed to admin.<br>Your account is waiting for approval<br>'; $from= 'Elite Brigade'; $to='ankitp@rsquareonline.com'; $subject='New User Registration'; $message="Dear admin,\n\nA new user request for registration. Please check it out.\n\nRegards\nMicro"; mail($to,$subject,$message,'From:'.$from); //header('Location: index.php'); // header('Location: Registration.php'); } else { echo 'Dear '.$Name. ', <br> An account already exist with login-id<b> '.$LoginId.'</b> <br>Please try another login-id'; }} } ?> <html> <head> <script src="jquery-latest.js"></script> <script type="text/javascript" src="jquery-validate.js"></script> <style type="text/css"> * { font-family: Verdana; } label.error { color: white; padding-left: .5em; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> <script> $(document).ready(function(){ $("#commentForm").validate(); }); </script> </head> <body> <?php echo $error_msg; ?> <form action='<?php echo $_SERVER['PHP_SELF'];?>' id="commentForm" method='post'> <div class="registration_and_activity"> <table border="0" width="380"> <tr><td colspan="2"> <h3>New User?</h3></td></tr> <tr><td width="120"> <em>*</em>Enter Login id</td><td width="150"><input type='text' name='LoginId' minlength="4" value='<?php if(!empty($LoginId))echo $LoginId;?>' /></td></tr> <tr><td> <em>*</em>Enter Password</td> <td><head> <div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> <SCRIPT language=Javascript> function capLock(e){ kc = e.keyCode?e.keyCode:e.which; sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false); if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)) document.getElementById('divMayus').style.visibility = 'visible'; else document.getElementById('divMayus').style.visibility = 'hidden'; } </SCRIPT> </HEAD> <input onkeypress='return capLock(event)' type='password' name='Password1' value='<?php if(!empty($Password1))echo $Password1;?>' /></td></tr> <tr><td> <em>*</em>Confirm Password</td><td><input type='password' name='Password2' value='<?php if(!empty($Password2))echo $Password2;?>' /></td></tr> <tr><td width="120"> <em>*</em>Enter Name</td> <td><input type='text' name='Name' value='<?php if(!empty($Name))echo $Name;?>' /></td></tr> <tr><td> <em>*</em>Enter Age</td><HEAD> <SCRIPT language=Javascript> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> </HEAD> <td><INPUT onkeypress='return isNumberKey(event)' type='text' name='Age' value='<?php if(!empty($Age))echo $Age;?>'/></td></tr> <tr><td> <em>*</em>Enter Blood</td><td><input type='text' name='BloodGroup' value='<?php if(!empty($BloodGroup))echo $BloodGroup;?>' /></td></tr> <tr><td> <em>*</em>Enter Sex</td><td><input type='radio' name='Sex' style='width:16px; border:0;' 'value='Male' />Male <input type='radio' name='Sex' style='width:16px; border:0;' 'value='Female' />Female</td></tr> <tr><td> <em>*</em>Enter Qualification</td><td><input type='text' name='Qualification' value='<?php if(!empty($Qualification))echo $Qualification;?>' /></td></tr> <tr><td> <em>*</em>Contact Number </td><td><input onkeypress='return isNumberKey(event)'type='text' name='ContactNumber' value='<?php if(!empty($ContactNumber))echo $ContactNumber;?>' /></td></tr> <tr><td> <em>*</em>Enter Email</td><td><input type='text' name='Email'class="email" value='<?php if(!empty($Email))echo $Email;?>' /></td></tr> <tr><td> <em>*</em>Enter Address</td><td><input type='text' name='Address' value='<?php if(!empty($Address))echo $Address;?>' /></td></tr> <tr ><td > <em>*</em>About Yourself </td></tr> <tr><td colspan="2"><textarea rows='10' cols='40' name='AboutYourself' /><?php if(!empty($Address))echo $Address;?></textarea></td></tr> <tr><td> <?php echo" <tr><td colspan='2'><em>*</em><b>Select fields for which you want to register</b></td></tr>"; require_once('database.php'); $query="select * from activity"; $result=mysqli_query($dbc,$query); while($row=mysqli_fetch_array($result)){ $Title=$row['Title']; $ActivityId=$row['ActivityId']; echo "<tr><td>$Title</td>"; echo "<td><input type='checkbox' name='checkbox[]' value='$Title' style='width:14px; text-align:right;'/></td></tr>";//value=$ActivityId tells ActivityId variable extracts with name="checkbox" echo "<br/>"; } echo "<td><em>*</em><input type='checkbox' name='TermsAndConditions' style='width:14px; text-align:right;'/></td><td> I agree all <a href='TermsAndConditions.php'>Terms and conditions </a>of Elite Brigade</td></tr>"; echo "<tr><td colspan='2' align='center'><input type='submit' value='Register' name='submit' style='background:url(./images/button_img2.png) no-repeat 10px 0px; width:100px; padding:3px 0 10px 0; color:#FEFBC4; border:0;'/></td></tr><br>"; echo " </td></tr></table> </div> </form> </body> </html>"; require_once('lower.php'); ?> Hi Friends .... I encrypt user password by SHA('$Password') method but now i want to add "Forget Password Module" for which I need to decrypt it first before tell my user but I don't Know how to decrypt it. Please help me........ Code: [Select] $stick_topic = isset($_POST['stick_topic']) ? '1' : '0'; does this need to be escaped while entering the database or no because the values could only be 1 or 0 ? srry it's just i got hacked so i am trying to do my security #1 using this below is it safe against hackers? Code: [Select] $post_id = intval($_GET['report']); if ($post_id < 1) message($lang_common['Bad request']); query: Code: [Select] $result = $db->query('SELECT subject, forum_id FROM '.$db->prefix.'topics WHERE id='.$topic_id) or error('Unable to fetch topic info', __FILE__, __LINE__, $db->error()); should i escape my $topic_id ? Guys, Having a major headache here. I need to send an enquiry using jquery and php. The user can only send an enquiry if they are logged in - so it's a one click process. On the click (which is an <a> tag) the user's data is retrieved from the database and sent to the company they are enquiring about. When the link is clicked, a jquery popup is shown to notify the user that the enquiry has been sent. This all works. However, currently the enquiry is sent when the page loads and this is what I'm having trouble with. Code: [Select] <a href="#e" onclick="openinfobox('Enquiry Sent', 1)" class="enq"></a>What I want to do is say if the URL contains #e, then send the enquiry, otherwise do nothing. I understand that the # portion of the url cannot be referenced by PHP. How on earth can I run php process to say only run this php process if there is a # in the url? Hi guys, I have been using the same code for years now to include my default page and pull content into my layouts.
I found the code online and its a bit confusing so was just wondering if its still safe to use, and is it all needed nowadays?
or is there a simpler way i could be doing this?
Thanks for any help
<?php if (isset($_GET['nav'])) { if (strpos($_GET['nav'], "/")) { $direc = substr(str_replace('..', '', $_GET['nav']), 0, strpos($_GET['nav'], "/")) . "/"; $file = substr(strrchr($_GET['nav'], "/"), 1); if (file_exists($direc.$file.".php")) { require($direc.$file.".php"); } else { require("error.php"); } } else { if (file_exists(basename($_GET['nav']).".php")) { require(basename($_GET['nav']).".php"); } else { require("error.php"); } } } else { require("links.php"); } ?> Hello all. Just wanted to run this past you guys to see if I am missing anything important. I am making a script that I plan to allow a lot of other people around the web to use, so I want to make sure it's as bullet proof as possible. I am passing two values and grabbing them with a _GET, one is a big number, and the other is only letters and 8 characters long. her's my code so far. Code: [Select] <?php $clan = $_GET['clanid']; // make sure its an INT //if(isint($clan)){ if(ereg("[^0-9]", $clan)){ //im an int. echo ("ERROR Invalid CLANID"); die; } // make sure its a 8 letter only word. $style=$_GET['style']; // cut style down to 8 characters long. $style=substr($style, 0, 8); if(ereg("[^a-zA-Z]+", $style)) { // Contains only letters. echo("ERROR Invalid STYLE NAME"); die; } ?> to my noob php eye's it looks pretty solid, I cant think of any way a malicious user could get past it, but like I said, thought I would run it past you guys first , you can never be to careful. Advice please. I am setting up a new machine here and I can't remember which to download. What information do you need to be aware of to know whether to install 'non thread safe' or 'thread safe'. I did some googling but didn't find anything that was clear. And is 5.3 good to go or should I stick with 5.2. Thanks in advance for your input! I have a button that uses $_POST to send information to another page. The data is in a hidden input so it's not possible for users to change information. I have nothing to check if the data is correct on the other page. Is it still possible for people to change the $_POST data though? Or somehow send false $_POST data to the other page? Is a hash array the same thing as an associative array? My PHP books make no reference to this, yet I have seen the term referred to. Thanks. Are there any PHP hashes that are extremely secure and that CANNOT be reverse-engineered?
I have a section on my website where the url points to www.example.com/some_page#some_element #some_element is used by javascript to load the element in question into the parent element. However i need pagination done on this loaded element. How should i go about it? would it work? obv i cant use www.example.com/some_page#some_element/page/2. Any tips or advice? I am using seo friendly urls so when someone makes a post named "this is a post" the url will point to www.example.com/topic/this_is_a_post But when the user enters a character in their post name that means something in a url(? /) it obviously breaks. How can i make the urls safe from this without str_replace as i want to keep the characters. I have created this login class (In all honesty this is the most commented and well structured class I have ever written, I usualy just use random functions in a functions.php file, which works but this felt good when I finished it ) I just wanted some advice to how safe and whether the way I have done this is 'good practise', or if there is anything I should add to future proof it. This is the class: Code: [Select] <?php /* Author: Craig Dennis File: user_session.class.php Purpose: Flexible user login class that handles logging in, checking a user is logged in, and logging out. NOTE TO USE THIS CLASS YOU MUST ALREADY HAVE ALREADY CONNECTED TO THE DATABASE Include this file at the top of each page you wish to protect include("inc/user_session.class.php"); //(This could be put at the top of a global include file) Use the following code to check the user is logged in: $user_session = new user_session; //(This could be put at the top of a global include file) $user_session->validate_user(); //(This should only be left on the pages you wish to check for user validation) You will want to use the public redirect_if_logged_in() function instead of validate_user() on the login page like this: $user_session->redirect_if_logged_in(); //(This will redirect a user from the current page to the specified landing page) */ class user_session{ // Change these variables below if the table and fields in your database do not match public $t_name = "admins"; public $t_user = "username"; public $t_pass = "password"; public $t_lastlogin = "last_login"; //set $t_lastlogin = NULL if you do not have this field in your database //Change $login_page and $landing_page if your page names are different to this one public $login_page = "login.php"; public $landing_page = "logged_in.php"; //Change $log_in_error_msg if you wish to change the general error message when the user is unable to log in public $log_in_error_msg = "The username or password you have entered is incorrect or does not exist"; //Do not touch anything below unless you know what your doing /* * logged_in_user() * Returns value of the current logged in username */ public function logged_in_user(){ return $_SESSION['user_username']; } /* * log_in() * Takes 2 parameters ($username, $password) * Attempts to log in with the provided credentials, on success, the username and password are saved in the session for future testing */ public function log_in($username, $password){ $username = stripslashes(mysql_real_escape_string($username)); $password = stripslashes(mysql_real_escape_string($password)); $query_login = mysql_query("SELECT * FROM ".$this->t_name." WHERE ".$this->t_user."='$username' AND ".$this->t_pass."='$password'");; $login_accepted = mysql_num_rows($query_login); if($login_accepted == 1){ if($t_lastlogin != NULL){ $query_update_last_login = mysql_query("UPDATE ".$this->t_name." SET ".$this->t_lastlogin."='".time()."' WHERE ".$this->t_user."='$username'"); } $_SESSION['user_username'] = $username; $_SESSION['user_password'] = $password; return true; }else{ return false; } } /* * check_user() * Returns true if the current session credentials can be found in the database, otherwise returns false */ public function check_user(){ $query_login = mysql_query("SELECT * FROM ".$this->t_name." WHERE ".$this->t_user."='".$_SESSION['user_username']."' AND ".$this->t_pass."='".$_SESSION['user_password']."'"); $login_accepted = mysql_num_rows($query_login); if($login_accepted == 1){ return true; }else{ return false; } } /* * validate_user() * Returns true if the current session credentials can be found in the database, otherwise logs user out and returns false */ public function validate_user(){ $login_accepted = $this->check_user(); if($login_accepted == 1){ return true; }else{ $this->log_out(); return false; } } /* * redirect_if_logged_in() * Redirects the user to the specified landing page if the user is logged in */ public function redirect_if_logged_in(){ if($this->check_user()){ header("Location: ".$this->landing_page); } } /* * log_out() * Logs the user out by setting the session credentials to an empty string and redirecting them to the specified login page */ public function log_out(){ $_SESSION['user_username'] = ""; $_SESSION['user_password'] = ""; header("Location: ".$this->login_page); } } ?> Any comments or advice are appreciated. |