PHP - Checking Password Length With If Statement Not Working! (register Script)
This is my registering script:
<?php include('connectvars.php'); $user_email = strip_tags(trim($_POST['email'])); $firstname = strip_tags(trim($_POST['firstname'])); $lastname = strip_tags(trim($_POST['lastname'])); $nickname = strip_tags(trim($_POST['nickname'])); $password = strip_tags($_POST['password']); $repassword = strip_tags($_POST['repassword']); $dob = $_POST['dob']; $find_us_question = strip_tags(trim($_POST['find_us_question'])); if (isset($_POST['submit_signup'])) { if ((empty($user_email)) || (empty($firstname)) || (empty($lastname)) || (empty($nickname)) || (empty($password)) || (empty($dob))) { echo "Please fill out all the fields!"; } else { // check char length of input data if (($nickname > 30) || ($firstname > 30) || ($lastname > 30) || ($user_email > 50)) { echo "Your nickname, first- and/or lastname seem to be too long, please make sure you have them below the maximum allowed length of 30 characters!"; } else { // check password char length if (($password > 25) || ($password < 6)) { echo "Your password must be between 6 and 25 characters!"; } else { // encrypt password $password = sha1($password); $repassword = sha1($repassword); if ($password != $repassword) { echo "Please make sure your passwords are matching!"; } else { $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query = sprintf("INSERT INTO user (firstname, lastname, nickname, password, email, dob, doj) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', now())", mysqli_real_escape_string($dbc, $firstname), mysqli_real_escape_string($dbc, $lastname), mysqli_real_escape_string($dbc, $nickname), mysqli_real_escape_string($dbc, $password), mysqli_real_escape_string($dbc, $user_email), $dob); mysqli_query($dbc, $query); mysqli_close($dbc); echo "You have been successfully registered!"; } } } } } ?> A bunch of nested if statements, the read-ability gets worse after a while, I'm new to programming so I don't know if there's a better more read-able solution. Anyway, every time I try to sign up it's printing out the echo message: "Your password must be between 6 and 25 characters!" Which derives from: // check password char length if (($password > 25) || ($password < 6)) { echo "Your password must be between 6 and 25 characters!"; } else { EVEN if I stay between 6 and 25 characters it's still printing out this error message, let's say I have a password of 8 characters, and I've entered everything else correctly, it's still giving me all the time this error message, and I can not figure out why. Similar Tutorialshere is my change password script (This is being done by the admin)
<?php error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); require 'connect.php'; if(isset($_POST['change'])) { $newp = trim($_POST['npass']); $confp = trim($_POST['cpass']); if(empty(trim($newp))) { echo "<h3><center>You did not enter a new password!</center></h3>"; exit(); } if(empty(trim($confp))) { echo "<h3><center>You must confirm the password!</center></h3>"; exit(); } if($confp !== $newp) { echo "Passwords do not match!, try again."; } else { $sql = "UPDATE $db_name SET cpass='$password' WHERE id=' ".$row['id']." '"; echo " ".$row['username']."\s password has been reset! "; } } ?> <html><title> Change password </title><head><style>#form {border-radius: 20px;font-family: sans-serif; margin-top: 60px; padding: 30px;background-color: #aaa;margin-left: auto; margin-right: auto; width: 500px; clear: both;} #form input {width: 100%; clear: both;} #form input:hover {border: 1px solid #ff0000;}</style></head> <body> <div id="form"> <form action='' method='POST'> <h2><b><center>Change Password</center></b></h2><br> <tr> <td><b>New password:</b><input type="password" name="npass" placeholder="Enter new password" /></td><br><br> <td><b>Confirm password:</b><input type="password" name="cpass" placeholder="Confirm password" /></td><br><br> <td><input type="submit" name="change" value="Change!" /></td> </tr> </form> </div><!-- end of form div --> </body> </html>I'm getting Notice: Undefined variable: row in C:\xampp\htdocs\Login\web_dir\changepassword.php on line 30 Notice: Undefined variable: row in C:\xampp\htdocs\Login\web_dir\changepassword.php on line 32And it say's \s password has been reset!It's saying that the variable row is undefined, it's defined in my edit user / select user page <?php error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); session_start(); require 'connect.php'; echo "<title> Edit a user </title>"; $sql = "SELECT id, username FROM $tbl_name ORDER BY username"; $result = $con->query($sql); while ($row = $result->fetch_assoc()) { echo "<div id='l'><tr><td>{$row['username']}</td> | <td><a href='editUser.php?id={$row['id']}'>Edit User</a> |</td> <td><a href='changepassword.php?id={$row['id']}'>Change Password</a> |</td> <td><a href='banUser.php?id={$row['id']}'>Ban User</a></td><br><br> </tr></div>\n"; } ?>Also it doesn't actually UPDATE the password. Hello, I'm working on a register script, and basically I would like the user to repeat their password. And I would like PHP to compare the to passwords, and if they both match then it continues, whereas if they don't match it calls an error. Here is what I have so far: Form: Consists of 2 text fields - subpass, and subconfirmpass PHP: $field = "subpass"; if(!$subpass == $subconfirmpass){ $form->setError($field, "* Passwords do not match"); } $field is referring to the text fields in where the user inputs their password $form is keeping track of errors in user submitted forms and the form field values that were entered correctly. I would appreciate your help, Thanks I am trying to use the new way of validating the entered email in a register form. Code: [Select] /* REGISTER FORM */ // check if submit button has been clicked if (isset($_POST['submit_signup'])) { // process and assign variables after post submit button has been clicked $user_email = strip_tags(trim($_POST['email'])); $user_email = filter_var($user_email, FILTER_VALIDATE_EMAIL); $nickname = strip_tags(trim($_POST['nickname'])); $password = $_POST['password']; $repassword = $_POST['repassword']; $month = $_REQUEST['month']; $day = $_REQUEST['day']; $year = $_REQUEST['year']; $dob = $year . "-" . $month . "-" . $day; $find_us_question = strip_tags(trim($_POST['find_us_question'])); // connect to database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $check_query = "SELECT * FROM user WHERE nickname = '$nickname'"; $check_connect = mysqli_query($dbc, $check_query) or die(mysqli_error($dbc)); $check_count = mysqli_num_rows($check_connect); // Check if the email exists twice $query_get = "SELECT email FROM user WHERE email = '$user_email'"; $query_run = mysqli_query($dbc, $query_get); $num_rows = mysqli_num_rows($query_run); // check if username is already taken if ($check_count != 0) { echo "Username already exists!"; } elseif ($num_rows != 0) { echo "This email address is already registered in the database, you can not register it twice."; // check if fields are empty } elseif (empty($user_email) || empty($nickname) || empty($password) || empty($day) || empty($month) || empty($year)) { echo "Please fill out all the fields!"; // check char length of input data } elseif (strlen($nickname) > 30 || strlen($user_email) > 50) { echo "Maximum allowed character length for nickname/firstname/lastname are 30 characters!"; // check password char length } elseif (strlen($password) > 25 || strlen($password) < 6) { echo "Your password must be between 6 and 25 characters!"; // check if passwords match with each other } elseif ($password != $repassword) { echo "Please make sure your passwords are matching!"; } else { // encrypt password $password = sha1($password); I would like to implement now an error message stating something along the lines that the entered email address is not valid, how would I have to do the if statement to check the condition? 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? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=347719.0 I am trying to to create an if statement checking the domain name. I need to check the domain with "www" and without the "www". How can I make an OR inside an if statement "||" doesn't seem to work? I have tried this code, but doesn't work: if (($_SERVER['HTTP_HOST'] != 'www.domain.com')||($_SERVER['HTTP_HOST'] != 'domain.com')){ echo "some text here":} I am trying to check to see if a file size is acceptable before an upload but cant seem to get the right result no matter what i do. if i have my if statement below coded like this Code: [Select] if($_FILES["upload"]["size"] < 1024000){ echo'entered if statement<br />'; } else{ echo'entered else statement<br />'; } Then i always am entereing the if statememnt but if i have my if statement like this Code: [Select] if($_FILES["upload"]["size"] > 1024000){ echo'entered if statement<br />'; } else{ echo'entered else statement<br />'; } then i always seem to enter the else staement. I have tried with a VIREITY of differnt size files some from like 2kb to 10mb... i believe somewhere near the > or < is my problem but i dont seem to see it Hi there, I am working on a PHP web form. There is simple textbox where users can enter countries. If the user enters any of the European countries for example Spain, Germany or Italy then the web page must echo ' You entered a European country. The code I am using is: switch ($txtCountry) { case 'Germany' || 'Spain' || 'Belgium' || 'Cyprus' || 'Estonia': echo "You entered a European Country"; break; case 'Japan': echo "You entered a Far Eastern Country"; break; default: echo "Unknown Country"; break; } Now the problem is even if I enter a different country like Japan, it goes to the first Case: i.e. 'You entered a European Country' Whats the best way to use Switch case to check multiple values. Is my Syntax correct or do I need to use single quote of double quote here. Please reply. Thank you! I'm sorry this code is a mess, this is my attempt at a online youtube tutorial http://www.youtube.com/user/phpacademy#p/c/9CC58D1B2A2D83D6/9/cBJZZlLrXGo The script runs with no parse errors but it does not the following: - present error messages when input is incorrect - enter correct input into the database - retain the user input in the form so the user does not need to re enter the information. I would just use another script but this is the 2nd part of a tutorial that will really help me learn so I need this to work . Any help appreciated. 1. 2. <?php 3. include("design/header.php"); 4. require("connect.php"); 5. 6. //register code 7. 8. 9. if(isset($POST['submit'])) 10. { 11. //grab submitted data 12. $firstname = $_POST['firstname']; 13. $lastname = $_POST['lastname']; 14. $username = $_POST['username']; 15. $password = $_POST['password']; 16. $password_repeat = $_POST['password_repeat']; 17. 18. $dob_year = $_POST['dob_year']; 19. $dob_month = $_POST['dob_month']; 20. $dob_day = $_POST['dob_day']; 21. 22. $gender = $_POST['gender']; 23. 24. if ( 25. $firstname&& 26. $lastname&& 27. $username&& 28. $password&& 29. $password_repeat&& 30. $dob_year&& 31. $dob_month&& 32. $dob_day&& 33. $gender 34. ) 35. { 36. 37. //validation 38. if(strlen($firstname)>25 || strlen($lastname)>25 || strlen($username)>25) 39. echo "Firstname, lastname and username must be no more than 25 characters."; 40. 41. 42. else 43. { 44. if (strlen($password)>25 || strlen($password)<6) 45. echo "Password must be between 6 and 25 characters."; 46. 47. else 48. { 49. if (is_numberic($dob_year)&&is_numberic($dob_month)&&is_numberic($dob_day)) 50. { 51. 52. if (strlen($dob_year)>4||strlen($dob_year)>2||strlen($dob_year)>2) 53. echo "Date of birth must be 4 characters, month and must be 2."; 54. else 55. { 56. if ($gender=="Male"||$gender=="Female") 57. { 58. //compare pass 59. if ($password==$password_repeat) 60. { 61. //check dob limits for month and day 62. if ($dob_month>12||$dob_day>31) 63. echo "Date of birth month or day is bigger than expected!"; 64. else{ 65. //check for existing user 66. $query =mysql_query("SELECT * FROM users WHERE username='$username'"); 67. if (mysql_num_rows($query)>=1) 68. echo "That username is already taken."; 69. else { 70. //success!! 71. $dob_db = "$dob_year-$dob_month-$dob_day"; 72. $password_db = md5($password); 73. 74. switch ($gender) 75. { 76. case "Male": 77. $gender_db = "M"; 78. break; 79. case "Female": 80. $gender_db = "F"; 81. break; 82. $register = mysql_query("INSERT INTO user VALUES ('','$firstname','$lastname','$username','$password_db','$dob_db','$gender_db')"); 83. echo "success!"; 84. } 85. } 86. } 87. } 88. else 89. {echo "Passwords must match"; 90. } 91. } 92. else 93. echo "Gender must be Male or Female."; 94. } 95. } 96. else 97. echo "Date of birth must be in number form. For example 1993/05/30"; 98. } 99. } 100. }else{ 101. echo "Please enter your details and click Register!"; 102. } 103. } 104. 105. ?> 106. 107. <p> 108. <form action='register.php' method='POST'> 109. 110. <table width='60%'> 111. <tr> 112. <td width='40%' align='right'> 113. <font size='2' face='arial'>Firstname: 114. </td> 115. <td> 116. <input type='text' value='<?php echo $firstname; ?>' name='firstname' maxlength='25'> 117. </td> 118. </tr> 119. <tr> 120. <td width='40%' align='right'> 121. <font size='2' face='arial'>Lastname: 122. </td> 123. <td> 124. <input type='text' value='<?php echo $lastname; ?>' name='lastname' maxlength='25'> 125. </td> 126. </tr> 127. <tr> 128. <td width='40%' align='right'> 129. <font size='2' face='arial'>Username: 130. </td> 131. <td> 132. <input type='text' value='<?php echo $username; ?>' name='username' maxlength='25'> 133. </td> 134. </tr> 135. <tr> 136. <td width='40%' align='right'> 137. <font size='2' face='arial'>Password: 138. </td> 139. <td> 140. <input type='password' name='password' maxlength='25'> 141. </td> 142. </tr> 143. <tr> 144. <td width='40%' align='right'> 145. <font size='2' face='arial'>Repeat Password: 146. </td> 147. <td> 148. <input type='password' name='password_repeat' maxlength='25'> 149. </td> 150. </tr> 151. <tr> 152. <td width='40%' align='right'> 153. <font size='2' face='arial'>Date of birth: 154. </td> 155. <td> 156. <input type='text' name='dob_year' maxlength='4' size='3' value='<?php if ($dob_year) echo $dob_year; else echo "YYYY";?>'> /<input type='text' name='dob_month' maxlength='2' size='1' value='<?php if ($dob_month) echo $dob_month; else echo "MM";?>'> / <input type='text' name='dob_day' maxlength='2' size='1' value='<?php if ($dob_day) echo $dob_day; else echo "DD";?>'> 157. </td> 158. </tr> 159. <tr> 160. <td width='40%' align='right'> 161. <font size='2' face='arial'>Gender: 162. </td> 163. <td> 164. <select name='gender'> 165. <option>Female</option> 166. <option>Male</option> 167. </select> 168. </td> 169. </tr> 170. 171. </table> 172. <div align='right'><input type='submit' name='submit' value='Register'> 173. </form> 174. 175. 176. <?php 177. include("design/footer.php"); 178. 179. ?> 180. Hey, so this is my register script
<?php error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', 1); require 'connect.php'; echo "<title> Register </title>"; if(isset($_POST['register'])) { $username = trim($_POST['username']); $username = mysqli_real_escape_string($con, $_POST['username']); $password = mysqli_real_escape_string($con, $_POST['password']); $password = hash('sha512', $_POST['password']); if(!$_POST['username'] OR !$_POST['password']) { die("You must enter a username and password!"); } $stmt = $con->prepare("INSERT INTO usrs_usr (username, password) VALUES (?, ?)"); $stmt->bind_param("ss", $username, $password); $stmt->get_result(); var_dump($stmt); $stmt->execute(); echo "New user has been created successfully"; $stmt->close(); $conn->close(); } ?>Now the problem is i have done a variable dump which outputs nothing, and the only error i am getting is Fatal error: Call to a member function bind_param() on a non-object my registration script for my website, does sent activation link to newly registered user's for some reason. can some one please help me, i have stay up all-night just to figure out the problem. any help appreciated <?php $from = ""; // Initialize the email from variable // This code runs only if the username is posted if (isset ($_POST['username'])){ $username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']); // filter everything but letters and numbers $gender = preg_replace('#[^a-z]#i', '', $_POST['gender']); // filter everything but lowercase letters $b_m = preg_replace('#[^0-9]#i', '', $_POST['birth_month']); // filter everything but numbers $b_d = preg_replace('#[^0-9]#i', '', $_POST['birth_day']); // filter everything but numbers $b_y = preg_replace('#[^0-9]#i', '', $_POST['birth_year']); // filter everything but numbers $email1 = $_POST['email1']; $email2 = $_POST['email2']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; $humancheck = $_POST['humancheck']; $email1 = stripslashes($email1); $pass1 = stripslashes($pass1); $email2 = stripslashes($email2); $pass2 = stripslashes($pass2); $email1 = strip_tags($email1); $pass1 = strip_tags($pass1); $email2 = strip_tags($email2); $pass2 = strip_tags($pass2); // Connect to database include_once "scripts/connect_to_mysql.php"; $emailCHecker = mysql_real_escape_string($email1); $emailCHecker = str_replace("`", "", $emailCHecker); // Database duplicate username check setup for use below in the error handling if else conditionals $sql_uname_check = mysql_query("SELECT username FROM myMembers WHERE username='$username'"); $uname_check = mysql_num_rows($sql_uname_check); // Database duplicate e-mail check setup for use below in the error handling if else conditionals $sql_email_check = mysql_query("SELECT email FROM myMembers WHERE email='$emailCHecker'"); $email_check = mysql_num_rows($sql_email_check); // Error handling for missing data if ((!$username) || (!$gender) || (!$b_m) || (!$b_d) || (!$b_y) || (!$email1) || (!$email2) || (!$pass1) || (!$pass2)) { $errorMsg = 'ERROR: You did not submit the following required information:<br /><br />'; if(!$username){ $errorMsg .= ' * User Name<br />'; } if(!$gender){ $errorMsg .= ' * Gender: Confirm your sex.<br />'; } if(!$b_m){ $errorMsg .= ' * Birth Month<br />'; } if(!$b_d){ $errorMsg .= ' * Birth Day<br />'; } if(!$b_y){ $errorMsg .= ' * Birth year<br />'; } if(!$email1){ $errorMsg .= ' * Email Address<br />'; } if(!$email2){ $errorMsg .= ' * Confirm Email Address<br />'; } if(!$pass1){ $errorMsg .= ' * Login Password<br />'; } if(!$pass2){ $errorMsg .= ' * Confirm Login Password<br />'; } } else if ($email1 != $email2) { $errorMsg = 'ERROR: Your Email fields below do not match<br />'; } else if ($pass1 != $pass2) { $errorMsg = 'ERROR: Your Password fields below do not match<br />'; } else if ($humancheck != "") { $errorMsg = 'ERROR: The Human Check field must be cleared to be sure you are human<br />'; } else if (strlen($username) < 4) { $errorMsg = "<u>ERROR:</u><br />Your User Name is too short. 4 - 20 characters please.<br />"; } else if (strlen($username) > 20) { $errorMsg = "<u>ERROR:</u><br />Your User Name is too long. 4 - 20 characters please.<br />"; } else if ($uname_check > 0){ $errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside of our system. Please try another.<br />"; } else if ($email_check > 0){ $errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside of our system. Please use another.<br />"; } else { // Error handling is ended, process the data and add member to database //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $email1 = mysql_real_escape_string($email1); $pass1 = mysql_real_escape_string($pass1); // Add MD5 Hash to the password variable $db_password = md5($pass1); // Convert Birthday to a DATE field type format(YYYY-MM-DD) out of the month, day, and year supplied $full_birthday = "$b_y-$b_m-$b_d"; // GET USER IP ADDRESS $ipaddress = getenv('REMOTE_ADDR'); // Add user info into the database table for the main site table $sql = mysql_query("INSERT INTO myMembers (username, gender, birthday, email, password, ipaddress, sign_up_date) VALUES('$username','$gender','$full_birthday','$email1','$db_password', '$ipaddress', now())") or die (mysql_error()); $id = mysql_insert_id(); // Create directory(folder) to hold each user's files(pics, MP3s, etc.) mkdir("members/$id", 0755); //!!!!!!!!!!!!!!!!!!!!!!!!! Email User the activation link !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $to = "$email1"; $from = $dyn_www; // $adminEmail is established in [ scripts/connect_to_mysql.php ] $subject = 'Complete Your ' . $dyn_www . ' Registration'; //Begin HTML Email Message $message = "Hi $username, Complete this step to activate your login identity at $dyn_www Click the line below to activate when ready http://$dyn_www/activation.php?id=$id&sequence=$db_password If the URL above is not an active link, please copy and paste it into your browser address bar Login after successful activation using your: E-mail Address: $email1 Password: $pass1 See you on the site!"; //end of message $headers = "From: $from\r\n"; $headers .= "Content-type: text\r\n"; mail($to, $from, $subject, $message, $headers); $msgToUser = "<h2>One Last Step - Activate through Email</h2><h4>$username, there is one last step to verify your email identity:</h4><br /> In a moment you will be sent an Activation link to your email address.<br /><br /> <br /> <strong><font color=\"#990000\">VERY IMPORTANT:</font></strong> If you check your email with your host providers default email application, there may be issues with seeing the email contents. If this happens to you and you cannot read the message to activate, download the file and open using a text editor.<br /><br /> "; include_once 'msgToUser.php'; exit(); } // Close else after duplication checks } else { // if the form is not posted with variables, place default empty variables so no warnings or errors show $errorMsg = ""; $username = ""; $gender = ""; $b_m = ""; $b_d = ""; $b_y = ""; $email1 = ""; $email2 = ""; $pass1 = ""; $pass2 = ""; } ?> Hey I would just like to release a simple login/register script that will work just fine and has some nice systems in it. The Login. (I will post the code then below tell you what you need to do to get it to work with MYSQL DATABASE) Create a file and call it login with the suffix .php so if you have file extensions showing on your computer it will look like "login.php" then put this code inside of it. Code: [Select] <?php session_start(); ?> <?php function mysql_prep($value) { $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysql_real_escape_string"); // i.e PHP >= v4.3.0 if($new_enough_php){ // PHP v4.3.0 or higher if ($magic_quotes_active){ $value = stripslashes($value); } $value = mysql_real_escape_string($value); }else{ //Before PHP v4.3.0 //if magic quotes aren't already on then add slahes manually if(!$magic_quotes_active){ $value = addslashes($value); } // if magic quotes are active then the slashes already exist } return $value; } function redirect_to($location = NULL){ if($location != NULL){ header("Location: {$location}"); exit; } } define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS","yourpassword"); define("DB_NAME","yourdatabasename"); $connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS); if(!$connection){ die("Database Connection Failed: " . mysql_error()); } $db_select = mysql_select_db("bcooperz", $connection); if(!$db_select){ die("Connection to database failed: " . mysql_error()); } ?> <?php if(isset($_SESSION['user_id'])){ redirect_to("staff.php"); } ?> <?php if (isset($_POST['submit'])){ $errors = array(); // Perform validations on the form $required_fields = array('username', 'password'); foreach($required_fields as $fieldname){ if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])){ $errors[] = $fieldname; } } $field_with_lengths = array('username' => 30, 'password' => 30); foreach($field_with_lengths as $fieldname => $maxlength) { if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; } } $username = trim(mysql_prep($_POST['username'])); $password = trim(mysql_prep($_POST['password'])); $hashed_password = sha1($password); if (empty($errors)){ // Checks database to see if username and password exist their $query = "SELECT id, username FROM users WHERE username='$username' AND hashed_password='$hashed_password' LIMIT 1"; $result_set = mysql_query($query, $connection); if(!$result_set){ die("Database Query Failed: " . mysql_error()); } if (mysql_num_rows($result_set) == 1) { // The Username and Password have been found in the database and the user is verified // Only 1 Match $found_user = mysql_fetch_array($result_set); $_SESSION['user_id'] = $found_user['id']; $_SESSION['username'] = $found_user['username']; redirect_to("staff.php"); }else{ // Username and Password was not found in the database. $message = "Username/Password Combination Incorrect.<br/>Please make sure your caps lock key is off and try again."; echo $message; } }else{ $count = count($errors); if($count == 1){ echo "Their Was {$count} Error In The Form" . "<br />"; print_r(implode(", ", $errors)); }else{ echo "Their Was {$count} Error's In The Form" . "<br />"; echo "<b>"; print_r(implode(", ", $errors)); echo "</b>"; } } }else{ // The Form Has Not Been Submitted if(isset($_GET['logout']) && $_GET['logout'] == 1){ echo "You Are Now Logged Out"; } if(isset($_GET['nowlogged']) && $_GET['nowlogged'] == 1){ echo "You Need to Login to reach this page."; } $username = ""; $password = ""; } ?> <html> <head> <title>Register</title> </head> <body> <form action="login.php" method="post"> Username : <input type="text" name="username" maxlength="30" value="<?php echo htmlentities($username); ?>" /><br /> Password : <input type="password" name="password" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br /><br /> <input type="submit" name="submit" value="Login" /><br /> </form> <p>Haven't got an account? register <a href="register.php">here!</a></p> </body> </html> Now once you have a file called "login.php" with the above code inside of it you will need to goto your mysql database and create a database with a table that has 3 fields in the following format. - id - int(11) - Auto increment - username - varchar(50) - hashed_password - varchar(40) Now search for this in the login.php code Code: [Select] define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS","yourpassword"); define("DB_NAME","yourdatabasename"); And This: Code: [Select] $db_select = mysql_select_db("bcooperz", $connection); And change these to your settings. Once you have done all this create a new file called register with the suffix .php as well so if you have file extensions turned on it will look like "register.php" And add this code inside it: Code: [Select] <?php function mysql_prep($value) { $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysql_real_escape_string"); // i.e PHP >= v4.3.0 if($new_enough_php){ // PHP v4.3.0 or higher if ($magic_quotes_active){ $value = stripslashes($value); } $value = mysql_real_escape_string($value); }else{ //Before PHP v4.3.0 //if magic quotes aren't already on then add slahes manually if(!$magic_quotes_active){ $value = addslashes($value); } // if magic quotes are active then the slashes already exist } return $value; } function redirect_to($location = NULL){ if($location != NULL){ header("Location: {$location}"); exit; } } ?> <?php define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS","maxcooper"); define("DB_NAME","bcooperz"); $connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS); if(!$connection){ die("Database Connection Failed: " . mysql_error()); } $db_select = mysql_select_db("bcooperz", $connection); if(!$db_select){ die("Connection to database failed: " . mysql_error()); } ?> <?php if(isset($_POST['submit'])){ $username = trim(mysql_prep($_POST['username'])); $password = trim(mysql_prep($_POST['password'])); $hashed_password = sha1($password); $confirmpass=$_POST['confirmpass']; $query2 = "SELECT * FROM users WHERE username='$username'"; $result2 = mysql_query($query2); $counted=mysql_num_rows($result2); $errors = array(); // Perform validations on the form $required_fields = array('username', 'password', 'confirmpass'); foreach($required_fields as $fieldname){ if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])){ $errors[] = $fieldname; } } if($confirmpass!=$_POST['password']){ $errors[] = "passdifference"; } if($counted > 0){ $errors[] = "User Already Created"; } $field_with_lengths = array('username' => 30, 'password' => 30); foreach($field_with_lengths as $fieldname => $maxlength) { if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; } } /* The Form Has Been Submitted */ if (empty($errors)){ $query = "INSERT INTO users (username,hashed_password) VALUES ('{$username}', '{$hashed_password}')"; $result = mysql_query($query, $connection); if($result){ echo "User Successfully Created"; }else{ echo "The User Could Not Be Created" . "<br />"; echo mysql_error(); } }else{ $count = count($errors); if($count == 1){ echo "Their Was {$count} Error In The Form" . "<br />"; print_r(implode(", ", $errors)); }else{ echo "Their Was {$count} Error's In The Form" . "<br />"; echo "<b>"; print_r(implode(", ", $errors)); echo "</b>"; } } }else{ /* The Form Has Not Yet Been Submitted */ $username = ""; $password = ""; } ?> <html> <head> <title>Register</title> </head> <body> <form action="register.php" method="post"> Username : <input type="text" name="username" maxlength="30" value="<?php echo htmlentities($username); ?>" /><br /> Password : <input type="password" name="password" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br /> Confirm Password: <input type="password" name="confirmpass" maxlength="30" value="" /><br /><br /> <input type="submit" name="submit" value="Register" /><br /> </form> <p>Already have a account? login here <a href="login.php">here!</a></p> </body> </html> Once you have done that and you have a file called "register.php" you will need to perform the final step which will be changing the database details once again on the second file ("register.php"). Thanks, Bcooperz. Please tell me if this works The error is on line 101. Help please. Code: [Select] <?php //begin register script $submit = $_POST['submit']; //form data $username= strip_tags ($_POST['username']); $email= strip_tags($_POST['email']); $pwd= strip_tags($_POST['pwd']); $confirmpwd= strip_tags($_POST['confirmpwd']); $date = date("Y-m-d"); if ($submit) { //check for required form data if($username&&$pwd&&$confirmpwd&&$email) { //encrypt password $pwd = md5($pwd); $confirmpwd =md5($pwd); //check if passwords match if ($pwd==$confirmpwd) { //check length of username if (strlen($username)>25||strlen($username)>25) { echo "length of username is too long"; } else { //check password length if(strlen($pwd)>25||strlen($pwd)<6) { echo"password must be between 6 and 25 characters"; } else { //register the user } else echo "your passwords do not match"; } else echo "please fill in all fields"; } ?> Hi, I have taken the step of writing my site in MySQLi instead of MYSQL as advised. However, I had a script that I got off the internet, the original file works great and registers the user to the database. However the edited version of the script, where I have added more information such as the users address etc, no longer works. I have compared the two files and can't seem to find the problem. When the script is run, it skips all the registration part and jumps to the last error in the script saying 'You Could Not Be Registered Because Of Missing Data.'. All the variables match the column names in the database.
Here is the original working script
<?php error_reporting(E_ALL); ini_set('display_errors', '1'); // some error checking /* if($_POST['reg']){ echo "form submitted"; }else{ echo "form not submitted"; } */ if( isset( $_POST['user'] ) && isset( $_POST['pass'] ) && isset( $_POST['email'] ) ){ // echo $_POST['user']." - ".$_POST['pass']." - ".$_POST['email']; if( strlen( $_POST['user'] ) < 5 ) { include('header.inc'); echo "Username Must Be 5 or More Characters."; include('footer.inc'); } elseif( strlen( $_POST['pass'] ) < 5 ) { include('header.inc'); echo "Password Must Be 5 or More Characters."; include('footer.inc'); } elseif( $_POST['pass'] == $_POST['user'] ) { include('header.inc'); echo "Username And Password Can Not Be The Same."; include('footer.inc'); } elseif( $_POST['email'] == "" ) { //More secure to use a regular expression to check that the user is entering a valid email // versus just checking to see if the field is empty include('header.inc'); echo "Email must be valid."; include('footer.inc'); } else { require( 'database.php' ); $username = mysqli_real_escape_string($con, $_POST['user']); //Remove md5() function if not using encryption i.e. $password = $_POST['pass']; $password = mysqli_real_escape_string($con, md5( $_POST['pass'])); $email = mysqli_real_escape_string($con, $_POST['email'] ); $sqlCheckForDuplicate = "SELECT username FROM user WHERE username = '". $username ."'"; //echo "$sqlCheckForDuplicate<br/>"; $result = mysqli_query($con, $sqlCheckForDuplicate); if(mysqli_num_rows($result) == 0){ //echo "No Duplicates<br/>"; $sqlRegUser = "INSERT INTO user( username, password, email ) VALUES ( '". $username ."', '". $password ."', '". $email."' )"; //echo "$sqlRegUser<br/>"; if( !mysqli_query($con, $sqlRegUser ) ) { include('header.inc'); echo "You Could Not Register Because Of An Unexpected Error."; include('footer.inc'); } else { /* Note: When using the header function, you cannot send output to the browser * before the header function is called. IF you want to echo a message to the * user before going back to your login page then you should use the HTML * Meta Refresh tag. */ //echo "You Are Registered And Can Now Login"; //echo " $username"; //this is for error checking header ('location: login.php'); // if using echo then use meta refresh /* *?> *<meta http-equiv="refresh" content="2;url= login.php/"> *<? */ } mysqli_free_result($result); } else { include('header.inc'); echo "The Username You Have Chosen Is Already Being Used By Another User. Please Try Another One."; //echo " $username;" //this is for error checking include('footer.inc'); } /* close connection */ mysqli_close($con); } } else { include('header.inc'); echo "You Could Not Be Registered Because Of Missing Data."; include('footer.inc'); } ?>and here is my version <?php error_reporting(E_ALL); ini_set('display_errors', '1'); if( isset( $_POST['user'] ) && isset( $_POST['pass'] ) && isset( $_POST['pass_again'] ) && isset( $_POST['firstname'] ) && isset( $_POST['lastname'] ) && isset( $_POST['email'] ) && isset( $_POST['email_again'] ) && isset( $_POST['address1'] ) && isset( $_POST['address2'] ) && isset( $_POST['town'] ) && isset( $_POST['county'] ) && isset( $_POST['postcode'] ) && isset( $_POST['business'] ) && isset( $_POST['vat_registered'] ) && isset( $_POST['vat_number'] )) { if( strlen( $_POST['user'] ) < 5 ) { include('includes/overall/header.php'); echo "Username Must Be 5 or More Characters."; include('includes/overall/footer.php'); } elseif( strlen( $_POST['pass'] ) < 5 ) { include('includes/overall/header.php'); echo "Password Must Be 5 or More Characters."; include('includes/overall/footer.php'); } elseif( $_POST['pass'] == $_POST['user'] ) { include('includes/overall/header.php'); echo "Username And Password Can Not Be The Same."; include('includes/overall/footer.php'); } elseif( $_POST['pass_again'] == "" ) { include('includes/overall/header.php'); echo "Passwords must match"; include('includes/overall/footer.php'); } // CREATE BETTER EMAIL CHECK elseif( $_POST['email'] == "" ) { include('includes/overall/header.php'); echo "Email must be valid."; include('includes/overall/footer.php'); } elseif( $_POST['email_again'] == "" ) { include('includes/overall/header.php'); echo "Emails must match."; include('includes/overall/footer.php'); } elseif( $_POST['address_1'] == "" ) { include('includes/overall/header.php'); echo "Address cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['address_2'] == "" ) { include('includes/overall/header.php'); echo "Address cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['town'] == "" ) { include('includes/overall/header.php'); echo "Town cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['county'] == "" ) { include('includes/overall/header.php'); echo "County cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['postcode'] == "" ) { include('includes/overall/header.php'); echo "Postcode cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['business'] == "" ) { include('includes/overall/header.php'); echo "Business cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['vat_registered'] == "" ) { include('includes/overall/header.php'); echo "VAT Registered cannot be empty"; include('includes/overall/footer.php'); } elseif( $_POST['vat_number'] == "" ) { include('includes/overall/header.php'); echo "VAT number cannot be empty, please enter N/A if not VAT registered."; include('includes/overall/footer.php'); } else { require( 'database.php' ); $username = mysqli_real_escape_string($con, $_POST['user']); //Remove md5() function if not using encryption i.e. $password = $_POST['pass']; $password = mysqli_real_escape_string($con, md5( $_POST['pass'])); $password_again = mysqli_real_escape_string($con, md5( $_POST['pass_again'])); $firstname = mysqli_real_escape_string($con, $_POST['firstname']); $lastname = mysqli_real_escape_string($con, $_POST['lastname']); $email = mysqli_real_escape_string($con, $_POST['email'] ); $email_again = mysqli_real_escape_string($con, $_POST['email_again']); $address_1 = mysqli_real_escape_string($con, $_POST['address_1']); $address_2 = mysqli_real_escape_string($con, $_POST['address_2']); $town = mysqli_real_escape_string($con, $_POST['town']); $county = mysqli_real_escape_string($con, $_POST['county']); $postcode = mysqli_real_escape_string($con, $_POST['postcode']); $business = mysqli_real_escape_string($con, $_POST['business']); $vat_registered = mysqli_real_escape_string($con, $_POST['vat_registered']); $vat_number = mysqli_real_escape_string($con, $_POST['vat_number']); $sqlCheckForDuplicate = "SELECT username FROM user WHERE username = '". $username ."'"; //echo "$sqlCheckForDuplicate<br/>"; $result = mysqli_query($con, $sqlCheckForDuplicate); if(mysqli_num_rows($result) == 0){ //echo "No Duplicates<br/>"; $sqlRegUser = "INSERT INTO user( username, password, password_again, firstname, lastname, email, email_again, address_1, address_2, town, county, postcode, business, vat_registered, vat_number ) VALUES ( '". $username ."', '". $password ."', '". $password_again ."', '". $firstname ."', '". $lastname ."', '". $email ."', '". $email_again ."', '". $address_1 ."', '". $address_2 ."', '". $town ."', '". $county ."', '". $postcode ."', '". $business ."', '". $vat_registered ."', '". $vat_number."' )"; //echo "$sqlRegUser<br/>"; if( !mysqli_query($con, $sqlRegUser ) ) { include('includes/overall/header.php'); echo "You Could Not Register Because Of An Unexpected Error."; include('includes/overall/footer.php'); } else { header ('location: login.php'); } mysqli_free_result($result); } else { include('includes/overall/header.php'); echo "The Username You Have Chosen Is Already Being Used By Another User. Please Try Another One."; //echo " $username;" //this is for error checking include('includes/overall/footer.php'); } /* close connection */ mysqli_close($con); } } else { include('includes/overall/header.php'); echo "You Could Not Be Registered Because Of Missing Data."; include('includes/overall/footer.php'); } ?> Error reporting is switched on, I just cant see the problem. Any help is much appreciated :) here is my code: Code: [Select] function registerUser() { mysql_connect('localhost', 'user', 'password', 'table'); $rsPostCode = $_POST['rsPostCode']; $rsGender = $_POST['rsGender']; $rsUser = $_POST['rsUser']; $rsPass = $_POST['rsPass']; $rsEmail = $_POST['rsEmail']; $rsMobile = $_POST['rsMobile']; $rsAge = $_POST['rsAge']; $sql = "INSERT INTO members_copy (rsPostCode, rsGender, rsUser, rsPass, rsEmail, rsMobile, rsAge) VALUES ($rsPostCode, $rsGender, $rsUser, $rsPass, $rsEmail, $rsMobile, $rsAge);"; //echo $sql; mysql_query($sql); } When I write out my SQL this is the output: INSERT INTO members_copy (rsPostCode, rsGender, rsUser, rsPass, rsEmail, rsMobile, rsAge) VALUES (BN11, Male, jarv, mypassword, john@email.com, 07998989999, 08/11/1978); here is my register page: http://www.retroandvintage.co.uk/register.php This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=350611.0 I'm having issues with the following: Code: [Select] <?php session_start(); $_SESSION['username']=$_POST['username']; $_SESSION['password']=$_POST['password']; if($_SESSION['username']=="username" && $_SESSION['password']=="password"){ if($_GET['product']=="add"){ $content.=' <p><label>Product Name:</label> <input type="text" name="product_name" size="30" /> <label>Product Price:</label> <input type="text" name="product_price" size="5" /> </p> <p><label>Product Category:</label> <input type="text" name="product_category" size="30" /></p> <p><label>Product Link:</label> <input type="text" name="product_link" size="30" /></p> <p><label>Product Image:</label> <input type="text" name="product_image" size="30" /></p> <p><label>Product Tag:</label> <input type="text" name="product_tag" size="30" /></p> <p><label>Product Keywords:</label> <input type="text" name="keyword" size="30" /></p> <p><label>Product Features:</label><br /> <textarea name="product_features" rows="10" cols="60"></textarea> </p> <p><label>Product Pros:</label><br /> <textarea name="product_pros" rows="5" cols="30"></textarea> </p> <p><label>Product Cons:</label><br /> <textarea name="product_cons" rows="5" cols="30"></textarea> </p> <p><label>Product Description:</label><br /> <textarea name="product_description" rows="10" cols="60"></textarea> </p> <p><label>Product Notes:</label><br /> <textarea name="product_notes" rows="5" cols="30"></textarea> </p> '; $logout='<div><a href="./acp_admincp.php?log-out">Log-Out</a></div>'; } elseif($_GET['product']=="view"){ } else{ $content.=' <a href="./admincp.php?product=add">Add New Product</a> <br /> <a href="./admincp.php?product=view">View Products</a> '; } } elseif(isset($_GET['log-out'])){ session_start(); session_unset(); session_destroy(); header("Location: ./admincp.php"); } else{ $content=' <form action="./admincp.php" method="post"> <p><label>Username:</label> <input type="text" name="username" size="30" />'; $content.='</p> <p><label>Password:</label> <input type="password" name="password" /></p>'; $content.='<p><input type="submit" value="Submit" name="Submit" /></p> </form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <base href="http://ghosthuntersportal.com/" /> <title>Ghost Hunter's Portal - Admin Control Panel</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="verify-v1" content="" /> <meta name="keywords" content="ghost, hunters, hunter, ghosts, spirit, spirits, paranormal, investigation, investigator, investigators, k2, emf, meter, kii" /> <meta name="description" content="Ghost Hunters Potal. Parnormal research equipment store." /> <meta name="author" content="Andrew McCarrick" /> <meta name="robots" content="index, follow" <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <img src="./logo.png" alt="Ghost Hunter's Portal Admin Control Panel" /> <br /> <div style="color: #AA44AA; font-size: 26px; margin-top: -30px; margin-left: 125px;">Admin Control Panel</div> <?php echo $logout; echo $content; ?> </body> </html> I can log-in, and get to the page with the two links on it. However, once I click one of the links it falls back to the log-in page, and it ends up being a never ending loop. It's doing this: Log-In --> Page with links ---> Log-In page again Should be doing this: Log-In --> Page with links --> Add Product page or View Products page I can never get into the the actual sub page. Just to be clear, the address bar actually shows product=add or product=view, but it still shows the log-in page. Hi friends I have following code Code: [Select] function UseOfSSL($domain_name) { $site = ($domain_name); $port = 443; $fp = fsockopen($site,$port,$errno,$errstr,10); if(!$fp) { echo "Not Installed"; } else{ echo "Yes, it is installed"; fclose($fp); } } If domain name from $domain_name has installed SSL, it will show it is installed else not installed. Problem is that I tried this with both types of sites, those who are using SSL and those who are not and always, it says Yes, it is installed. 443 is used because https uses port 443 What is the cause ? I coded small funny script I tested it in three hosting ww.rufaa.net dallawat.com/new ibuj.org but I don't know why in the first link, my script seem slow not like the other second and third links Hey I'm trying to check a row in my database to see if its empty but this isnt working $usercheck = mysql_query("SELECT pet FROM users where name='$user'"); $returned_rows = mysql_num_rows($usercheck); if ($returned_rows == 0){ // do stuff if no pet }else{ echo 'There was ' . $returned_rows . ' records found.'; } The problem is its not checking the row pet its just checking to see if anything exists my database has id name pet 1 joe <empty> its just seeing joe and echoing "there was 1 record found" instead of seeing that the row pet is empty. thanks for the help |