PHP - How To Handle Sessions In Sign Up Registration Page In Php Using Mysql ?
Please help me out with sessions . I m new to this topic.
Similar TutorialsI am trying to build my own custom login script. What I am trying to achieve is once a user has logged in depending on wether they have checked the keep me logged in checkbox they have two options. If they haven't checked it then it creates session variables only, and if they have checked it it also creates cookie variable as well as the session variables. If they then close their browser / tab without logging out and then revisit the site they will get redirected to login page because the active session variable is no longer there. As soon as they land on the loggin page, it automatically checks for the cookie variable and if it exists, it uses it to login and redirect them automatically. However the problem that I am facing is that the session variable is still being trashed after a default amount of idle time and forcing a login. My goal is that the user shouldn't have to re-login unless they have either clicked the logout button. Can someone please have a look through my solution and advise me as to wether this is the correct method that I am implementing, if there is an easier way to achieve what I want, and is this a secure way to handle user logins. Thanks in advance. Andrew Here is the check code I have placed at the top of each admin page. Code: [Select] <?php session_start(); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $uid = $_SESSION['uid']; if (!isset($uid)) { header('location:login.php?redirect='.$url); exit(); } ?> Next we have the code for the login.php file. Code: [Select] <?php include ('functions.php'); ?> <?php get_header('login'); ?> <div id="login-result"> <?php connect(); $redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect']))); if(isset($_COOKIE['remembered'])){ $username = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['username']))); $password = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['password']))); $sql = "SELECT * FROM usersT WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); $row = mysql_fetch_array($result); $uid = $row['uid']; $fname = $row['firstname']; $lname = $row['lastname']; $role = $row['role']; if($count==1){ $sql2 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result2 = mysql_query($sql2); if($result2){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } else if (isset($_POST['admin_login'])){ if(isset($_POST["username"]) && isset($_POST["password"])){ $username_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"]))); $password_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"]))); $psw = md5($password_p); $sql3 = "SELECT * FROM usersT WHERE username='$username_p' AND password='$psw'"; $result3 = mysql_query($sql3); $count3 = mysql_num_rows($result3); $row3 = mysql_fetch_array($result3); $uid = $row3['uid']; $fname = $row3['firstname']; $lname = $row3['lastname']; $role = $row3['role']; if($count3==1){ $sql4 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result4 = mysql_query($sql4); if($result4){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(isset($_POST['remember'])) { setcookie("remembered[username]", $username, time() + 86400 * 365 * 2); setcookie("remembered[password]", $psw, time() + 86400 * 365 * 2); } if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } } ?> </div><!-- / login-results --> <div id="login" class="rounded5 shadow"> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label for="username">Username<br> <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label> </p> <p> <label for="password">Password<br> <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" /></label> </p> <p class="submit"> Keep me logged in<input type="checkbox" name="remember" id="remember" /><br /><br /><a href="" class="left">Lost your password?</a> <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" /> </p> <div class="cleaner"></div><!-- / cleaner --> </form> </div><!-- / login--> <?php get_footer('login'); ?> Finally here is the code I am using for the logout.php page. Code: [Select] <?php session_start(); include ('functions.php'); connect(); $uid = mysql_real_escape_string($_SESSION['uid']); $sql = "UPDATE usersT SET status = '0' WHERE uid = '$uid'"; $result = mysql_query($sql); if($result) { session_unset(); session_destroy(); if(isset($_COOKIE['remembered'])){ setcookie("remembered[username]", $username, time() - 3600); setcookie("remembered[password]", $psw, time() - 3600); header("location: login.php"); } exit(); } else { echo "You couldn't be logged out at this time."; } ?> Hello All, I have a custom session.set_save_handler to handler sessions for my application. It seems to work fine. The database table is of type innodb. I see some errors in my log file of the nature, "(1205) Lock wait timeout exceeded; try restarting transaction". I have a class which contains the session handler callbacks and have made it a singleton class. session_set_save_handler( array($this, "db_open"), array($this, "db_close"), array($this, "db_read"), array($this, "db_write"), array($this, "db_destroy"), array($this, "db_gc") ); In my "db_read" method, I am doing a "SELECT FOR UPDATE" on the row with the session id. So, while performing load testing on my app. which has a lot of ajax calls, I noticed the "lock wait timeout" errors. How do I resolve this problem? Any suggestions? 1) Should I catch these errors and issue a explicit "commit" in the read or write methods? 2) Should I specify a higher timeout value for "innodb_lock_wait_timeout"? Thanks this code is to create a new user based on posted variables. it works fine for creating the necessary tables and granting privileges. but then when i log out as root and try to log back in as the user it's failing. why is it failing? Thanks, G. Code: [Select] <?php extract( $_POST ); include( '../php/userobject.php' ); @ $db = mysqli_connect('localhost', 'root', 'xxxxxx', 'mealchamp'); if ( mysqli_connect_errno() ) { echo 'Error: could not connect to database as root.<br />'; exit; } else echo 'Connected to database as root.<br />'; $query = "SELECT username FROM userlist WHERE username = $uname"; $result = mysqli_query($db, $query); if ($result) echo 'That user name is already taken.<br/>Please hit back on your browser, and try a different user name.<br/>'; else { echo 'That username is available.<br/>'; echo "$fname<br/>"; echo "$lname<br/>"; echo "$add1<br/>"; echo "$add2<br/>"; echo "$city<br/>"; echo "$prov<br/>"; echo "$ctry<br/>"; echo "$post<br/>"; echo "$email<br/>"; echo "$uname<br/>"; echo "$pass1<br/>"; echo "$sex<br/>"; echo "$birth<br/>"; echo "$height<br/>"; echo "$weight<br/>"; $query = "INSERT INTO userlist (firstname, lastname, address1, address2, city, province, country, postal, email, username, password, sex, birth, height, weight) VALUES ('$fname', '$lname', '$add1', '$add2', '$city','$prov', '$ctry', '$post','$email','$uname', '$pass1', '$sex', '$birth', '$height', '$weight')"; $result = mysqli_query($db, $query); if ($result) echo "Userlist was updated successfully<br />"; else echo "Could not update userlist"; $query = "CREATE TABLE ".$uname."_persfood (persfoodid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, food VARCHAR(30) NOT NULL)"; $result = mysqli_query($db, $query); if ($result) echo "Personal food table was created successfully<br />"; else echo "Could not create personal food table<br />"; $query = "GRANT select ON mealchamp.userlist TO ".$uname." IDENTIFIED BY '$pass1'"; $result = mysqli_query($db, $query); if ($result) echo "User priveleges were granted successfully<br />"; else echo "Could not grant user priveleges<br />"; $query = "GRANT select, insert, update, delete, index ON mealchamp.".$uname."_persfood TO ".$uname." IDENTIFIED BY '$pass1'"; $result = mysqli_query($db, $query); if ($result) echo "User priveleges were granted successfully<br />"; else echo "Could not grant user priveleges<br />"; mysqli_close($db); @ $db = mysqli_connect('localhost', $uname, $pass1, 'mealchamp'); if ( mysqli_connect_errno() ) { echo 'Error: could not connect to database as user.<br />'; exit; } else { echo 'Connected to database as user.<br />'; ?> Hello, Im sure this is an easy one, but I just cant get my head around this. Where my results are displayed and there is a result without a webaddress or email address, I dont want "br" to be output. I pressume I need an If / else if statement for $row, but Im unsure of how I would incorporate this into my array? and im also unsure of how to say IF $row == NULL, - dont display anything. Code: [Select] <?php $subtype = $_GET['subtype']; echo "<h1>$subtype</h1>"; $result = mysql_query("SELECT name, phone, email, WebAddress, postcode FROM business WHERE subtype ='$subtype' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($row = mysql_fetch_array($result)) { echo $row['name'] . "<br>"; echo $row ['phone'] . "<br>"; echo $row['email'] . "<br>"; echo $row['WebAddress'] . "<br>"; echo $row['postcode'] ; $postcode = str_replace(' ','+',$row['postcode']); echo "<p class=link><a href='/gmap.php?postcode=$postcode'>Map</a></p><br>"; } ?> Hi there, im trying to create a sign up page for my site! I have used confirm password and email fields on the form but the code still shows the error message even if the passwords and emails match! Can anyone advice me please? $username = $_POST['username']; $password = $_POST['password']; $month = $_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $query = mysql_query("INSERT INTO users VALUES ('','$username','$password','$month','$day','$year') mysql_query($query); The code above is a sample of what I have but what I want is to store an entire birthdate in ONE SQL cell. More like this... $username = $_POST['username']; $password = $_POST['password']; $month = $_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $query = mysql_query("INSERT INTO users VALUES ('','$username','$password','$birthdate') mysql_query($query); How is this possible? Can I do this and actually use it efficiently in the future? Hi All. New at this, form is working perfect, then added recapthca, now it only handles recaptcha and not the form. not sure where the error is
I have a script that takes a 2 or 3 page pdf, uploads it and hashes the file name to something that isn't guessable. We now want to add an image of each of the PDF for users who don't have Adobe Reader. Some pdf's will be 2 and some 3 pages. Should I: A) Let convert name the different pages "*-0.jpg, *-1.jpg..." and then use a recursion function (it's already written for another reason) to crawl the folder, B) Use a PHP/PDF library to determine the number of pages, then add the value to the database's corresponding row. C) Use a hybrid of both D) Any better ideas??? Thanks I have practically no experience with PHP but I know how to use mysql. Anyway I am trying to set up registration for a game through my website, so would something simple like this work, provided I can figure how to tell it what database and table to input the information in?
so the user is reading a story, to finish reading he has to click a link that redirects them to the signup page. Code: [Select] <?php session_start(); $beginurl = $_SERVER['HTTP_REFERER']; $_SESSION['beginurl'] = $beginurl; echo $_SESSION['beginurl']; ?> <html> <head> </head> <body> <script type="text/javascript"><!-- location.replace("http://www.mysite.com/members/"); //--></script> </body> </html> When they get to the second page, they have to click a link that opens up a modal. this is the code that runs when they hit the register button Code: [Select] session_start(); $beginurl = $_SESSION['beginurl']; $beginurl= (isset($_SESSION['beginurl'])) ? $_SESSION['beginurl'] : 'Error'; if( $_SESSION['status'] ='authorized') $_SESSION['$makemodal'] = 0; //sends the user to the page upon successful password credential if(!isset($_SESSION['SESS_USERID'])||(trim($_SESSION['SESS_USERID']=='admin'))) { echo '<script language="javascript">'; echo "top.location.href = $beginurl"; echo '</script>'; exit(); } Am I passing this variable correctly? and I'm not sure if the top.location.href towards the bottom is correct either, right now after I hit the register button I'm redirected to a blank page where the url is, "http://www.mysite.com/function Error() { [native code]}" Register.php Code: [Select] <?php $page_title = "Register"; $rank_check = 0; include "header.inc.php"; if (!$remember_day) { $remember_day = "DD"; } if (!$remember_month) { $remember_month = "MM"; } if (!$remember_year) { $remember_year = "YYYY"; } if ($remember_gender == 1) { $rememberFemale = " SELECTED"; } else { $rememberMale = " SELECTED"; } print "$openHTML"; ECHO <<<END <P align="center"><FORM ACTION=$base_url/register.pro.php METHOD=POST> <CENTER><FONT SIZE="-2" COLOR="#FF0000"><B>*</B></FONT><FONT SIZE="-1">Information checked with a red star means that information<br> is required to register here on Music World Anonymous!</FONT> <P><TABLE CELLSPACING=0 CELLPADDING=0 WIDTH=450> <TR> <TD COLSPAN=2 BGCOLOR="$topAndBottomBG"> <P><FONT SIZE="-1" COLOR="$topAndBottomText"><B>Account Information:</B></FONT></P> </TD> </TR> <TR BGCOLOR="#FFFFFF"> <TD WIDTH=130> <P><FONT SIZE="-1"><B>Username: </B></FONT><FONT SIZE="-1" COLOR="#FF0000"><B>*</B></FONT><FONT SIZE="-1"><BR> &#149; 20 Char. Limit<BR> &#149; a-z and 0-9 only!<BR> &#149; </FONT><A HREF="javascript:;" onclick="window.open('check_names.php','checknames',config='height=250,width=250,menubar=no,resizable=yes,directories=no,scrollbars=no,status=yes,toolbar=no'); return false;"><FONT SIZE="-1">See if it's available!</FONT></A></P> </TD> <TD> <P> <INPUT TYPE=text NAME="reg_username" VALUE="$remember_username" SIZE=32 MAXLENGTH=20></P> </TD> </TR> <TR BGCOLOR="$reallyLight"> <TD WIDTH=130> <P><FONT SIZE="-1"><B>Display Name: </B></FONT><FONT SIZE="-1"><BR> &#149; 25 Char. Limit<BR> &#149; Same as username, Add spaces and CaPs!</FONT></P> </TD> <TD> <P> <INPUT TYPE=text NAME="reg_display_name" VALUE="$remember_display_name" SIZE=32 MAXLENGTH=25></P> </TD> </TR> <TR BGCOLOR="#FFFFFF"> <TD WIDTH=130> <P><FONT SIZE="-1"><B>Password: </B></FONT><FONT SIZE="-1" COLOR="#FF0000"><B>*</B></FONT><FONT SIZE="-1"><BR> &#149; CaSe SenSitIVe!</FONT></P> </TD> <TD> <P> <INPUT TYPE=password NAME="reg_pass1" SIZE=32></P> </TD> </TR> <TR BGCOLOR="$reallyLight"> <TD WIDTH=130> <P><FONT SIZE="-1"><B>Confirm Password: </B></FONT><FONT SIZE="-1" COLOR="#FF0000"><B>*</B></FONT><FONT SIZE="-1"><BR> &#149; CaSe SenSitIVe!<BR> &#149; Must match previous password!</FONT></P> </TD> <TD> <P> <INPUT TYPE=password NAME="reg_pass2" SIZE=32></P> </TD> </TR> <TR BGCOLOR="#FFFFFF"> <TD WIDTH=130 HEIGHT=20> <P><FONT SIZE="-1"><B>Name: </B></FONT></P> </TD> <TD> <P> <INPUT TYPE=text NAME="reg_full_name" VALUE="$remember_name" SIZE=32></P> </TD> </TR> <TR BGCOLOR="$reallyLight"> <TD WIDTH=130 HEIGHT=20> <P><FONT SIZE="-1"><B>Email Address: </B></FONT><FONT SIZE="-1" COLOR="#FF0000"><B>*</B></FONT></P> </TD> <TD> <P> <INPUT TYPE=text NAME="reg_email" VALUE="$remember_email" SIZE=32></P> </TD> </TR> <TR BGCOLOR="#FFFFFF"> <TD WIDTH=130 HEIGHT=20> <P><FONT SIZE="-1"><B>Location:</B></FONT></P> </TD> <TD> <P> <INPUT TYPE=text NAME="reg_location" VALUE="$remember_location" SIZE=32></P> </TD> </TR> <TR BGCOLOR="$reallyLight"> <TD WIDTH=130 HEIGHT=20> <P><FONT SIZE="-1"><B>Birthday: </B></FONT></P> </TD> <TD> <P> <INPUT TYPE=text NAME="reg_month" VALUE="$remember_month" SIZE=4> <INPUT TYPE=text NAME="reg_day" VALUE="$remember_day" SIZE=4> <INPUT TYPE=text NAME="reg_year" VALUE="$remember_year" SIZE=7> </P> </TD> </TR> <TR BGCOLOR="#FFFFFF"> <TD WIDTH=130> <P><FONT SIZE="-1"><B>Gender: </B></FONT></P> </TD> <TD> <P> <SELECT NAME=reg_gender> <OPTION value=1$rememberFemale>Female</OPTION> <OPTION value=2$rememberMale>Male</OPTION> </SELECT></P> </TD> </TR> <TR BGCOLOR="#FFFFFF"> <TD WIDTH=130> <P><FONT SIZE="-1"><B>Bio:</B></FONT></P> </TD> <TD> <P> <TEXTAREA NAME=reg_bio ROWS=6 COLS=34 WRAP=virtual>$remember_bio</TEXTAREA></P> </TD> </TR> </TABLE> </P> <P><FONT SIZE="-1">All information is provided here is safe. No personal information will ever be sold for any reason. Read our </FONT><A HREF="privacy.php"><FONT SIZE="-1">Privacy Policy</FONT></A><FONT SIZE="-1"> for more information.</FONT></P> <P><FONT SIZE="-1">By registering an account here you agree to all of our </FONT><A HREF="tos.php"><FONT SIZE="-1">Terms and Conditions</FONT></A><FONT SIZE="-1">!</FONT></P> <P><FONT SIZE="-1"><INPUT TYPE=submit NAME=Submit VALUE="Register! :)"></FONT></CENTER> </FORM></P> END; print "$closeHTML"; ?> Register.pro.php Code: [Select] <?php include "config.inc.php"; $rememberInfo = "?remember_username=$remember_username&remember_display_name=$reg_display_name&remember_name=$reg_full_name&remember_email=$reg_email&remember_location=$reg_location&remember_month=$reg_month&remember_day=$reg_day&remember_year=$reg_year&remember_bio=$reg_bio"; if ((!$remember_username) OR (!$reg_pass1) OR (!$reg_pass2) OR (!$reg_email)) { die(header(error("register.php$rememberInfo","Please fill in all required information."))); } $reg_username = strtolower($reg_username); $check_username = fetch("SELECT id FROM members2 WHERE username = '$reg_username'"); if ($check_username[id]) { die(header(error("register.php$rememberInfo","The username you have selected alredy exists. Please try again."))); } if ($reg_pass1 != $reg_pass2) { die(header(error("register.php$rememberInfo","Your passwords did not match. Passwords ARE CaSe SenSitIVe."))); } if (!$reg_display_name) { $reg_display_name = $reg_username; } $newDisplay = strtolower(ereg_replace(" ","","$reg_display_name")); if ($newDisplay != $reg_username) { die(header(error("register.php$rememberInfo","Your display name must contain the exact same letters as your username with the exception of spaces and capitals."))); } $mwa22pass = md5($reg_pass1); if ( ($this_year-$reg_year >= 13) OR (($this_year-$reg_year == 12) AND ($this_month-$reg_month >= 1)) OR (($this_year-$reg_year == 12) AND ($this_month-$reg_month == 0) AND ($today-$reg_day >= 0))) { $rank = 3; } else { $rank = 2; } if (($reg_month < 1) OR ($reg_month > 12) OR ($reg_day < 1) OR ($reg_day > 31) OR ($reg_year < 0) OR ($reg_year > $this_year)) { die(header(error("register.php$rememberInfo","Please choose a VALID bithdate."))); } $reg_username = badwords($reg_username); if (($reg_gender != "1") AND ($reg_gender != "2")) { die(header(error("register.php$rememberInfo","Please choose a VALID gender."))); } $reg_bio = smilies(badwords(strip_tags($reg_bio,"<b><i><u><a><font><img><p><br><body><background>"))); $reg_sig = badwords(strip_tags($reg_sig,"<b><i><u><a><font>")); if (preg_match('/^[a-z0-9_]*$/UD',$reg_username)) { $insertMemberID = mysql_insert_id(); mysql_query("INSERT INTO members2 (username,password,display_name,rank,email,name,birthday,account_made,location,gender,bio) VALUES ('$reg_username','$mwa22pass','$reg_display_name','$rank','$reg_email','$reg_full_name','$reg_month-$reg_day-$reg_year','$timestamp','$reg_location','$reg_gender','$reg_bio'')"); } else { die(header(error("register.php$rememberInfo","Your username can only contain a-z, 0-9 and underscores. Please try again."))); } setcookie("54865421545_mwauser",$reg_username,time()+2678400); setcookie("14182525mwapass_mwauser",$mwa22pass,time()+2678400); die(header(error("index.php$rememberInfo","Thank you for registering. :D"))); ?> It always says that the required info is not filled in - when it actually is. So then noone can make an account because of it. Required fields a name, email, password, password2 (the one you confirm). If you need more info feel free to ask. Hi Does anyone know any good tutorials for creating a registration page for a website? Thanks in advance. Can anyone explain how i can create a registration and login page using PHP that doesnt use databases, sessions, or cookies? Is there a tutorial someone can point me to or could anyone tell me the method. Thanks first time php coder ok well my registration page is supposed to send out an email so the user can activate his or her account , but it will not send! i am using xampp for my local webhost and my php.ini settings are [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = relay.jangosmtp.net ; http://php.net/smtp-port smtp_port = 587 ; For Win32 only. ; http://php.net/sendmail-from sendmail_from = activate.social@gmail.com sendmail_path="\"C:\xampp\sendmail\sendmail.exe\"-t and my sendmail.ini is account Gmail tls on tls_certcheck off host relay.jangosmtp.net from activate.social@gmail.com auth on user activate.social@gmail.com password mypassword port 587 account default : Gmail and now here is my php script that sends the mail but it wont send , the reason i put those .ini files in here is because that is what xampp uses to send mail. here is the php script Code: [Select] <?php $to = "$email1";// which is established further up on the script which is to big! $from = 'activate.social@gmail.com'; // same email used in php.ini and sendmail.ini but wont send $subject = 'Complete Your ' . $dyn_www . ' Registration'; //Begin HTML Email Message $message = "Hi $username, Complete this step to activate your login identity at $dyn_www Click the line below to activate when ready http://$dyn_www/activation.php?id=$id&sequence=$db_password If the URL above is not an active link, please copy and paste it into your browser address bar Login after successful activation using your: E-mail Address: $email1 Password: $pass1 See you on the site!"; //end of message $headers = "From: $from\r\n"; $headers .= "Content-type: text\r\n"; mail($to, $subject, $message, $headers); // supposed to send but wont ?> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=350931.0 Hello users: I am exploring the delightful world of PHP for web applications. I am in the stage where I need to use SESSIONS and COOKIES and MYSQL for a user/membership/profile structure. I understand most of the grammar behind PHP and am excited to apply this in application. I am searching for recommendations and comments about using: 1. COOKIES 2. SESSIONS 3. MYSQL/SQL Almost every website has an authentication mechanism, profile, and use information. My website required this similar structure, but I have been having some problems completing all of the technical steps for production. If anyone has code samples or places where I can review code on this topic, that would be wonderful. I am specifically searching for more advanced topics in these area for general robustness. Please kindly send me a message or respond to this post. Regards, Diamond Edited by Diamond, 30 December 2014 - 04:27 PM. I have a user registration page that requires the user to input a Username, Password, Confirm Password, Email. If the user passes all the validation requirements for the new account, I then need to have the username, password, email fields saved to a file called 'login.dat'
Here is my code that I have so far, it runs perfectly.
<?php include 'helpfulfunctions.inc'; include 'productsdata.inc'; $user_login_file = 'login.dat'; //var_dump($_POST); // product data for photo, name, and price. $alluserinfo = load_users_info($user_login_file); //validate users info $errors = array(); if (array_key_exists('register_submit', $_POST)) { //check to see if username is taken $username_entered = $_POST['username']; //check to see if username already exists if (array_key_exists($username_entered, $alluserinfo)) { $errors['username']['username_exists'] = "Username already exists."; } //validate username is 4-11 characters long using only a-z A-Z 0-9 if(preg_match("/^[0-9a-zA-z]{4,11}$/",$_POST['username']) ===0){ $errors['username']['invalid_username']= "Invalid username. Username must be 4-11 characters long and use only letters and numbers."; } //validate password "." means any character //.* allows numbers 0-9 to be inserted anywhere //?= positive lookahead: next text must be like this and follow these rules // must be at least 6 characters, contain 0-9, a-z, A-Z $pw_entered=$_POST['password']; if(preg_match("/^.*(?=.{6,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0){ $errors['password']['invalid_password']="Password must be at least 6 characters and must contain at least one lower case letter, one upper case letter and one digit."; } //validate that "confirm password" matches password above $pw_repeat=$_POST['confirmpassword']; if($pw_repeat != $pw_entered){ $errors['confirmpassword']['pw_no_match']="Passwords do not match. Try again."; } //validate email format $email_entered=($_POST['email']); if(!filter_var($email_entered, FILTER_VALIDATE_EMAIL)){ $errors['email']['invalid_email']="Not a valid email. Please try again."; } //no validation errors=>print invoice if (empty($errors)) { include 'invoice.inc'; exit; } } //reprint if invalid entry. if no errors print invoice ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <h3>Please register to continue.</h3> <table> <tr> <td> *Username: </td> <td> <input type="text" name="username"/> <?php if (isset($errors['username'])) { print implode('<br>', $errors['username']); } ?> </td> </tr> <tr> <td> *Password: </td> <td> <input type="password" name="password"/> <?php if (isset($errors['password'])) { print implode('<br>', $errors['password']); } ?> </td> </tr> <tr> <td> *Confirm Password: </td> <td> <input type="password" name="confirmpassword"/> <?php if (isset($errors['confirmpassword'])) { print implode('<br>', $errors['confirmpassword']); } ?> </td> </tr> <tr> <td> *Email: </td> <td> <input type="text" name="email"/> <?php if (isset($errors['email'])) { print implode('<br>', $errors['email']); } ?> </td> </tr> <tr> <td> * required info <br> <input type="submit" value="Register" name="register_submit"> <?php //print out hiddens with quantities save_hidden_qty($_POST['quantity']); ?> </form> </td> </tr> </table>In case it's needed, this is the 'helpfulfunctions.inc' file and the included functions: <?php if (!function_exists('load_users_info')) { function load_users_info($users_data_file) { $fp = fopen($users_data_file, 'r'); //read all lines of login.dat file and create user info arrays while (!feof($fp)) { $users_info_line = fgets($fp); $user_info_parts = explode(',', $users_info_line); $user_info_array = array('username' => $user_info_parts[0], 'password' => $user_info_parts[1], 'email' => $user_info_parts[2]); $complete_user_info_array[$user_info_array['username']] = $user_info_array; } fclose($fp); return $complete_user_info_array; } } // function to display products if (!function_exists('display_products')) { function display_products($products_to_display, $quantities = array()) { global $errors; ?> <table border="1"> <tbody> <tr> <td style="text-align: center;"><b><big>Product</big></b></td> <td style="text-align: center;"><b><big>Brand</big></b></td> <td style="text-align: center;"><b><big>Price(each)</big></b></td> <td style="text-align: center;"><b><big>Quantity Desired</big></b></td> </tr> <?php // quantities are 0 unless already inputted, if quantities previously were inputted, return the values. // input boxes for ($i = 0; $i < count($products_to_display); $i++) { if (empty($quantities)) { $qty = isset($_POST['quantity'][$i]) ? $_POST['quantity'][$i] : 0; $qty_str = "<input type=text size=3 maxlength=3 name='quantity[$i]' value='$qty'>"; if (isset($errors['quantity'][$i])) { $qty_str .= "<span style='font-style:italic;font-size:8px;color:red;'>{$errors['quantity'][$i]}</span>"; } } else { $qty_str = $quantities[$i]; } // loop to print out table of photo of board, name of the brand, price, and quantity selected printf(' <tr> <td><img alt="Small" id="lightboxImage" style="width: 119px; height: 88px; bgcolor="#cccccc;" src="http://imgur.com/%s" height="300" width="300"></td> <td style="text-align: center;">%s</td> <td style="text-align: center;">$%.2f</td> <td style="text-align: center;">' . $qty_str . '</td> </tr> ', $products_to_display[$i]['item'], $products_to_display[$i]['board'], $products_to_display[$i]['price']); } ?> <tr><td colspan="4" style="text-align: right; border: none"> <input type="submit" value="Purchase"></td></tr> </tbody> </table> <?php } } if (!function_exists('save_hidden_qty')) { function save_hidden_qty($the_quantities){ foreach ($the_quantities as $key=>$value){ print "<input type='hidden' name='quantity[$key]' value='$value'>\n"; } } } ?>Can anyone help me out? I need help trying to figure out why my form won't write the database it is supposed to - i checked the connection to the database and it works and the user seems to have permission to edit database - the error I get is "Error: User not added to database." from "register.php". Can someone please look over my code and see if the problem is coming from somewhere within?
I created a connection file (connect.php)
<? session_start(); // Replace the variable values below // with your specific database information. $host = "localhost"; $user = "master"; $pass = "hidden"; $db = "user"; // This part sets up the connection to the // database (so you don't need to reopen the connection // again on the same page). $ms = mysql_pconnect($host, $user, $pass); if ( !$ms ) { echo "Error connecting to database.\n"; } // Then you need to make sure the database you want // is selected. mysql_select_db($db); ?>Then there is the php script (register.php): <?php session_start(); // connect.php is a file that contains your // database connection information. This // tutorial assumes a connection is made from // this existing file. require('connect.php'); // If the values are posted, insert them into the database. if (isset($_POST['email']) && isset($_POST['password'])){ $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $email = $_POST['email']; $password = $_POST['password']; $query = "INSERT INTO `member` (firstname, lastname, email, password) VALUES ('$firstname', '$lastname', '$email' '$password')"; $result = mysql_query($query); if ( !mysql_insert_id() ) { die("Error: User not added to database."); } else { // Redirect to thank you page. Header("Location: surveylanding_no-sidebar.html"); } } ?>Here is the HTML form: <form name="htmlform" method="post" class="form" action="register.php"> <p class="firstname"> <input type="text" name="firstname" id="firstname" /> <label for="firstname">First Name</label> </p> <p class="lastname"> <input type="text" name="lastname" id="lastname" /> <label for="lastname">Last Name</label> </p> <p class="email"> <input type="email" name="email" id="email" /> <label for="email">Email</label> </p> <p class="Password"> <input type="password" name="password" id="password" /> <label for="password">Password</label> </p> <p class="submit"> <input type="submit" value="Register"/> </p> </form> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=305698.0 |