PHP - What Would Be The Best Way Of Checking User Input On A Multipage Registration?
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. Similar TutorialsHey guys and gals! This is my first post here and needing a bit of help with my php code! So here is the deal, i have 3 tables in ms sql 2000 which i will be using on this project. i have an employee table that has the regular information such as: TABLE employee( uniqueid, employee_number, lastname, firstname, dob, address, city, state, zip ) TABLE employee_docs( uniqueid, employee_number, doc_type int, date_received, date_issued, date_expired ) TABLE doc_type(uniqueid, description, valid_month) so basically from the employee_doc table, the doc_type column is an int and will have the description of the document as well as valid month column which will tell you how long the document type is valid until. the Description gives a brief description of what the product is. The uniqueid is used as what ever number is chose from the employee_docs table will represent the document type from table doc_type. ok so now that i gave a brief explanation of the tables i am working with, I can tell you what i need. i need a php page that will display: employee number, lastname, firstname, doc_type, date_received, date_issued, date_expired. Code: [Select] select pn.empnum as employeeid, (pn.lastname + ', ' + pn.firstname)as [Full Name], dt.description as doc_type, formatDate(pd.received) as [Date Received], formatDate(pd.expired)as [Date Expired], formatDate(pd.issued) as [Date In Service] from personnel_document pd left join document_types dt on (dt.uniqueid = pd.doc_type) left join personnel pn on (pd.empnum = pn.empnum) where pd.empnum = '$EmpNum' now, I went ahead and did this for the html part: Code: [Select] <table border=0> <tr> <td height=20px weight=1px valign=bottom><span class=underline>DESCRIPTION</span></td> <td height=20px weight=1px valign=bottom><span class=underline>DATE RECEIVED</span></td> <td height=20px weight=1px valign=bottom><span class=underline>LICENSE NUMBER</span></td> <td height=20px weight=1px valign=bottom><span class=underline>DATE IN SERVICE</span></td> <td height=20px weight=1px valign=bottom><span class=underline>DATE EXPIRED</span></td> </tr> <tr> </tr> <tr> <td height=20px valign=bottom><span class=label_text>PHYSICAL EXAM</span></td> <td valign=top><input class=demog_box type=text size=10 name= phexam_dr id=phexam_dr onBlur= 'formatDate(this)' value='<?php echo $phexam_dr; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= phexam_ln id=phexam_ln onBlur='formatDate(this)' value='<?php echo $phexam_ln; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= phexam_is id=phexam_is onBlur= 'formatDate(this)' value='<?php echo $phexam_is; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= phexam_ex id=phexam_ex onBlur='formatDate(this)' value='<?php echo $phexam_ex; ?>'> </td> </tr> <tr> </tr> <tr> <td height=20px valign=bottom><span class=label_text>PROFESSIONAL LICENSE</span></td> <td valign=top><input class=demog_box type=text size=10 name= prolic_dr id=prolic_dr onBlur='formatDate(this)' value='<?php echo $prolic_dr; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= prolic_ln id=prolic_ln onBlur='formatDate(this)' value='<?php echo $prolic_ln; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= prolic_is id=prolic_is onBlur='formatDate(this)' value='<?php echo $prolic_is; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= prolic_ex id=prolic_ex onBlur='formatDate(this)' value='<?php echo $prolic_ex; ?>'> </td> </tr> <tr> </tr> <tr> <td height=20px valign=bottom><span class=label_text>PROFESSIONAL INSURANCE</span></td> <td valign=top><input class=demog_box type=text size=10 name= proins_dr id=proins_dr onBlur='formatDate(this)' value='<?php echo $proins_dr; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= proins_ln id=proins_ln onBlur='formatDate(this)' value='<?php echo $proins_ln; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= proins_is id=proins_is onBlur='formatDate(this)' value='<?php echo $proins_is; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name= proins_ex id=proins_ex onBlur='formatDate(this)' value='<?php echo $proins_ex; ?>'> </td> </tr> <tr> </tr> <tr> <td height=20px valign=bottom><span class=label_text>DRIVER'S LICENSE</span></td> <td valign=top><input class=demog_box type=text size=10 name=dl_dr id=dl_dr onBlur='formatDate(this)' value='<?php echo $dl_dr; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name=dl_ln id=dl_ln onBlur='formatDate(this)' value='<?php echo $dl_ln; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name=dl_is id=dl_is onBlur='formatDate(this)' value='<?php echo $dl_is; ?>'> </td> <td valign=top><input class=demog_box type=text size=10 name=dl_ex id=dl_ex onBlur='formatDate(this)' value='<?php echo $dl_ex; ?>'> </td> </tr> <tr> </tr> <tr> </table> I am now doing the the sql statement to insert into my db but i am stuck. i basically want to get the information that the user enters for each field and save it on the employees profile. $querydoc = "update personnel_document set empnum = '$EmpNum' , doc_type = ???, date_received = ????, date_expired = ????, date issued = ??? where empnum = '$EmpNum' "; The problem is that since each description has a different variable im not sure how to update it.... would I have to create a new update for each description? also I hard coded the name of each description but i believe it is better if i echo the description name from the db as i cant use taht as the doc_type... i am pretty confused, if anyone has a better way of doing this i would really appreciate it! eventually i also want to make sure that the description is expired to to with the fields I have there and promp the user of something that is expired. Once again, any help given is much appreciated!!! New 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? 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
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! 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 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? 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! 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); ?> 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? 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> 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 :/ So basically I have a site, and on that site, I have a page that submits a form and updates a database. I have it set up so that someone can enter in Multiple values into a textarea, one on each line, and it will submit each of those values as a new row in the database, but for the life of me, I cannot figure out how to check those values against the actual users. It is basically a point system, where the staff can award points users of the site. But at the moment, a Staff member could enter in Jibberish, and it would insert that into the database, but I want it to check my users table to make sure the user exists before it inserts it into the database. here is my code: <?php include 'global.php'; echo $headersidebar; if ($_COOKIE['access'] == $accessstaff) { if(count($_POST)) { $array = preg_split('/(\r?\n)+/', $_POST['studentname']); foreach($array as $students) { $statusmsg = '<center><span style="background: #A6FF9E;">You have successfully submitted points to the database.</span></center>'; mysql_query("INSERT INTO points (giver, receiver, points, category, reason, date, status) VALUES ('{$_COOKIE['username']}', '{$students}', '{$_POST['pointamt']}', '{$_POST['pointcat']}', '{$_POST['pointreason']}', '{$date}', 'Validating')"); } } $addpointspage = $statusmsg . ' <form action="submit_points.php" method="post"> <table class="table" > <tr> <td colspan="10"> <h1><strong><center>Submit Points</center></strong></h1> </td> </tr> <tr> <td colspan="10" rowspan="100"> <center>Please remember to follow the house point limits when submitting house points.</center> </td> </tr> </table> <table class="table"> <tr> <td style="width: 15%;" valign="top"> Student Name:<br> <span style="font-size: 60%;">(List as many as you want; One per Line)</span> </td> <td colspan="10"> <center><textarea name="studentname" cols="60" rows="10"></textarea></center> </td> </tr> <tr> <td style="width: 15%;" valign="top"> Amount of Points: </td> <td> <input style="position: relative; left: 16px;" type="text" size="15" name="pointamt" /> </td> <td> Do not put anything that is not a number into this box. </td> </tr> <tr> <td style="width: 15%;" valign="top"> Point Category: </td> <td colspan="10"> <select name="pointcat" style="position: relative; left: 16px;"> <option SELECTED value="">-------</option> <option>Class Work</option> <option>Class Exam</option> <option>Extra Work</option> <option>Contests</option> <option>Teacher\'s Assistant</option> <option>Negative Points</option> </select> </td> </tr> <tr> <td style="width: 15%;" valign="top"> Reason: </td> <td colspan="10"> <input style="position: relative; left: 16px;" name="pointreason" type="text" size="80" /> </td> </tr> <tr> <td> </td> <td colspan="10"> <input style="position: relative; left: 16px;" type="submit" value="Submit Points" /> </td> </tr> </table </form> '; } elseif (1==1) { $addpointspage = $accessdenied; } echo ' <!-- start content --> <div id="content"> <div class="post"> <div class="entry"> <p><strong>' . $addpointspage . '</p> <p class="links">' . $addpointslink . '</p> </div> </div> </div> <!-- end content --> <div style="clear: both;"> </div> </div> <!-- end page --> </div>'; echo $footer; ?> I am fairly new to PHP, so I would appreciate any help someone could give me; I am not too good with arrays and such, so this one has got me stumped. This code logs the user in with the correct user_email, user_pwd, and active=1. A '0' is inserted into the active column of the users table during registration. I need help checking if active=0 then flash_warning('User account not activated'). login_user.php Code: [Select] <?php include(MODEL_PATH.'user.php'); switch ($route['view']){ case "login_user": if(login($params['user']['user_email'], $params['user']['user_pwd'])) { flash_notice('You are logged in!'); redirect_to(''); } else { flash_warning('Username or password is invalid!'); $route['view'] = 'login'; } break; }user.php Code: [Select] <?php session_start(); function login($username, $password) { db_connect_posts(); $query = sprintf("SELECT * FROM users WHERE user_email = '%s' AND user_pwd = '%s' AND active = '1'" , mysql_real_escape_string($username), md5($password) ); $result = mysql_query($query); $number_of_posts = mysql_num_rows($result); if($number_of_posts == 0) { return false; } $row = mysql_fetch_array($result); $_SESSION['user'] = $row; return true; } ?>Login form Code: [Select] <form action="<?php echo '/'.APP_ROOT.'/'; ?>sessions/login_user" method="post"> <fieldset> <legend>Login</legend> <div> <label>E-mail</label> <input name="user[user_email]" size="40" type="text" /> </div> <div> <label>Password</label> <input name="user[user_pwd]" size="40" type="password" /> </div> <input type="submit" value="Login" /> </fieldset> </form> Hi i have a simple script that functions perfect and easy but i am looking for a way to secure it a little
is there any way for me to create a simple user checking system ?
i have a mysql db with both usernames and passwords
is there any way to get the username and password from a get comand in the url and check the db to see if they exist and if they do run the rest of my code and if not throw access denied ?
i know this is not 100% secure but i its how i want it to be done
could anyone help me with this ?
I am trying to check for an admin user to access the admin panel. I have been playing around try different things and this what I have ended up with in my database table I have a column called usergroup and i do the follow to check for admin user. Code: [Select] $checkAdmin = mysql_query("SELECT * FROM `users` WHERE email='$email' , usergroup = 'admin'"); $adminUser = mysql_num_rows($checkAdmin); if ($adminUser == 0) { echo count($adminUser); die ('You do not have permissions to access this area'); } I do the select statement through phpmyadmin and it comes back with one row. which is basically hat i want to check for. I do have a variable called $email which is getting a value from the email cookie. currently $adminUser Return a value of 10. All of the count() functions is for testing purposes only. 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; ?> This is something that has intrigued me, that has only recently surfaced when viewing the forum. Which of the following methods of authenticating that a user exists would be better/faster/ect? Example 1 - Fetching Row Data <?PHP $username = 'LoserVille'; $password = 'password'; $myQuery = mysql_query("SELECT account_id FROM user_accounts WHERE username = '$username' AND password = '$password'"); $myQuery = mysql_fetch_assoc($myQuery); if($myQuery) { /*### User Exists ###*/ } else { /*### User Does Not Exist ###*/ } ?> Example 2 - Fetching Number of Results <?PHP $username = 'LoserVille'; $password = 'password'; $myQuery = mysql_query("SELECT account_id FROM user_accounts WHERE username = '$username' AND password = '$password'"); $myQuery = mysql_num_rows($myQuery); if($myQuery >= 1) { /*### User Exists ###*/ } else { /*### User Does Not Exist ###*/ } ?> Just looking for some insight, not really a problem Regards, PaulRyan. Hi, I'm trying to figure out the best way to determine if a user is currently downloading a file from my website. The way my site works, is the user waits 30 seconds and views an ad. After the timer is up the download becomes available. I heard that I could probably use a timestamp or something of the sort. I've read up on it but not sure how I could go about this. |