PHP - User Registration Code
This Works But for Some reason when you Register an Account and try to login it says "Incorrect Username/Password" It is also Allowing Multiple Accounts to be Created Under the Same Username and Password:
DB.php <?php session_start(); mysql_connect("localhost", "USERNAME", "PASSWORD"); mysql_select_db("DATABASE_USER"); function user_login ($username, $password) { //take the username and prevent SQL injections $username = mysql_real_escape_string($username); //begin the query $sql = mysql_query("SELECT * FROM usersystem WHERE username = 'username' AND password = 'password' LIMIT 1"); //check to see how many rows were returned $rows = mysql_num_rows($sql); if ($rows<=0 ) { echo "Incorrect username/password"; } else { //have them logged in $_SESSION['sername'] = $username; } } ?> Register.php <?php include("db.php"); if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email'])) { //Prevent SQL injections $username = mysql_real_escape_string($_POST['username']); $email = mysql_real_escape_string($_POST['email']); //Get MD5 hash of password $password = md5($_POST['password']); //Check to see if username exists $sql = mysql_query("SELECT username FROM usersystem WHERE username = 'username'"); if(mysql_num_rows($sql) > 0) { die ("Username taken."); } mysql_query("INSERT INTO usersystem (username, password, email) VALUES ( '$username', '$password', '$email')") or die (mysql_error()); echo "Account created."; } ?> <form action="register.php" method="post"> Username: <input name="username" type="text" /><br> Password: <input type="password" name="password" /><br> Email: <input name="email" type="text" /><br> <input type="submit" value="Submit" /> </form> Login.php <?php include("db.php"); if (isset($_POST['username']) && isset($_POST['password'])) { user_login($_POST['username'], $_POST['password']); } ?> <form action="login.php" method="post"> Username: <input name="username" type="text" /><br> Password: <input type="password" name="password" /><br> <button type="submit">Submit</button><br> </form> Could Anyone Help Please? Similar TutorialsNew to php and starting to feel way in over my head. Please help, point me in the right direction here. How do i create a new folder with a index.html like (www.mydomain.com/NEWUSER/index.html) when a user registers for my site and have it do live check for AVAILABILITY? I want to give my users a unique url for there profile. how then do i automate the creation of x.com/newuser/index.html and write it with the users input from my database at the same time? Im trying to build mysql php user registration. For some reason i cannot insert values into my database. Code: [Select] <?php $submit = $_POST['submit']; $fullname = strip_tags($_POST['fullname']); $username = strip_tags($_POST['username']); $password = strip_tags($_POST['password']); // Connect the database $connection = mysql_connect("bla", "bla", "bla") or die ("Could not connect"); mysql_select_db("my_db", $connection); // mysql query $query = "INSERT INTO users VALUES (''. 'fullname', 'username', 'password')"; mysql_query($query); echo "You have successfully registered"; ?> Any help spotting the error would be appreciated! Hi Can anyone help with this problem it seems very simple, I am not an experienced PHP coder but keen to progress. I am trying to create a User Registration project but have a problem. every time I try to login using mysqli_fetch_assoc it drops through to my error Invalid Email /Password it seems that the mysqli code is not working correctly but I do not understand this function enough can anyone help. I have attached the coding if this helps. This is the function
function Login_Attempt($Email,$Password){
This is the code I am using Login.php
<?php require_once("Include/Session.php"); ?>
<br><input type="Submit" Name="Submit" value="Login"><br> Hope this Helps Ossieboy
I'm trying to teach myself how to use functions and includes in my scripts. As an exercise I am trying to create a registration system that I can re-use on other future projects. I have my main register.php page as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Register</title> </head> <body> <?php ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); error_reporting(E_ALL); // Check to see if query string is set, if not pass empty array to function. if((!isset($_GET['success'])) && (!isset($_GET['active'])) && (!isset($_GET['valid']))) { include ('registerform.php'); $invalidcode = array(); regform($invalidcode); } //If success is set, use value to determine response if(isset($_GET['success'])) { if($_GET['success'] == "false") { echo "There has been an error with your registration. You will be redirected to the registration page in 5 SECONDS."; echo "<meta http-equiv=refresh content =\"5; URL=index.php\">"; } if($_GET['success'] == "true") { echo "Thanks for registering. An activation email has been sent to your registered email address.<br />"; echo "Please check you email and follow the activation link contained within it."; } } //if active is set, determine response (note: code to be added here in future) if(isset($_GET['active'])) { if($_GET['active'] == "true") { echo "Thank you for activating this account.<br />"; echo "You may now return to the home page and login!"; } } //if valid is set there was a problem with the form validation. //get valid from query string, convert back to an array and pass array to the form display script if(isset($_GET['valid'])) { $invalidcode = $_GET['valid']; $invalidcode = unserialize(urldecode($invalidcode)); include ('registerform.php'); regform($invalidcode); } ?> </body> </html> When the page loads it first checks for any variables passed in the url to determine action. Heres the code for the function regform(): <?php function regform($errors) { //set variables to initial value to prevent undefined variable error $errors0 = 0; $errors1 = 0; $errors2 = 0; $errors3 = 0; $errors4 = 0; $errors5 = 0; $errors6 = 0; $errors7 = 0; //check to make sure the array that was passed was not empty //from my validation script the errors are in matching order to the display on this page. //I have only prepared 2 errors for this inital testing, there will be one for each field on the form. $i = count($errors); if($i > 0){ $errors0 = $errors[0]; $errors1 = $errors[1]; //$errors2 = $errors[2]; //$errors3 = $errors[3]; //$errors4 = $errors[4]; //$errors5 = $errors[5]; //$errors6 = $errors[6]; //$errors7 = $errors[7]; } echo "<form id='register' name='register' method='post' action='doreg.php' >"; echo "<table>"; //if the variable = 1 there was an error validating the field in the validate script if($errors0 == 1){ echo "<tr><td><font color='red'>First Name</font></td><td><input type='text' name='firstname' /></td><tr>"; } else { echo "<tr><td>First Name</td><td><input type='text' name='firstname' /></td><tr>"; } if($errors1 == 1){ echo "<tr><td><font color='red'>Last Name</font></td><td><input type='text' name='lastname' /></td><tr>"; } else { echo "<tr><td>Last Name</td><td><input type='text' name='lastname' /></td><tr>"; } //additional errors to be added, as per abov,e for the code below echo "<tr><td>Email Address</td><td><input type='text' name='email' /></td><tr>"; echo "<tr><td>Password</td><td><input type='password' name='password1' /></td><tr>"; echo "<tr><td>Confirm Password</td><td><input type='password' name='password2' /></td><tr>"; echo "<tr><td></td><td></td><tr>"; echo "<tr><td>Accept Terms?</td><td><input type='checkbox' name='accept' /></td><tr>"; echo "<tr><td>Security String</td><td><input type='text' name='secstring' /></td><tr>"; echo "<tr><td></td><td><input type='submit' name='submit' value='submit' /></td><tr>"; echo "<tr><td></td><td><input type='hidden' name='form_submit' value='1' /></td><tr>"; echo "</table>"; echo "</form>"; } ?> So the form takes the array ?valid passed to the register page and determines which fields had a validation error and highlights them red. (I'll modify this highlighting to be what ever I need later...just testing my logic ) The form then calls doreg.php on submit. This will firstly run the validate script, then perform DB actions if all ok, else it will return to register with the error array passed in a query string: <?php if($_POST['form_submit'] == 1) { include ('validate.php'); //the validate script returns $errorarray. Need to figure out better way to test values to determine if any error flags are set if(($errorarray[0]!=0) or ($errorarray[1]!=0) or ($errorarray[2]!=0)) { $errorarray = urlencode(serialize($errorarray)); echo "<meta http-equiv=refresh content=\"0; URL=register.php?valid=$errorarray\">" ; } echo "<meta http-equiv=refresh content=\"0; URL=register.php?success=true\">"; } ?> php] And finally there is the actual validation script. I was hoping to be able to use this for all form validations across the site. I'll just add if(isset) for the various form fields and make sure I standardize my field names across my sites forms. [php] <?php $errorarray = array(); if($_POST['firstname'] == "") { $errorarray[0] = 1; } else {$errorarray[0] = 0; } if($_POST['lastname'] == "") { $errorarray[1] = 1; } else {$errorarray[1] = 0; } if($_POST['email'] == "") { $errorarray[2] = 1; } else {$errorarray[2] = 0; } return $errorarray; ?> For this example I have just done simple empty string checks. I'd really appreciate any advice on the code I've written to date. Im quite sure there are more elegant ways to achieve what these scripts do and I would greatfully accept any feedback. (Be gentle...I'm new ) Thanks Hello freaks, I can't seem to figure out why code not working correctly. Any advise greatly apprechiated. <?php include_once('connect/mysqlconnect.php'); $user = $_POST['uname']; $email = $_POST['email']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; $checkname = mysqli_query("SELECT * FROM users WHERE uname='$user'"); if(isset($_POST['submitted'])){ if(mysqli_num_rows($checkname) > 0) { $errors[] = 'User name not available, please choose different name'; } else { $u = mysqli_real_escape_string($dbc, $user); } if(!empty($email)) { $e = mysqli_real_escape_string($dbc, $email); } else { $errors[] = 'You did not enter email address!'; } if($pass1 == $_POST['pass2']) { $p = mysqli_real_escape_string($dbc, trim($pass1)); } else{ $errors[] = 'Your password did not match. Please try again.'; } if(empty($errors)) { $insert = "INSERT INTO users(uname, email, pass1, register_date) VALUES ('$u','$e',sha1('$p'), NOW(register_date))"; // This execute above statement to INSERT into database $r = mysqli_query($dbc, $insert); } if($r) { //Print a message: echo '<h1>Thank you!</h1> <p>You are now registered.</p><p><br /></p>'; } else { echo ',<h1>Server Error</h1> <p>You could not be registered do to a server error. We apologize for any inconvience.</p>'; } } mysqli_close($dbc); ?> Feel free to move this post if it is in the incorrect category. I was using a validation method for usernames on my website but I would like to make some improvements on it. You typed in your name and it would search and pop-up whether it was available or not. I am looking for a method similar to the one used on this website and many others that checks when the field loses focus. The php code and easiest example I have found is he http://shawngo.com/wp/blog/gafyd/index.html Code: [Select] $username = $_POST['username']; // get the username $username = trim(htmlentities($username)); // strip some crap out of it $file = '/home/js4hire/public_html/gafyd/data.csv'; // Here's the file. Notice the full path. echo check_username($file,$username); // call the check_username function and echo the results. function check_username($file_in,$username){ $username=strtolower($username); $file = file($file_in); foreach ($file as $line_num => $line) { $line = explode(',',$line); $user = trim(str_replace('"','',$line[0])); if($username == strtolower($user)){ return '<span style="color:#f00">Username Unavailable</span>'; } } return '<span style="color:#0c0">Username Available</span>'; } That example uses a flat file CSV, but I would like to use my MySQL database instead. I have included a snippet from my previous that I believe would tie into this, I'm just not sure how exactly: Code: [Select] require_once dirname(__FILE__).'/../includes/common.inc.php'; require_once dirname(__FILE__).'/../includes/user_functions.inc.php'; $output=''; if (!empty($_POST['user'])) { $user=sanitize_and_format($_POST['user'],TYPE_STRING,$__field2format[FIELD_TEXTFIELD]); if (get_userid_by_user($user) || $user=='guest') { $output=1; } } echo $output; That common.inc.php calls for the database connection in session.inc.php: Code: [Select] $josh_dblink=db_connect(_DBHOST_,_DBUSER_,_DBPASS_,_DBNAME_); if (!defined('NO_SESSION')) { require _BASEPATH_.'/includes/sessions.inc.php'; } I don't want to have to call the db connection again in that file but I need to get the relevant information and pass it through the php. Any help would be appreciated! I'm trying to make a simple but secure login/user registration for this site I'm building. I'm new to php, so I followed some tutorials from www.newthinktank.com. http://www.newthinktank.com/2011/01/php-security-pt-2/ http://www.newthinktank.com/2011/01/php-security-pt-4-set-up-captcha// http://www.newthinktank.com/2011/01/web-design-and-programming-pt-21-secure-login-script/ But I'm having a couple of problems. On the registration.php file, whenever I type in wrong information, the validation error messages don't display and also whenever I click the submit button, the form doesn't do anything. It doesn't insert information into my database. It just shows the empty form. On my login.php file, again the validation errors don't display and I can't tell if I'm logged in or not. The form redirects to my index page, but the user box that shows the different menus depending on whether or not someone is logged in stays in guest mode. I don't get any php error messages on either file. Here's my code: register.php file: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled</title> <link href="_css/page_layout.css" rel="stylesheet" type="text/css" /> <link href="_css/page_text.css" rel="stylesheet" type="text/css" /> <link href="_css/sidebarLeft.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrapper"> <?php include('_includes/template/header.php'); ?> <?php include('_includes/template/nav.php'); ?> <?php include('_includes/template/sidebar_left.php'); ?> <div id="mainContent"> <div class="content"> <?php require_once('_includes/connectvars.php'); if (isset($_POST['submitted'])) { if (preg_match ('%^[A-Za-z\.\' \-]{2,20}$%', stripslashes(trim($_POST['first_name'])))) { $firstname = escape_data($_POST['first_name']); } else { $firstname = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid first name!</font></p>'; } if (preg_match ('%^[A-Za-z\.\' \-]{2,40}$%', stripslashes(trim($_POST['last_name'])))) { $lastname = escape_data($_POST['last_name']); } else { $lastname = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid last name!</font></p>'; } if (preg_match ('%^(0?[1-9]|[12][0-9]|3[01])[-/. ](0?[1-9]|1[0-2])[-/.](19|20)\d{2}$%', stripslashes(trim($_POST['birth_date'])))) { $birthdate = escape_data($_POST['birth_date']); } else { $birthdate = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid date of birth!</font></p>'; } $gender = escape_data($_POST['gender']); if (preg_match ('%^[0-9]{5}$%', stripslashes(trim($_POST['zip_code'])))) { $zipcode = escape_data($_POST['zip_code']); } else { $zipcode = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid 5 digit zip code!</font></p>'; } if (preg_match ('%^[A-Za-z0-9._\%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$%', stripslashes(trim($_POST['email'])))) { $email = escape_data($_POST['email']); } else { $email = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid email address!</font></p>'; } if (preg_match ('%^[a-z\d_]{2,20}$%', stripslashes(trim($_POST['username'])))) { $username = escape_data($_POST['username']); } else { $username = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid username!</font></p>'; } if (preg_match ('%\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{6,}\z%', stripslashes(trim($_POST['password1'])))) { if (($_POST['password1'] == $_POST['password2']) && ($_POST['password1'] != $_POST['username'])) { $password = escape_data($_POST['password1']); } elseif ($_POST['password1'] == $_POST['username']) { $password = FALSE; echo '<p><font color="red" size="+1″>Your password cannot be the same as the username!</font></p>'; } else { $password = FALSE; echo '<p><font color="red" size="+1″>Your password did not match the confirmed password!</font></p>'; } } else { $password = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid password!</font></p>'; } $captchchk = 1; require_once('_includes/recaptchalib.php'); $privatekey = "My private key goes here...i know"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { echo '<p><font color="red" size="+1″>The CAPTCHA Code wasn\'t entered correctly! </font></p>'; $captchchk = 0; } if ($firstname && $lastname && $birthdate && $gender && $zipcode && $email && $username && $password) { $query = "SELECT user_id FROM users WHERE username='$username'"; $result = mysql_query($query) or trigger_error("Sorry, that username is taken"); if(mysql_num_rows($result) == 0) { $a = md5(uniqid(rand(), true)); $query = "INSERT INTO users(zip_code, username, first_name, password, activation_code, join_date, last_name, gender, birth_date, email) VALUES ('$zipcode', '$username', '$firstname', SHA('$password'), '$a', NOW(), '$lastname', '$gender', '$birthdate', '$email')"; $result = mysql_query($query) or trigger_error("Sorry an error happened"); if(mysql_affected_rows() == 1) { $body = "Thanks for registering. Activate account by clicking this link: <br />"; $body .= "http://localhost/activate.php?x=" . mysql_insert_id() . "&y=$activationcode"; mail($email, 'Registration Confirmation', '$body', 'From: admin@mysite.com'); echo '<br /><br /><h1>Thank you for registering! A confirmation email has been sent to your address. Please click on the link in that email in order to activate your account.</h1>'; } exit(); } else { echo '<p><font color="red" size="+1″>You could not be registered due to a system error. We apologize for any inconvenience.</font></p>'; } } else { echo '<p><font color="red" size="+1″>That email address has already been registered. If you have forgotten your password, use the link to have your password sent to you.</font></p>'; } mysql_close(); } ?> <h1>Register</h1> <br /> <p>Please fill out the form below. All fields required.</p> <br /> <center><form action="register.php" method="POST" id="regform"> <table width="550" border="0"> <tr> <td width="200"><p>First Name:</p></td> <td width="200"><label for="first_name"></label> <input name="first_name" type="text" id="first_name" maxlength="20" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/></td> <td width="200"> </td> </tr> <tr> <td><p>Last Name:</p></td> <td><label for="last_name"></label> <input name="last_name" type="text" id="last_name" maxlength="45" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Birthdate:</p></td> <td><label for="birth_date"></label> <input name="birth_date" type="text" id="birth_date" maxlength="10" value="<?php if (isset($_POST['birth_date'])) echo $_POST['birth_date']; ?>"/></td> <td><p>(Format: MM/DD/YYYY)</p></td> </tr> <tr> <td><p>Gender</p></td> <td><p> <label> <input type="radio" name="gender" value="F" id="gender_0" /> F </label> <label> <input type="radio" name="gender" value="M" id="gender_1" /> M </label> <input name="gender" type="hidden" value="" /> <br /> </p></td> <td> </td> </tr> <tr> <td><p>Zip Code</p></td> <td><label for="zip_code"></label> <input name="zip_code" type="text" id="zip_code" maxlength="5" value="<?php if (isset($_POST['zip_code'])) echo $_POST['zip_code']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Email:</p></td> <td><label for="email"></label> <input name="email" type="text" id="email" maxlength="255" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Username:</p></td> <td><label for="username"></label> <input name="username" type="text" id="username" maxlength="60" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Choose New Password:</p></td> <td><label for="password1"></label> <input name="password1" type="password" id="password1" maxlength="40" /></td> <td> </td> </tr> <tr> <td><p>Confirm New Password:</p></td> <td><label for="password2"></label> <input name="password2" type="password" id="password2" maxlength="40" /></td> <td> </td> </tr> </table> </br> <?php require_once('_includes/recaptchalib.php'); $publickey = "my public key goes here...i know"; // you got this from the signup page echo recaptcha_get_html($publickey); ?> <br /> <input type="submit" name="submit_signup" id="submit_signup" value="Sign Up" /> <input type="hidden" name="submitted" value="TRUE" /> </form></center> <br /> <br /> </div> </div> <?php include('_includes/template/sidebar_right.php'); ?> <?php include('_includes/template/footer.php'); ?> </div> </body> </html> login.php file: Code: [Select] <?php session_start(); require_once('_includes/connectvars.php'); ?> <?php if (isset($_POST['submitLogin'])) { if (preg_match ('%^[A-Za-z0-9]\S{6,20}$%', stripslashes(trim($_POST['username'])))) { $username = escape_data($_POST['username']); } else { $username = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid username!</font></p>'; } if (preg_match ('%^[A-Za-z0-9]\S{6,20}$%', stripslashes(trim($_POST['password'])))) { $password = escape_data($_POST['password']); } else { $password = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid password!</font></p>'; } if ($username && $password) { $query = "SELECT user_id, level_access, username, password, join_date, first_name, last_name, birth_date, gender, zip_code, email, activation_code FROM users WHERE username='$username' AND password=SHA('$password')"; $result = mysql_query ($query) or trigger_error("Either the Username or Password are incorrect"); if (mysql_affected_rows() == 1) { $row = mysql_fetch_array ($result, MYSQL_NUM); mysql_free_result($result); $_SESSION['first_name'] = $row[5]; $_SESSION['username'] = $row[2]; $tokenId = rand(10000, 9999999); $query2 = "update users set tokenid = $tokenId where username = '$_SESSION[username]'"; $result2 = mysql_query ($query2); $_SESSION['token_id'] = $tokenId; session_regenerate_id(); header("Location: http://localhost/mysite/index.php"); mysql_close(); exit(); } } else { echo '<br><br><p><font color="red" size="+1″>Either the Username or Password are incorrect</font></p>'; mysql_close(); exit(); } echo '<br><br><p><font color="red" size="+1″>Either the Userid or Password are incorrect</font></p>'; mysql_close(); exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled</title> <link href="_css/page_layout.css" rel="stylesheet" type="text/css" /> <link href="_css/page_text.css" rel="stylesheet" type="text/css" /> <link href="_css/sidebarLeft.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrapper"> <?php include('_includes/template/header.php'); ?> <?php include('_includes/template/nav.php'); ?> <?php include('_includes/template/sidebar_left.php'); ?> <div id="mainContent"> <div class="content"> <h1>Login</h1> <form action="login.php" method="post" name="login" id="login"> <table width="200" border="0"> <tr> <td><p>Username:</p></td> <td><label for="username"></label> <input type="text" name="username" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>"/></td> </tr> <tr> <td><p>Password:</p></td> <td><label for="password"></label> <input type="password" name="password" id="password" /></td> </tr> </table> <br /> <p> <label> <input type="radio" name="remember_me" value="radio" id="remember_me_0" /> Keep me logged in </label> <br /> </p> <br /> <input type="submit" name="submitLogin" value="Login" /> <input type="hidden" name="submitted" value="TRUE" /> </form> <br /> <p>Not a member? <a href="register.php">Create an account!</a></p> <br /> <p>Forgot password?</p> </div> </div> <?php include('_includes/template/sidebar_right.php'); ?> <?php include('_includes/template/footer.php'); ?> </div> </body> </html> Here's the code that shows the different menus depending on if someone is logged in or not. Code: [Select] <div class="login"> <?php echo '<p>'; echo 'Welcome '; if (isset($_SESSION['first_name'])) { echo " {$_SESSION['first_name']}!</br></br>"; } else { echo 'Guest!'; } if (isset($_SESSION['username']) AND (substr($_SERVER['PHP_SELF'], -10) != 'logout.php')) { echo '<a href="add_event.php">Add an Event</a></br> <a href="my_profile.php">My Profile</a></br> <a href="logout.php"><p>Logout</a></br>'; } else { echo '</br> <a href="register.php">Register</a></br> <a href="login.php">Login</a></br>'; } echo'</p>'; ?> </div> I need help with this ASAP!!! I pretty sure my boss will fire me if I can not figure this out tonight... PLEASE HELP! I am a graphic designer and not a programmer... PLEASE HELP ME!!! My form will not display the echoed message ("Please fill in all required (*) feilds", "Maximum length for username is 25 characters", etc.) when I hit submit... It wouldn't even show the variables when I tried to just have the form only echo the various strings... nothing appeared... the only way I could get the string values to appear was through a array like this: if(is_array($_POST)){ echo '<pre>'; print_r($_POST); echo '</pre>'; } ^^This returned the data fine... but when I try to echo on particular string and not using the array, nothing appears... This is crucial as this is how the custom error messages are displayed... Here is my PHP code: <?php $submit = $_POST['submit']; //form data $username = strip_tags($_POST['username']); $password = strip_tags($_POST['password']); $passwordrepeat = strip_tags($_POST['passwordrepeat']); $email = strip_tags($_POST['email']); $emailrepeat = strip_tags($_POST['emailrepeat']); $career_status = strip_tags($_POST['career_status']); $name_title = strip_tags($_POST['name_title']); $first_name = strip_tags($_POST['first_name']); $middle_name = strip_tags($_POST['middle_name']); $last_name = strip_tags($_POST['last_name']); $suffix = strip_tags($_POST['suffix']); $current_address1 = strip_tags($_POST['current_address1']); $current_address2 = strip_tags($_POST['current_address2']); $current_city = strip_tags($_POST['current_city']); $current_state = strip_tags($_POST['current_state']); $current_zip = strip_tags($_POST['current_zip']); $phone_home = strip_tags($_POST['phone_home']); $phone_mobile = strip_tags($_POST['phone_mobile']); $preferred_contact = strip_tags($_POST['preferred_contact']); $school_name = strip_tags($_POST['school_name']); $school_city = strip_tags($_POST['school_city']); $school_state = strip_tags($_POST['school_state']); $school_gradYear = strip_tags($_POST['school_gradYear']); $med_school_debt = strip_tags($_POST['med_school_debt']); $monthly_debt_payment = strip_tags($_POST['monthly_debt_payment']); $credit_score = strip_tags($_POST['credit_score']); $marital_status = strip_tags($_POST['marital_status']); $current_employer_name = strip_tags($_POST['current_employer_name']); $current_employer_city = strip_tags($_POST['current_employer_city']); $current_employer_state = strip_tags($_POST['current_employer_state']); $current_position = strip_tags($_POST['current_position']); $current_specialty = strip_tags($_POST['current_specialty']); $current_employer_startDate_mm = strip_tags($_POST['current_employer_startDate_mm']); $current_employer_startDate_yyyy = strip_tags($_POST['current_employer_startDate_yyyy']); $changing_employer = strip_tags($_POST['changing_employer']); $current_employer_endDate_mm = strip_tags($_POST['current_employer_endDate_mm']); $current_employer_endDate_yyyy = strip_tags($_POST['current_employer_endDate_yyyy']); $future_employer_name = strip_tags($_POST['future_employer_name']); $future_employer_city = strip_tags($_POST['future_employer_city']); $future_employer_state = strip_tags($_POST['future_employer_state']); $future_position = strip_tags($_POST['future_position']); $future_specialty = strip_tags($_POST['future_specialty']); $future_employer_startDate_mm = strip_tags($_POST['future_employer_startDate_mm']); $future_employer_startDate_yyyy = strip_tags($_POST['future_employer_startDate_yyyy']); $destination_city = strip_tags($_POST['destination_city']); $destination_state = strip_tags($_POST['destination_state']); $move_date_mm = strip_tags($_POST['move_date_mm']); $move_date_yyyy = strip_tags($_POST['move_date_yyyy']); $prop_single_family = strip_tags($_POST['prop_single_family']); $prop_townhouse = strip_tags($_POST['prop_townhouse']); $prop_condo = strip_tags($_POST['prop_condo']); $prop_co_op = strip_tags($_POST['prop_co_op']); $prop_duplex = strip_tags($_POST['prop_duplex']); $prop_mobile = strip_tags($_POST['prop_mobile']); $prop_other = strip_tags($_POST['prop_other']); $num_bedrooms = strip_tags($_POST['num_bedrooms']); $num_bath = strip_tags($_POST['num_bath']); $price_low = strip_tags($_POST['price_low']); $price_high = strip_tags($_POST['price_high']); $prop_purpose = strip_tags($_POST['prop_purpose']); $need_realtor = strip_tags($_POST['need_realtor']); $need_lender = strip_tags($_POST['need_lender']); $need_refinance_NoCash = strip_tags($_POST['need_refinance_NoCash']); $need_refinance_TakeCash = strip_tags($_POST['need_refinance_TakeCash']); $need_home_equity = strip_tags($_POST['need_home_equity']); $need_commercial = strip_tags($_POST['need_commercial']); $need_practice = strip_tags($_POST['need_practice']); $mortgage_needs = strip_tags($_POST['mortgage_needs']); $most_important = strip_tags($_POST['most_important']); $keep_property_time = strip_tags($_POST['keep_property_time']); $keep_mortgage_time = strip_tags($_POST['keep_mortgage_time']); $program_foundHome_lowDown_NoPMI = strip_tags($_POST['program_foundHome_lowDown_NoPMI']); $program_foundHome_20down_bestRate = strip_tags($_POST['program_foundHome_20down_bestRate']); $program_foundHome_20down_specializedLender = strip_tags($_POST['program_foundHome_20down_specializedLender']); $program_preapproved_physLoan = strip_tags($_POST['program_preapproved_physLoan']); $program_preapproved_coventionalLoan = strip_tags($_POST['program_preapproved_coventionalLoan']); $program_lenderBailed = strip_tags($_POST['program_lenderBailed']); $program_poorCredit = strip_tags($_POST['program_poorCredit']); $referral_source = strip_tags($_POST['referral_source']); $registration_date = date("Y-m-d"); if ($submit) { //check that required fields are completed if ($username&&$password&&$passwordrepeat&&$email&&$emailrepeat&&$career_status&&$first_name&&$last_name) { //encrypt password $password = md5($password); $passwordrepeat = md5($passwordrepeat); if ($password==$passwordrepeat) { //check character length of username and if (strlen($username)>25) { echo "Maximum length for username is 25 characters."; } else { //check password length if (strlen($password)>25||(strlen($password)<6)) { echo "Password must be between 6 and 25 characters in length."; } else { //register the user echo "Success!"; } } } else echo "Your passwords do not match. Please re-enter and hit submit again."; } else echo "Please fill in all required (*) feilds."; } ?> Here is my form: http://www.doctorbrownshoes.com/testPHP/registration.php CREATE TABLE user (username varchar(20),password varchar(20),level varchar(20),PRIMARY KEY(username)); INSERT INTO `user` VALUES ('a', 'pass1', 'admin'); INSERT INTO `user` VALUES ('b', 'pass2', 'admin'); INSERT INTO `user` VALUES ('c', 'pass3', 'user'); This is my database and Registration.php Code: [Select] <html> <head> <script type="text/javascript"> function a() { var x = document.register.username.value; var y = document.register.pass.value; var z = document.register.pass2.value; if(x==""&& y==""&& z=="") { alert("Please insert all message!"); return false; } if(x=="") { alert("Please insert an username!"); return false; } if(y=="") { alert("Please insert an password!"); return false; } if(z=="") { alert("Please insert an password2!"); return false; } if (y!=z) { alert("Your passwords did not match"); return false; } } </script> </head> <?php mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); if (isset($_POST["sub"])) { $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); $_POST['pass'] = addslashes($_POST['pass']); } $usercheck = $_POST["username"]; $check = mysql_query("SELECT username FROM regis WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('Sorry, the username" ." ".$usercheck." ". "is already in use.')</SCRIPT>"); echo ("<SCRIPT LANGUAGE='JavaScript'>setTimeOut(window.location = 'registration.php',1)</script>"); } else if($_POST['username'] && $_POST['pass'] && $_POST['pass2'] ) { $insert = "INSERT INTO regis(username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('Registration had been succesfully added :)')</SCRIPT>"); echo "<meta http-equiv='refresh' content='0; url=login.php'>"; } } ?> <body> <form name="register" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return a()"> <table border='0'> <tr><td>Username:</td><td><input type="text"name="username" maxlength="60"></td></tr> <tr><td>Password:</td><td><input type="password" name="pass" maxlength="10"></td></tr> <tr><td>Confirm Password:</td><td><input type="password" name="pass2" maxlength="10"></td></tr> <tr><th colspan=2><input type="submit" name="sub" value="Register"></th></tr></table> </form> </body> </html> My main problem when in registration iam did not put user level field because it is not secure but how to manage or how to detect when someone registering he or she is user or admin? Hi All, I have currently been working on a login/registration system for a university project and I am now struggling with the login section. The problem is with one particular function and an if statement. The function checks to see if the username and password entered matches the username and password in the database but each time I get it echoing username/password incorrect. the function is Code: [Select] function valid_credentials($user, $pass) { $user = mysql_real_escape_string($user); $pass = sha1($pass); $total = mysql_query("SELECT COUNT(`user_username`) FROM `users` WHERE `user_username` = '{$user}' AND `user_password` = '{$pass}'"); return (mysql_result($total, 0) == '1') ? true : false; } and the statement is Code: [Select] if (valid_credentials($_POST['username'], $_POST['password']) == false) { $errors = 'Username/Password incorrect.'; } Any help would be greatly appreciated as this has been bugging me for the past 5 days :/ Set up: * XAMPP 1.7.3 * Apache 2.2.14 (IPv6 enabled) + OpenSSL 0.9.8l * MySQL 5.1.41 + PBXT engine * PHP 5.3.1 * phpMyAdmin 3.2.4 * Perl 5.10.1 * FileZilla FTP Server 0.9.33 * Mercury Mail Transport System 4.72 I'm trying to set up a multipage registration script. It's tuff! I've set up some basic scripts to distribute variables into the correct tables from previous forms using a session. But I want the script to check the input from form one is valid before it moves on to form 2. Here are my scripts: form 1: <html> <head> <title>Register</title> <style type="text/css"> td { vertical-align: top; } </style> </head> <body> <form action="form2.php" method="post"> <table> <tr> <td><label for="name">Username:</label></td> <td><input type="text" name="name" id="name" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="password">Password:</label></td> <td><input type="password" name="password" id="password" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="first_name">First name:</label></td> <td><input type="text" name="first_name" id="first_name" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="last_name">Last name:</label></td> <td><input type="text" name="last_name" id="last_name" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="email">Email:</label></td> <td><input type="text" name="email" id="email" size="20" maxlength="50" value=""/></td> </tr><tr> <td><label for="address">Address:</label></td> <td><input type="text" name="address" id="address" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="city">City/Town:</label></td> <td><input type="text" name="city" id="city" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="county">County:</label></td> <td><input type="text" name="county" id="county" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="post">Postcode:</label></td> <td><input type="text" name="post" id="post" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="home">Home Number:</label></td> <td><input type="text" name="home" id="home" size="20" maxlength="20" value=""/></td> </tr><tr> <td><label for="mobile">Mobile:</label></td> <td><input type="text" name="mobile" id="mobile" size="20" maxlength="20" value=""/></td> </tr><tr> <td> </td> <td><input type="submit" name="submit" value="Sumbit"/></td> </tr> </table> </form> </body> </html> Form 2: <?php //let's start the session session_start(); //now, let's register our session variables session_register('name'); session_register('password'); session_register('first_name'); session_register('last_name'); session_register('email'); session_register('address'); session_register('city'); session_register('county'); session_register('post'); session_register('home'); session_register('mobile'); //finally, let's store our posted values in the session variables $_SESSION['name'] = $_POST['name']; $_SESSION['password'] = $_POST['password']; $_SESSION['first_name'] = $_POST['first_name']; $_SESSION['last_name'] = $_POST['last_name']; $_SESSION['email'] = $_POST['email']; $_SESSION['address'] = $_POST['address']; $_SESSION['city'] = $_POST['city']; $_SESSION['county'] = $_POST['county']; $_SESSION['post'] = $_POST['post']; $_SESSION['home'] = $_POST['home']; $_SESSION['mobile'] = $_POST['mobile']; ?> <html> <head> <title>Register</title> <style type="text/css"> td { vertical-align: top; } </style> </head> <body> <form action="form3.php" method="post"> <table> <tr> <td><label for="bio">Biography:</label></td> <td><input type="text" name="bio" id="bio" size="400" maxlength="500" value=""/></td> </tr><tr> <td> </td> <td><input type="submit" name="submit" value="Sumbit"/></td> </tr> </table> </form> </body> </html> I've also got form3.php and process_forms.php(that's where I mysql_real_escape_string and input the data) but that's probably not relevant. How would I get this to work? Are there any sites I should look at that you'd recommend? Any help appreciated. I'm building a php program that registers users onto a website. With the help of people from this thread http://www.phpfreaks.com/forums/index.php?topic=332260.15 I was able to accomplish the goal and now the signup works with conditions that check for a valid email, and if the password is strong enough. T he program correctly displays the the problem when a user does NOT enter a valid email, or a strong enough password, but the user has to re-enter the email and password everytime. I want to make it so that the fields remained populated with what the user entered previously, so he or she does not have to re-enter his or her email/password. Here is the code (its really ghetto) Code: [Select] <?php function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } define('DB_NAME', 'catch'); define('DB_USER', 'username'); define('DB_PASS', 'password'); define('DB_HOST', 'page.sqlserver.com'); // contact to database $connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Error , check your server connection.'); mysql_select_db(DB_NAME); //Get data in local variable $v_name=$_POST['name']; $v_email=$_POST['email']; $v_msg=$_POST['msg']; if ( check_email_address($_POST['name']) == false) { $query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } echo <<<EOD <head> <link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css"> </head> <h2>Free Registration</h2> <form action="contact_insert2.php" method="POST" id="insert"> <table> <tr> <td>Email</td> <td ><input type="text" size="40" name="name"></td> </tr> <tr> <td>Password</td> <td><input type="password" size="40" name="msg" ></td> </tr> <tr> <td colspan=2 id="sub"> You must enter a valid email. <br /> <input type="submit" name="submit" value="submit"> </td> </tr> </Table> </form> EOD; } if( $v_name == "" || $v_msg == "" ) // if name is empty or if pass is empty { $query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } echo <<<EOD <head> <link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css"> </head> <h2>Free Registration</h2> <form action="contact_insert2.php" method="POST" id="insert"> <table> <tr> <td>Email</td> <td ><input type="text" size="40" name="name"></td> </tr> <tr> <td>Password</td> <td><input type="password" size="40" name="msg" ></td> </tr> <tr> <td colspan=2 id="sub"> You must enter an email and password. <br /> <input type="submit" name="submit" value="submit"> </td> </tr> </Table> </form> EOD; } if( strcspn( $_REQUEST['msg'], '0123456789' ) == strlen( $_REQUEST['msg'] ) ) // the above statement says if pass does not contain a number { $query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } echo <<<EOD <head> <link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css"> </head> <h2>Free Registration</h2> <form action="contact_insert2.php" method="POST" id="insert"> <table> <tr> <td>Email</td> <td ><input type="text" size="40" name="name"></td> </tr> <tr> <td>Password</td> <td><input type="password" size="40" name="msg" ></td> </tr> <tr> <td colspan=2 id="sub"> <div style="color:red;">Your password must contain a number.</div> <br /> <input type="submit" name="submit" value="submit"> </td> </tr> </Table> </form> EOD; } if( strlen($_POST['msg']) < 8 ) // the above statement says if pass is not 8 characters long { $query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } echo <<<EOD <head> <link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css"> </head> <h2>Free Registration</h2> <form action="contact_insert2.php" method="POST" id="insert"> <table> <tr> <td>Email</td> <td ><input type="text" size="40" name="name"></td> </tr> <tr> <td>Password</td> <td><input type="password" size="40" name="msg" ></td> </tr> <tr> <td colspan=2 id="sub"> <div style="color:red;">Your password must be at least 8 characters long.</div> <br /> <input type="submit" name="submit" value="submit"> </td> </tr> </Table> </form> EOD; } if ( $_POST['msg'] == strtolower($_POST['msg']) ) // the above statement says if pass is all lowercase { $query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } echo <<<EOD <head> <link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css"> </head> <h2>Free Registration</h2> <form action="contact_insert2.php" method="POST" id="insert"> <table> <tr> <td>Email</td> <td ><input type="text" size="40" name="name"></td> </tr> <tr> <td>Password</td> <td><input type="password" size="40" name="msg" ></td> </tr> <tr> <td colspan=2 id="sub"> <div style="color:red;">Your password must have at least one capital letter.</div> <br /> <input type="submit" name="submit" value="submit"> </td> </tr> </Table> </form> EOD; } if ( preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST['msg']) == $_POST['msg'] ) // the above statement says if pass contains no special characters { $query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } echo <<<EOD <head> <link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css"> </head> <h2>Free Registration</h2> <form action="contact_insert2.php" method="POST" id="insert"> <table> <tr> <td>Email</td> <td ><input type="text" size="40" name="name"></td> </tr> <tr> <td>Password</td> <td><input type="password" size="40" name="msg" ></td> </tr> <tr> <td colspan=2 id="sub"> <div style="color:red;">Your password must have at least one special character.</div> <br /> <input type="submit" name="submit" value="submit"> </td> </tr> </Table> </form> EOD; } else echo <<<EOD <B>GO FUCK YOURSELF</B> EOD; ?> Hi everyone, I wanted to let you know first that i am real new into this. I am trying to build a user management system and i can't seem to add a registration field. I got the free script uM Script and here's the code, please help me on this one: REGISTER.PHP Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB"> <head> <title>Member Registration</title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="robots" content="index, follow" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <script type="text/javascript" src="js/jquery-1.6.2.js"></script> <script type="text/javascript" src="js/script.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#regForm').submit(function(e) { register(); e.preventDefault(); }); }); </script> </head> <body> <table align="center" width="100%" cellspacing="1" cellpadding="1" border="0"> <tr> <td align="left"><a href="index.php">Home</a> | <a href="login.php">Log in</a> | <a href="register.php">Register</a> | <a href="pass_reset.php">Reset Password</a> | <a href="contact_us.php">Contact Us</a></td><td align="right"><a href="admin/login.php">Admin Login</a></td> </tr> </table> <hr/> <p>Register</p> <p>Use the form below to register.</p> <hr/> <div class="done"><p>Registration successful! <a href="login.php">Click here</a> to login.</p></div><!--close done--> <div class="form"> <form id="regForm" action="reg_submit.php" method="post"> <table align="center" width="50%" cellspacing="1" cellpadding="1" border="0"> <tr> <td colspan="2" ></td> </tr> <tr> <td> <label for="username">Username:</label> </td> <td> <input onclick="this.value='';" name="username" type="text" size="25" maxlength="8" value="<?php if(isset($_POST['username'])){echo $_POST['username'];}?>"/> </td> </tr> <tr> <td> <label for="password">Password:</label> </td> <td> <input name="password" type="password" size="25" maxlength="15" /> </td> </tr> <tr> <td> <label for="email">Email:</label> </td> <td> <input onclick="this.value='';" name="email" type="text" size="25" maxlength="50" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>"/> </td> </tr> <tr> <td><label for="phone"><label>Phone:</label></td><td><input type="text" name="phone" value="<?php if(isset($_POST['phone'])){echo $_POST['phone'];}?>"/></td> </tr> <td> </td> <td> <input type="submit" name="register" value="Register" /><img id="loading" src="images/loading.gif" alt="working.." /> </td> </tr> <tr> <td colspan="2"><div id="error"> </div></td> </tr> </table> </form> </div><!--close form--> </body> </html> REG.SUBMIT.PHP Code: [Select] <?php require_once('lib/connections/db.php'); include('lib/functions/functions.php'); $sitesettings = getSiteSettings(); $site_url = $sitesettings[0]['site_url']; //For registration // we check if everything is filled in and perform checks if(!$_POST['username']) { die(msg(0,"<p>Please enter a username.</p>")); } if(strlen($_POST['username'])<3 || strlen($_POST['username'])>15) { die(msg(0,"<p>Username must be between 3 and 15 characters.</p>")); } elseif(uniqueUser($_POST['username'])) { die(msg(0,"Username already taken.")); } elseif(!$_POST['password']) { die(msg(0,"<p>Please enter a password.</p>")); } elseif(strlen($_POST['password'])<5) { die(msg(0,"<p>Usernames must be atleast 5 characters.</p>")); } elseif(!$_POST['email']) { die(msg(0,"<p>Please enter an email address.</p>")); } /*elseif(validateEmail($_POST['email'])) { die(msg(0,"<p>Invalid email address.</p>")); }*/ elseif(uniqueEmail($_POST['email'])) { die(msg(0,"<p>Email taken. Please select another email address.</p>")); } elseif(!$_POST['phone']) { die(msg(0,"Phone numbers must be of numeric type only.")); } else { $res = addUser($_POST['username'],$_POST['password'],$_POST['email'], $_POST['phone'],$site_url); if ($res == 1){ die(msg(0,"Failed to send activation email. Please contact the site admin.")); } if ($res == 2){ die(msg(0,"There was an error registering your details. Please contact the site admin.")); } if ($res == 99){ die(msg(1,"<p>Registration successful! <a href='login.php'>Click here</a> to login.</p>")); } } function msg($status,$txt) { return '{"status":'.$status.',"txt":"'.$txt.'"}'; } ?> And the code of the function: Code: [Select] //----------Function for adding user's profile---------- function addUser($user,$pass,$email,$site_url) { $user = secureInput($user); $pass = secureInput($pass); $email = secureInput($email); $site_url = secureInput($site_url); //Encrypt password for database $salt = 's+(_a*'; $pass = md5($pass.$salt); $reg_date = date("l, M j, Y, g:i a"); $sql = "INSERT INTO users (username,password,email,active,level_access,reg_date) VALUES ('".$user."','".$pass."','".$email."',0,2,'".$reg_date."')"; $res = mysql_query($sql); if($res){ //build email to be sent $to = $email; $subject = $site_url; $subject .= ": Activate Your Account"; $message = " <html> <head> <title>Account Activation</title> </head> <body> <h3>Account Activation</h3> <p>Dear ".$user.", thank you for registering at ".$site_url.".</p> <p>Please click on the link below to activate your account:</p> <a href='".$site_url."/confirm_user_reg.php?prsn=".$user."'>http://www.".$site_url."</a>. <p>If the above link does not work, copy and paste the below URL to your browser's address bar:</p> <p><i>http://www.".$site_url."/confirm_user_reg.php?prsn=".$user."</i></p><br/> <p>If you did not initiate this request, simply disregard this email, and we're sorry for bothering you.</p> <br/><br/> <p>Sincerely,</p> <p>The ".$site_url." Team.</p> </body> </html> "; // To send HTML mail, the Content-type header must be set $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; if($mail_send = mail($email, $subject, $message, $headers)) { } return 99; return 1; } else return 2; } I know i'm wrong somewhere because when i register a user the phone number won't post on the "phone" field on database. below is the code for a registration form. It "works",I mean that the insert query is being performed, some error messages appear. the problem is, i don't understand how "root" is being automatically sent to the database as a username. when logging into phpmyadmin, the username root appears because it is on autofill. but, i don't get why it's filling the registration form with root. i don't see "root" entered on the form, but, after registering, it says "Congratulations root!". If i leave the form blank, i don't get the error message for blank username either. i've just started learning php,so i guess something might be wrong with the code. any help, please? Code: [Select] <html> <head> <link rel="stylesheet" type="text/css" href="reset.css" media="screen" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> <title>Register</title> </head> <body> <div id="layout_wrapper"> <div id="layout_container"> <div id="layout_content"> <div id="site_title"> <h1><a href="home.html">WEBSITE</a></h1> <h2>WEBSITE DESCRI</h2> </div> <div id="header_image"></div> <div class="clearer"> </div> </div> <div id="main"> <div class="post"> <div class="post_top"> <div class="post_title"><h2>REGISTER</h2></div> </div> <div class="post_body"> <?php $error_stat=0; $errorMsg=''; if (isset ($_POST['submit'])){ $username = $_POST['username']; $gender = preg_replace('#[^a-z]#i', '', $_POST['gender']); $b_m = preg_replace('#[^0-9]#i', '', $_POST['birth_month']); $b_d = preg_replace('#[^0-9]#i', '', $_POST['birth_day']); $b_y = preg_replace('#[^0-9]#i', '', $_POST['birth_year']); $email1 = $_POST['email1']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; $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); include_once "../scripts/connect_to_mysql.php"; $emailCHecker = mysql_real_escape_string($email1); $emailCHecker = str_replace("`", "", $emailCHecker); $sql_uname_check = mysql_query("SELECT user_name FROM tbl_user WHERE user_name='$username'"); $uname_check = mysql_num_rows($sql_uname_check); $sql_email_check = mysql_query("SELECT email FROM tbl_user WHERE email='$emailCHecker'"); $email_check = mysql_num_rows($sql_email_check); if ((!$username) || (!$gender) || (!$b_m) || (!$b_d) || (!$b_y) || (!$email1) || (!$pass1) || (!$pass2)) { $error_stat=1; $errorMsg = 'ERROR: You did not submit the following required information:<br /><br />'; if(!$username){ $errorMsg .= ' * User Name<br />'; } if(!$gender){ $errorMsg .= ' * 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(!$pass1){ $errorMsg .= ' * Login Password<br />'; } if(!$pass2){ $errorMsg .= ' * Confirm Login Password<br />'; } } else if ($pass1 != $pass2) { $errorMsg = 'ERROR: Your Password fields below do not match<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 { $email1 = mysql_real_escape_string($email1); $pass1 = mysql_real_escape_string($pass1); $full_birthday = "$b_y-$b_m-$b_d"; $sql = mysql_query("INSERT INTO tbl_user (user_name, sex, dob, date_joined,email, password) VALUES('$username','$gender','$full_birthday', now(),'$email1', '$pass1')") or die (mysql_error()); $id = mysql_insert_id(); echo "<h2>Registration Successful!</h2>"; echo "<p>Congratulations <b>$username</b>, your registration was successful. Your account has now been created with the following details:</p>"; echo "<p><b>Username:</b> $username</p>"; echo "<p><b>Password:</b> $pass1</p>"; echo "<p><b>Sex:</b> $gender</p>"; echo "<p><b>Email:</b> $email1</p>"; echo "<p><b>DOB:</b> $full_birthday</p>"; echo "<p>You may now login.</p>"; } // Close else after duplication checks } if (!isset($_POST['submit']) || $error_stat==1) { ?> <?php echo $errorMsg;?> <form method="POST" action=""> <table> <tr> <td width="114" bgcolor="#FFFFFF">User Name: *</span></td> <td width="452" bgcolor="#FFFFFF"><input name="username" type="text" id="username " size="32" maxlength="20" /> <span id="nameresponse">Alphanumeric Characters Only</span></td> </tr> <tr> <td bgcolor="#EFEFEF">Sex:*</span></td> <td bgcolor="#EFEFEF"><label> <input name="gender" type="radio" id="gender" value="m" checked="checked" />Male <input type="radio" name="gender" id="gender" value="f" />Female </label></td> </tr> <tr> <td bgcolor="#FFFFFF">Date of Birth:*</span></td> <td bgcolor="#FFFFFF"> <select name="birth_month" id="birth_month"> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="birth_day" id="birth_day"> <option value="01">1</option> <option value="02">2</option> <option value="03">3</option> <option value="04">4</option> <option value="05">5</option> <option value="06">6</option> <option value="07">7</option> <option value="08">8</option> <option value="09">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="birth_year" id="birth_year"> <option value="2010">2010</option> <option value="2009">2009</option> <option value="2008">2008</option> <option value="2007">2007</option> <option value="2006">2006</option> <option value="2005">2005</option> <option value="2004">2004</option> <option value="2003">2003</option> <option value="2002">2002</option> <option value="2001">2001</option> <option value="2000">2000</option> <option value="1999">1999</option> <option value="1998">1998</option> <option value="1997">1997</option> <option value="1996">1996</option> <option value="1995">1995</option> <option value="1994">1994</option> <option value="1993">1993</option> <option value="1992">1992</option> <option value="1991">1991</option> <option value="1990">1990</option> <option value="1989">1989</option> <option value="1988">1988</option> <option value="1987">1987</option> <option value="1986">1986</option> <option value="1985">1985</option> <option value="1984">1984</option> <option value="1983">1983</option> <option value="1982">1982</option> <option value="1981">1981</option> <option value="1980">1980</option> <option value="1979">1979</option> <option value="1978">1978</option> <option value="1977">1977</option> <option value="1976">1976</option> <option value="1975">1975</option> <option value="1974">1974</option> <option value="1973">1973</option> <option value="1972">1972</option> <option value="1971">1971</option> <option value="1970">1970</option> <option value="1969">1969</option> <option value="1968">1968</option> <option value="1967">1967</option> <option value="1966">1966</option> <option value="1965">1965</option> <option value="1964">1964</option> <option value="1963">1963</option> <option value="1962">1962</option> <option value="1961">1961</option> <option value="1960">1960</option> <option value="1959">1959</option> <option value="1958">1958</option> <option value="1957">1957</option> <option value="1956">1956</option> <option value="1955">1955</option> <option value="1954">1954</option> <option value="1953">1953</option> <option value="1952">1952</option> <option value="1951">1951</option> <option value="1950">1950</option> <option value="1949">1949</option> <option value="1948">1948</option> <option value="1947">1947</option> <option value="1946">1946</option> <option value="1945">1945</option> <option value="1944">1944</option> <option value="1943">1943</option> <option value="1942">1942</option> <option value="1941">1941</option> <option value="1940">1940</option> <option value="1939">1939</option> <option value="1938">1938</option> <option value="1937">1937</option> <option value="1936">1936</option> <option value="1935">1935</option> <option value="1934">1934</option> <option value="1933">1933</option> <option value="1932">1932</option> <option value="1931">1931</option> <option value="1930">1930</option> <option value="1929">1929</option> <option value="1928">1928</option> <option value="1927">1927</option> <option value="1926">1926</option> <option value="1925">1925</option> <option value="1924">1924</option> <option value="1923">1923</option> <option value="1922">1922</option> <option value="1921">1921</option> <option value="1920">1920</option> <option value="1919">1919</option> <option value="1918">1918</option> <option value="1917">1917</option> <option value="1916">1916</option> <option value="1915">1915</option> <option value="1914">1914</option> <option value="1913">1913</option> <option value="1912">1912</option> <option value="1911">1911</option> <option value="1910">1910</option> <option value="1909">1909</option> <option value="1908">1908</option> <option value="1907">1907</option> <option value="1906">1906</option> <option value="1905">1905</option> <option value="1904">1904</option> <option value="1903">1903</option> <option value="1902">1902</option> <option value="1901">1901</option> <option value="1900">1900</option> </select> </td> </tr> <tr> <td bgcolor="#EFEFEF">Email Address:*</span></td> <td bgcolor="#EFEFEF"><input name="email1" type="text" id="email1" size="32" maxlength="48" /></td> </tr> <tr> <td bgcolor="#FFFFFF">Create Password:*</span></td> <td bgcolor="#FFFFFF"><input name="pass1" type="password" id="pass1" size="32" maxlength="16" /> <span>Alphanumeric Characters Only</span></td> </tr> <tr> <td bgcolor="#EFEFEF">Confirm Password: *</span></td> <td bgcolor="#EFEFEF"><input name="pass2" type="password" id="pass2" size="32" maxlength="16" /> <span>Alphanumeric Characters Only</span></td> </tr> <tr> <td><input type="submit" name="submit" value="Sign Up!" /></td> </tr> </table> </form> <?php } ?> </div> <div id="footer"> <div class="left">© 2011</div> <div class="right"><a href="#">....</a><a href="#">....</a></div> <div class="clearer"> </div> </div> </div> </div> </div> </body> </html> Hello,
I hope it's ok to ask this question here. I have a registration script, but I'm not sure how to handle it efficiently and I have some questions about it. This is used in the page 'signup.php'. The class is called 'User'. I haven't noticed any errors or bugs. It would be very useful for me to be aware of my mistakes. public function regUser($uname,$upass,$upassverify) { $new_password = password_hash($upass, PASSWORD_DEFAULT); if(!password_verify($upassverify, $new_password)) { // passwords are not the same (I thought it would be better to do this after hashing, but maybe it doesn't matter or it's worse. I'm not sure about it) $info = 'pass_err'; } $stmt1 = $this->db->prepare("SELECT * FROM users WHERE username=:uname"); $stmt1->execute(array(':uname'=>$uname)); if($stmt1->rowCount() > 0) { // this username has already been used $info = 'user_err'; } if (!$info) { $stmt2 = $this->db->prepare("INSERT INTO users(username,password) VALUES(:uname, :upass)"); $stmt2->bindparam(":uname", $uname); $stmt2->bindparam(":upass", $new_password); $stmt2->execute(); // succesfully made an account $info = "success"; } header("Location:/signup.php?status=".$info); exit(); }Am I using the prepared statements as how I should be using them? Is this a safe way of handling my data or do you see vulnerabilities? I'm using PRG to prevent resubmission but I want to show a 'everything is fine' or 'oh no, something went wrong' to the one who is signinup. If I now go to signup.php?status=success, i see 'eveything is fine', without actually signing up, is there a better way to do this or can I somehow prevent everyone being able to see this? As you might have noticed in my last post, my English is not very good, sorry about that. Thanks, Fabian Edited September 17, 2019 by FabelHello, I am currently coding a site from scratch. I know i can use templates and everything else but i want the experience. The HTML I've had down for years but it seems PHP is getting a little elusive for me. I'm trying to create a registration form and when i test my site i keep getting parse errors and syntax errors... mainly regarding the use of {} and if/else. Any help would be appreciated. Most of the code is still incomplete, I have to go back and fill in some areas I've left blank for now, but i have commented using // Where the browser is kicking back my errors.
- “Any sufficiently advanced technology is indistinguishable from magic” (Arthur C. Clark, 1962)
<?php $con = Mysqli_connect("'', '', ''"); if (Mysqli_connect_errno()) { echo "Failed to connect to DB. Please check your connection info." . Mysqli_connect_errno; // Only if there is an error. } //Declaring Variable for Registration form $fname = ""; $lname = ""; $em = ""; $emc = ""; $pass = ""; $passc = ""; $date = ""; $error_array = ""; if (insert($_POST['register_button'])) { // To handle the registration form // First Name Values $fname = strip_tags($_POST['reg_fname']); $fname = str_replace(' ', '', $fname); $fname = ucfirst(strtolower($fname)); // Last Name Values $lname = strip_tags($_POST['reg_lname']); $lname = str_replace(' ', '', $lname); $lname = ucfirst(strtolower($lname)); // Registration Email Values $em = strip_tags($_POST['reg_email']); $em = str_replace(' ', '', $em); // Confirm Registration Email Values $emc = strip_tags($_POST['reg_emailc']); $emc = str_replace(' ', '', $emc); // Registrsation Password Values $pass = strip_tags($_POST['reg_pass']); // Registration Password Confirmation Values $passc = strip_tags($_POST['reg_passc']); // Registration Date Values $date = date("m-d-Y"); // Here is where the browser keeps kicking back parse errors if ($em == $emc) { } else { echo "Email and Confirmation Email must match"; } if (filter_var($em, FILTER_VALIDATE_EMAIL)) { $em = filter_var($em, FILTER_VALIDATE_EMAIL) } else { echo "Invlaid Format"; } ?>
I have this working code except I can't redirect to a thank you page when a new user registers. When they login it works without issue. I just don't know where or what to put for the registration part.
Here is my Code. Any help would be much appreciated.
<?php Hi There, I want to add a picture to an existing user. The sql looks like: CREATE TABLE `klanten` ( `id` int(4) unsigned NOT NULL auto_increment, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `level` int(4) default '1', `filename` varchar(255) not null, `mime_type` varchar(255) not null, `file_size` int not null, `file_data` mediumblob not null, primary key (id), index (filename) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; id, username, password and level are allready filled in. Now i need some code to go with <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> process.php: <?php require_once 'database.php'; function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if (count($errors) == 0) { // no errors, so insert the image $query = sprintf( "insert into klanten (filename, mime_type, file_size, file_data) values ('%s', '%s', %d, '%s')", mysql_real_escape_string($image['name']), mysql_real_escape_string($info['mime']), $image['size'], mysql_real_escape_string( file_get_contents($image['tmp_name']) ) ); mysql_query($query, $con); $id = (int) mysql_insert_id($con); // finally, redirect the user to view the new image header('Location: view.php?id=' . $id); exit; } ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> to add to an existing user. Can somebody help me here? Best regards, Martijn |