PHP - Trouble With Database Editing Through Php (website Registration Page)
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> Similar TutorialsHi guys, just wondering if someone can help me i am currently trying to edit a MYSQL database through PHP and just wondering if you could take a look at the code i have and tell me where i have gone wrong. I have tried to use a tutorial but have got lost and need some help. This is for my final year project for University and really needs to be done soon so i would be really greatful if someone could help me out. Thanks code below: 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 content="text/html; charset=utf-8" http-equiv="Content-Type" /> <link rel="stylesheet" type="text/css" href="style.css"/> <title>Database Editor</title> </head> <body> <div id="page"> <img src="images/banner1.jpg" alt="banner"/> <div id="navi-container"> <ul id="navi"> <li><a href="index.php">Home</a></li> <li><a href="news.php">News</a></li> <li><a href="latest_products.php">Latest Products</a></li> <li><a href="gallery.php">Gallery</a></li> <li><a href="Admin_page.php">Administration</a></li> </ul> </div> <?php ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <h1>Database Editor</h1> <table class="inputtable"> <tr> <td class="label">Item Name:</td> <td class="inputtd"> <input name="Item_Name" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label"> Item Image:</td> <td class="inputtd"> <input name="Item_Image" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label">Item Description:</td> <td class="inputtd"> <input name="Item_Description" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label">Item Number:</td> <td class="inputtd"> <input name="Item_Number" type="text" class="standardwidth" /></td> </tr> </table> <br /> <table class="radbuttons"> <tr> <td class="standardwidth"> <input name="op" type="radio" checked="checked" value="rdbase" /> Read from Database</td> <td><input name="op" type="radio" value="cdbase" />Change Entry (enter data in form)</td> </tr> <tr> <td class="standardwidth"> <input name="op" type="radio" value="adbase" />Add to Database</td> <td><input name="op" type="radio" value="ddbase" />Delete Entry (enter name in form)</td> </tr> </table> <br /> <input name="submit" type="submit" value="submit" /> <input name="reset" type="reset" value="reset" /> <br /> </form> <?php if (count($view->peopleList) > 0) { ?> <table class="datatable"> <tr> <th><strong>Surname</strong></th> <th><strong>First Name </strong></th> <th class="standardwidth"><strong>Address </strong></th> <th><strong>Phone</strong></th> </tr> <?php foreach ($view->peopleList as $person) : ?> <tr> <td> <?php echo $person->getSurname(); ?> </td> <td> <?php echo $person->getFirstname(); ?> </td> <td> <?php echo $person->getAddress(); ?> </td> <td> <?php echo $person->getPhone(); ?> </td> </tr> <?php endforeach; } ?> </table> <?php ?> <?php $dbc = mysql_connect ('****','***','salford*****') OR die('Could not connect to MySQL : ' . mysql_error() ); mysql_select_db ('****') OR die('Could not select the database : ' . mysql_error() ); $query = "SELECT * FROM ****** ORDER BY Item_Number"; $result = mysql_query ($query); ?> <body> <h1>Database</h1> <table border="1"> <tbody> <tr> <td>Item Name</td> <td>Item Image</td> <td>Item Description</td> <td>Item Number</td> </tr> <?php while($row = mysql_fetch_array($result,MYSQL_ASSOC)) { echo " <tr> <td>$row[Item_Name]</td> <td>$row[Item_Image]</td> <td>$row[Item_Description]</td> <td>$row[Item_Number]</td> </tr> "; } mysql_close(); ?> $sql = 'INSERT INTO murrayfp10_ipad (Item_Name, Item_Description, Item_Number) VALUES (:Item_Name, :Item_Description, :Item_Number)'; $result = $this->dbh->prepare($sql); $result->execute(array( ':Item_Name' => $data['Item_Name'], ':Item_Description' => $data['Item_Description'], ':Item_Number' => $data['Item_Number'] )); return $this->dbh->lastInsertId(); } public function edittbl($data) { $sql = 'UPDATE murrayfp10_ipad SET Item_Name = :Item_Name, Item_Description = :Item_Description, Item_Number = :Item_Number WHERE Item_Name = :Item_Name'; $result = $this->dbh->prepare($sql); return $result->execute(array( ':Item_Name' => $data['Item_Name'], ':Item_Description' => $data['Item_Description'], ':Item_Number' => $data['Item_Number'], ':Item_Number' => $data['Item_Number'] )); } public function deletetbl($data) { $sql = 'DELETE FROM murrayfp10_ipad WHERE Item_Name = :Item_Name'; $result = $this->dbh->prepare($sql); return $result->execute(array( ':Item_Name' => $data['Item_Name'] )); } <div style="text-align:center;"> Copyright © M.Murray 2011 </div> </body> </html> Hello: I am trying to figure out how to do an UPDATE SET for a photo gallery based on the "photo_id" ... not working to well ... Currently, it just uploads a photo but updates everything. This is the code: Photo_Edit.php Code: [Select] <?php $photo_id = $_REQUEST['photo_id']; ?> ... <?php $query=mysql_query("SELECT * FROM gallery_photos WHERE photo_id = $photo_id") or die("Could not get data from db: ".mysql_error()); while($result=mysql_fetch_array($query)) { $photo_id=$result['photo_id']; $photo_filename=$result['photo_filename']; $photo_caption=$result['photo_caption']; } ?> <form enctype="multipart/form-data" action="a_Photo_Upload2.php" method="post" name="upload_form"> <input type='hidden' name='photo_id' value='<?php echo $photo_id; ?>' /> <table width='600' border='0' id='tablepadding' align='center'> <tr> <td width='50'> Photo: <td width='550'> <input name='photo_filename[]' id='my_photo' type='file' /> <div style='clear: both;'></div> Current photo: <div style='clear: both;'></div> <img src="../gallery/tb_<?php echo $photo_filename; ?>" width="100px" class='imgCenter' /> <div style='clear: both;'></div> <a href="javascript:void(0);" onmouseover="tooltip.show('<img src=../gallery/tb_<?php echo $photo_filename; ?> width=500 />');" onmouseout="tooltip.hide();">Larger view</a> </td> </tr> <tr> <td> Description: </td> <td> <textarea name='photo_caption[]' cols='100' rows='10'><?php echo $photo_caption; ?></textarea> </td> </tr> <tr> <td> <input type='submit' name='submit' value='Edit Product' /> </td> </tr> </table> </form> Goes to this page, where I am having the problems: a_Photo_Upload2.php Code: [Select] <?php echo $photo_id; ?> <?php // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) //{ //$thumbnail_width = 100; //$thumbnail_height = (int)(100 * $size[1] / $size[0]); //} //else //{ //$thumbnail_width = (int)(100 * $size[0] / $size[1]); //$thumbnail_height = 100; //} { //$thumbnail_width = 690; //$thumbnail_height = (int)(500 * $size[1] / $size[0]); $old_width = $size[0]; $old_height = $size[1]; $thumbnail_width = 690; $thumbnail_height = ($old_height * $thumbnail_width / $old_width); } else { $thumbnail_width = (int)(690 * $size[0] / $size[1]); $thumbnail_height = 500; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail //$destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); $destination_handle = imagecreatetruecolor( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' style='margin-right: 20px; width: 100px;' />"; } } $counter++; } // Print Result echo <<<__HTML_END $result_final __HTML_END; ?> Can anyone show me how to make this work, OR show me a way to do this ... Thank you. 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?
Hey guys! I ran into another problem, i am looking to create a system so my users can go edit their accounts such as: Password, Age and Info and so on. but im am totally blank so i need some kind of tutorial to get started, or maybe help if anyone got time for that. Thanks Hello, iv got a code that validates form fields: ////////////////////duomenys is regform.php $username = $_POST['regname']; $email= $_POST['regemail']; $password1 = $_POST['regpass1']; $password2 = $_POST['regpass2']; /////////////////////////////////////////// ini_set('error_reporting', E_ALL); ini_set('display_errors', 1); $result = pg_query('SELECT 1 FROM duom WHERE LOWER(name)=\''.strtolower(pg_escape_string($username)).'\'')or exit(pg_last_error()); if(isset($_POST['regsubmit'])){ ////////////////////////////////////tikrina ar viskas uzpildyta if($username !="" && $email !="" && $password1 !="" && $password2 !="" && $password1 == $password2) { /////////////////////////////////////////////////////////////// if (pg_num_rows($result)) { exit('Toks vartotojas jau egzistuoja, pasirinkite kita vartotojo varda'); } else ///////////////////ideda duomenys is regform.php i duomenu baze $insert = "INSERT into duom(name, email, pass) VALUES('".$username."','".$email."','".$password1."')"; pg_query($insert); echo "Registracija pavyko!"; /////////////////////////////////////////////////////////////// } else echo "Blogai uzpildyti domenys!"; } everything is working but i need to add 1 more thing to this - to see if email already exists in the databse. I did it for username but idk how to add the same code for email. Heres the code to check if username already exists: ini_set('error_reporting', E_ALL); ini_set('display_errors', 1); $result = pg_query('SELECT 1 FROM duom WHERE LOWER(name)=\''.strtolower(pg_escape_string($username)).'\'')or exit(pg_last_error()); if (pg_num_rows($result)) { exit('Username already exists); thanks in advance Ok, first off, I tested my own coded reg system and when I make an error test, the error shows but the user info gets added to the database. How can I stop letting the code add the user to the database when an error occurs. <?php include "lang.php"; ?> <!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>PokePals - Registering</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" /> <link rel="stylesheet" type="text/css" href="style.css" /></head> <body> <?php include "navbar.php"; ?> <?php // Important stuff goes here include "sql_local.php"; include "ban.php"; // Now for the registration page echo "<div class='panel'>"; if (isset($_POST["submit"])) { // Define the variables here $user = mysql_real_escape_string ($_POST["user"]); $pass1 = mysql_real_escape_string ($_POST["pass"]); $pass2 = mysql_real_escape_string ($_POST["passconf"]); $email = mysql_real_escape_string ($_POST["email"]); $email2 = mysql_real_escape_string ($_POST["email2"]); $dpfc = mysql_real_escape_string ($_POST["dpfc"]); $platinumfc = mysql_real_escape_string ($_POST["platinumfc"]); $hgssfc = mysql_real_escape_string ($_POST["hgssfc"]); $otherfc = mysql_real_escape_string ($_POST["otherfc"]); $favoritepkmn = mysql_real_escape_string ($_POST["favoritepkmn"]); $aboutme = mysql_real_escape_string ($_POST["aboutme"]); $hobbies = mysql_real_escape_string ($_POST["hobbies"]); $favorites = mysql_real_escape_string ($_POST["favorites"]); $gender = mysql_real_escape_string ($_POST["gender"]); // Now check for some errors // Did he/she fill out the form completely? Lets find out function errors() { if (!$_POST["user"] | !$_POST["pass"] | !$_POST["email"] ) { echo "<div class='error'>Please fill in the required fields</div>"; } // Passwords match if ($_POST['pass'] != $_POST['passconf']) { echo "<div class='error'>Password does not match with the other one</div>"; } // Email match if ($_POST['email'] != $_POST['email2']) { echo "<div class='error'>Email does not match with the other one</div>"; } } // Is the user banned? foreach($banned_ips as $ip_ban) { if($user_ip == $ip_ban) { die ("<div class='error'>Your IP address is banned from registering. Contact the site administrator for more info</div>"); } } // If there are no errors, start adding the information to the database if (!errors()) { // Secure the passwords $securepass = md5($pass1); // Submit to the database $insertuser = "INSERT INTO users (user, password, email, dpfc, platinumfc, hgssfc, otherfc, favoritepkmn, aboutme, hobbies, favorites, gender, regip) values ('$user', '$securepass', '$email', '$dpfc', '$platinumfc', '$hgssfc', '$otherfc', '$favoritepkmn', '$aboutme', '$hobbies', '$favorites', '$gender', '$user_ip')"; $add = mysql_query($insertuser, $con) or die ('Error: ' . mysql_error() . ' Please contact an admin'); if ($add) { echo ("<h3>Registration Success</h3><p>You may now login using your username and password. Start hatching some eggs now!</p>"); } } } ?> <div class='registerform'><form action='register.php' method='post'> <label>Username *</label> <input type='text' name='user' class='form1' value='<?php echo @$_POST['user']; ?>' /> <fieldset><legend>Password</legend> <label>Enter your password *</label> <input type='password' name='pass' class='form1' value='<?php echo @$_POST['pass']; ?>' /> <label>Password again *</label> <input type='password' name='passconf' class='form1' value='<?php echo @$_POST['passconf']; ?>' /> </fieldset> <fieldset><legend>Email</legend> <label>Enter your email *</label> <input type="text" name="email" class="form1" value="<?php echo @$_POST['email']; ?>" /> <label>Enter email again *</label> <input type="text" name="email2" class="form1" value="<?php echo @$_POST['email2']; ?>" /> </fieldset> <input type="submit" name="submit" class="submitbutton" value="Register!" /> </form> Ok Here is my Problem the following works great except it does not add the $user var to the account_details. As well as outputs md5 wrong it outputs something but its different than the password should be. Heres my PHP code: Code: [Select] <?php session_start(); /** * @author Brian T. Flores * @copyright 2010 - 2014 */ error_reporting(E_ALL); $conn = mysql_connect($db_host, $db_user, $db_pass) or die ('Error connecting to mysql'); mysql_select_db($db_name); if($_GET['goahead']==1){ // If GoAhead Is set if(isset($_GET['user'])){ // If isset GoAhead $user = mysql_real_escape_string($_GET['user']); // Clean User for Transfer. $user_check = mysql_query("SELECT * FROM `account_details` WHERE `username01` = '$user'"); // Check to see if username is taken. $ucount = mysql_num_rows($user_check); // Get Username Check Count if($ucount!=""){ // If Username is Taken. die(3); // Die Error Number 3 } // End If Username is Taken. if(isset($_GET['pass'])){ // If password is set. $pass = mysql_real_escape_string($_GET['pass']); // Clean Password for Transfer. $encPass = md5($pass); // Encrypt Password if(isset($_GET['race'])){// If Race is Set. $race = mysql_real_escape_string($_GET['race']); // Clean Race for Transfer. if(isset($_GET['email'])){ // If Email is set. $email = mysql_real_escape_string($_GET['email']); // Clean Email for Transfer. $email_check = mysql_query("SELECT * FROM `account_details` WHERE `email` = '$email'");// Check to see if Email is Taken. $ecount = mysql_num_rows($email_check); // Get Email Check Count. if($ecount!=""){ // If Email is Taken. die(2); // Die Error Number 2 } // End If Email is Taken. if(isset($_GET['email2'])){ // If email confirmation is set. $email2 = mysql_escape_string($_GET['email2']); // Clean Email Confirmation for Transfer. if($email == $email2){ // If emails match. if(isset($_GET['planet'])){ // If Planet Name is Set. $pname = mysql_real_escape_string($_GET['planet']); // Clean Planet Name for Transfer. if(isset($_GET['security_code'])){ // If Security Code Input is set. $security_code = mysql_real_escape_string($_GET['security_code']); // Clean Security Code. $security_enc = md5($security_code); // Encrypt Security Code. $security_code2 = $_SESSION['image_random_value']; // Get Security Code Session if($security_enc == $security_code2){ // If Codes Match. $randActive = rand(11111111111111111111,99999999999999999999); // Get Activation Link pre-encrypt. $activation_link = md5($randActive); // Get Encrypted Activation Link. $q = "INSERT INTO `account_details` (`username01`, `password01`, `loggedIn`, `currentlyLogged`, `active`, `activelink`, `race`, `email`) VALUES ('$user', '$encPass', 0, 0, 0, '$activation_link', '$race', '$email');"; // ^ Add Account Query. $res = mysql_query($q) or die("Error Detected! <br />".mysql_error()); // ^ Add Account to SQL. $q = mysql_query("SELECT * FROM `account_details` WHERE `username01` = '$user'")or die(mysql_error()); // ^ Get Information from New Account. $newuserinfo = mysql_fetch_array($q);// Get New User Information $id = $newuserinfo['id']; // Set New Account Id. $q="INSERT INTO `planets` (`owner`, `name`, `recource1`, `recource2`, `recource3`, `recource4`, `recource5`, `turns_01`, `untrained_units_01`, `attackers_01`, `defenders_01`, `miners_01`, `covert_01`, `anticovert_01`, `ship_01`, `ship_02`, `ship_03`, `ship_04`, `ship_05`, `ship_06`, `ship_07`, `building01`, `building02`, `building03`, `building04`, `building05`, `building06`, `building07`, `building08`, `building09`) VALUES ('$id', '$pname', 35000, 15000, 12000, 135000, 125000, 220, 150, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0);"; // ^ Add Planet Query. $res2 = mysql_query($q) or die("Error Detected! <br />".mysql_error()); // Add Planet to SQL. $body = " Hello ".$user.", Congradulations! Your account on Ultimate Conquest has been Registed Today! Click the following Link to Activate Account: http://testing.ultimateconquest.net/activate.php?code=".$activation_link." If you have not registered an account and have found this message in error please click the following link to report this error: http://testing.ultimateconquest.net/errorreg.php?account=".$user." Thank you for registering for Ultimate Conquest - ULC, Head Admin Brian Flores AKA Photonic.... "; // Activation Email Information. if (mail($email, "Activate your ULC Ultimate Conquest Account! No-Reply!", $body)) { // If Email Is Sent. die("1"); // Die Error Number 1 } // End Send Email }else{ // If Security Codes do Not Match. die("12"); // Die Error Number 12 } }else{ // If Security Code is Not Set die("11"); // Die Error Number 13 } }else{ // If Planet Name is Not Set. die("10"); // Die Error Number 10. } }else{ // If Emails do not match. die("9"); // Die Error Number 9. } }else{ // If email confirmation is not set. die("8"); // Die Error Number 8. } }else{ // If email is not set. die("7"); // Die Error Number 7. } }else{ // If race is not set. die("6"); // Die Error Number 6. } }else{ // If Password is not set. die("5"); // Die Error Number 5. } }else{ // If Username is not set. die("4"); // Die Error Number 4. } }else{ // If GoAhead is Not Set. die("Go Ahead Not Established By Game System!"); } ?> Here is the Register Function in Javascript: Code: [Select] function regMast(){ var user = document.getElementById('username_client').value; var pass = document.getElementById('password_client').value; var race1 = document.getElementById('races1').value; if(race1 !=""){var race = document.getElementById('races1').value;} var race2 = document.getElementById('races2').value; if(race2 !=""){var race = document.getElementById('races2').value;} var race3 = document.getElementById('races3').value; if(race3 !=""){var race = document.getElementById('races3').value;} var race4 = document.getElementById('races4').value; if(race4 !=""){var race = document.getElementById('races4').value;} var planet_name = document.getElementById('pname').value; var email = document.getElementById('email').value; var email2 = document.getElementById('email2').value; var security_code = document.getElementById('security_code').value; var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var returni = ajaxRequest.responseText; if(returni == "1"){ document.getElementById('reg_error').innerHTML = 'Registration Completed! Check Activation Email for more information.'; } if(returni == "2"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Email Address Already Taken!'; } if(returni == "3"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Username Already Taken!'; } if(returni == "4"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Username Field Empty!'; } if(returni == "5"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Password Field Empty!'; } if(returni == "6"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! You must select a race!'; } if(returni == "7"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Email Field Empty!'; } if(returni == "8"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Email Confirmation Field Empty!'; } if(returni == "9"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Emails did not Match!'; } if(returni == "10"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Planet Name Field Empty!'; } if(returni == "11"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! You did not Input the Security Code!'; } if(returni == "12"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! The Security Code you Inputed did not Match the Image!'; }else{ document.getElementById('reg_error').innerHTML = returni; } } } var queryString = "?goahead=1&user=" + user + "&pass=" + pass + "&race=" + race + "&email=" + email + "&email2=" + email2 + "&security_code=" + security_code + "&planet=" + planet_name; ajaxRequest.open("GET", "register.php" + queryString, true); ajaxRequest.send(null); } Could anyone help me making a login function that checks the txt document if user and pw exists/are correct? -and if they are, sends you to a logged in page. This is for a assignment which is why I have to store the information in a text document, I know it's unsafe. Also i know i should use $_Sessions but I'm not sure how to use it and where to put it.
So far I have created the form which has 2 buttons one for registering and one for logging in. I have also created the registration function which checks the text file if the username already exists if not it will register it. <html lang="eng"> <head> <link rel="stylesheet" href="style.css"> <title>name</title> </head> <body> <div class="formdiv"> <h2>Log in or register</h2> <form action="" method="post"> <p>Username<p style="color:black">*</p> <input type="text" name="user" placeholder="Type in your username" required> <p>Password<p style="color:black">*</p> <input type="password" name="pw" placeholder="Type in your password" required> <?php if (isset($_POST['saveBtn'])){ $username = $_POST['user']; $password = $_POST['pw']; $error = register($username); if ($error == '') { echo "User: $username has been registered!<br/>"; } else echo $error; } ?> <input type="submit" name="saveBtn" value="Save new user"> <input type="submit" name="loginBtn" value="Login"> </form> </div> <?php // Registration function register($user){ $textError = ''; // Check and see if user exists $UserPassTxt = fopen("userpwd.txt","a+"); // Opens text doc rewind($UserPassTxt); while (!feof($UserPassTxt)) { $line = fgets($UserPassTxt); $tmp = explode(':', $line); if ($tmp[0] == $user) { $textError = "Username already exists!"; break; } } if ($textError == ''){ $hash = password_hash('', PASSWORD_DEFAULT); fwrite($UserPassTxt, "\n$user: $hash"); } fclose($UserPassTxt); // Closes txt doc return $textError; } ?> <?php //Login function login($user, $pass){ } ?> </body> ///here's my best attempt at the function <?php //Login $error = '0'; if (isset($_POST['loginBtn'])){ $username = $_POST['user']; $password = $_POST['pw']; $error = login($username,$password); } function login($user, $pass){ $errorText = ''; $validUser = false; $UserPassTxt = fopen("userpwd.txt","r"); rewind($UserPassTxt); while (!feof($UserPassTxt)) { $line = fgets($UserPassTxt); $tmp = explode(':', $line); if ($tmp[0] == $user) { if (trim($tmp[1]) == trim(password_hash('', PASSWORD_DEFAULT))){ $validUser= true; $_SESSION['user'] = $user; } break; } } fclose($UserPassTxt); if ($validUser != true) $errorText = "Not correct username or password"; if ($validUser == true) $_SESSION['validUser'] = true; else $_SESSION['validUser'] = false; return $errorText; } function logoutUser(){ unset($_SESSION['validUser']); unset($_SESSION['user']); } function checkUser(){ if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true)){ header('Location: index.php'); } } ?>
Hello Im quite confused at what filtering I should use on my data when pulling it from a MySQL database. I don't sanitize my data on input because I am using prepared statements with PHP's PDO Driver which means I don't need to use mysql_real_escape_string() at all. When I pull the data to be displayed i.e. in a HTML Table I use the below function to make it safe for HTML output. public static function htmlSafe($data) { return nl2br(htmlentities($data, ENT_QUOTES)); } However the rules change when Im using a HTML Form to edit the data, and I am unsure what I need to strip out. I.e. What would I need to do to make all data safe to insert into the following form input. <input id = "someInput" type = "text" value = "<?php echo $someVarThatNeedsFiltering ?>" /> Also, one more question, in my html attributes (Valid ones like class, name, id, style, _target) I use a mixture of double quotes(") and single quotes ('), for quoting my values. Which one should I use or which one is more valid, doubles, or singles? 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. 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 Hi Does anyone know any good tutorials for creating a registration page for a website? Thanks in advance. This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=350931.0 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 ?> So I have a page that displays a table from my database and now I have to create a link that edits the information and saves it back to the database from a page. I have 2 pages: student_man.php which displays the table info and provides the edit link, and then editstudent.php which displays the form etc where you edit the info and submit it. I think my first page is fine, or rather doesn't display any errors. I'm struggling with my second page however, receiving errors and my data that is already in the fields aren't displaying rather the fields are just empty. First time I attempt this just want to know if I am on the right path and what I might doing wrong. Here is my code First page:<?php Code: [Select] <html> <head> <head> <title>Courses</title> <style type="text/css"> #apDiv2 { position:absolute; left:0px; top:0px; width:1024px; height:180px; z-index:2; } </style> </head> <body bgcolor="white"> <?php ?> <div id="apDiv1"> <div id="apDiv2"><img src="Images/Banner.gif" width="1024" height="180" /></div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <center><p><a href="student_reg.php"> Register a student</a> -- <a href="course_man.php"> Manage courses </a> -- <a href="student_man.php"> Manage student </a> --<a href="list.php"> view registrations </a> </p></center> </div> <br> <br> <p><a href="selectdelstudent.php"> Delete </a> <a href="student_reg.php"> Add </a> </p> <!-- Table for course --> <div id="apdiv3"> <table border=1px noshade="no"> <tr> <td><b> Course Name</b></td> <td><b> Surname</b></td> <td><b> Initials</b></td> <td><b> Full First Name</b></td> <td><b> Title</b></td> <td><b> Maiden or previous surname</b></td> <td><b> Date of birth</b></td> <td><b> Gender</b></td> <td><b> Language of correspondence</b></td> <td><b> Identity number</b></td> <td><b> Cell Phone Number</b></td> <td><b> Fax Code + Number</b></td> <td><b> E-mail Address</b></td> <td><b> Postal address of student</b></td> </tr> </table> </div> <!-- Start of php code for retrieving student information --> <?php include 'includes/config.php'; //connect to database $link=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); //error check if (!$link) { die('could not connect: ' . mysql_error()); } $db_selected=mysql_select_db(DB_NAME, $link); // error check if (!$db_selected) { die('can\t use ' . DB_NAME . ': ' . mysql_error()); } //query database $query=mysql_query("SELECT * FROM student "); //fetch results and convert to table while ($rows = mysql_fetch_array($query)): echo "<a href=\"editstudent.php?id=" . $rows['sno'] ."\" > edit </a>"; $cname=$rows['cname']; $sname=$rows['sname']; $init=$rows['init']; $fname=$rows['fname']; $title=$rows['title']; $msname=$rows['msname']; $dob=$rows['dob']; $sex=$rows['sex']; $lang=$rows['lang']; $idno=$rows['idno']; $telh=$rows['telh']; $telw=$rows['telw']; $cell=$rows['cel']; $fax=$rows['fax']; $email=$rows['email']; $address=$rows['address']; echo " <table border=1px> <tr> <td>$cname</td> <td>$sname</td> <td>$init</td> <td>$fname</td> <td>$title</td> <td>$msname</td> <td>$dob</td> <td>$sex</td> <td>$idno</td> <td>$telh</td> <td>$telw</td> <td>$cell</td> <td>$fax</td> <td>$email</td> <td>$address</td> </tr> </table>" ; endwhile; ?> </body> </html> ?> Here is my second page where you edit the info: <?php Code: [Select] <?php include 'includes/config.php'; //connect to database $link=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); //error check if (!$link) { die('could not connect: ' . mysql_error()); } $db_selected=mysql_select_db(DB_NAME, $link); // error check if (!$db_selected) { die('can\t use ' . DB_NAME . ': ' . mysql_error()); } // connected to database if (!isset($_POST['submit'])) { $q = "SELECT * FROM student WHERE ID = $_GET[sno]"; $result = mysql_query($q); $person = mysql_fetch_array($result); } ?> <h1> You are editing a student </h1> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <p>Course name:</p> <INPUT TYPE = "text" name="input1"value="<?php echo $person['cname']; ?>" /> <br> <p>Surname:</p> <INPUT TYPE = "text" name="input2"value="<?php echo $person['sname']; ?>" /> <br> <p>Initials:</p> <INPUT TYPE = "text" name="input3"value="<?php echo $person['init']; ?>" /> <br> <p>Full First Name:</p> <INPUT TYPE = "text" name="input4"value="<?php echo $person['fname']; ?>" /> <br> <p>Title:</p> <INPUT TYPE = "text" name="input5"value="<?php echo $person['title']; ?>" /> <br> <p>Maiden or previous surname:</p> <INPUT TYPE = "text" name="input6"value="<?php echo $person['msname']; ?>" /> <br> <p>Date of Birth:</p> <INPUT TYPE = "text" name="input7"value="<?php echo $person['dob']; ?>" /> <br> <p>Gender:</p> <INPUT TYPE = "text" name="input8"value="<?php echo $person['sex']; ?>" /> <br> <p>Language for correspondence:</p> <INPUT TYPE = "text" name="input9"value="<?php echo $person['lang']; ?>" /> <br> <p>Identity Number:</p> <INPUT TYPE = "text" name="input10"value="<?php echo $person['id']; ?>" /> <br> <p>Home Telephone Code + Number:</p> <INPUT TYPE = "text" name="input11"value="<?php echo $person['telh']; ?>" /> <br> <p>Work Telephone Code + Number:</p> <INPUT TYPE = "text" name="input12"value="<?php echo $person['telw']; ?>" /> <br> <p>Cell Phone Number:</p> <INPUT TYPE = "text" name="input13"value="<?php echo $person['cel']; ?>" /> <br> <p>Fax Code + Number:</p> <INPUT TYPE = "text" name="input14"value="<?php echo $person['fax']; ?>" /> <br> <p>E-mail Address:</p> <INPUT TYPE = "text" name="input15"value="<?php echo $person['email']; ?>" /> <br> <p>Postal Address of student:</p> <INPUT TYPE = "text" name="input16"value="<?php echo $person['address']; ?>" /> <br> <INPUT TYPE = "Submit" name="submit" VALUE = "Submit"/> <input type="hidden" name="sno" value="<?php echo $_GET['sno']; ?>" /> </form> <?php if(isset($_POST['submit'])) { $u = "UPDATE student SET `cname` = '$_POST[input1]' `sname` = '$_POST[input2]' `init` = '$_POST[input3]' `fname` = '$_POST[input4]' `title` = '$_POST[input5]' `msname` = '$_POST[input6]' `dob` = '$_POST[input7]' `sex` = '$_POST[input8]' `lang` = '$_POST[input9]' `idno` ='$_POST[input10]' `telh` = '$_POST[input11]' `telw` = '$_POST[input12]' `cel` = '$_POST[input13]' `fax` = '$_POST[input14]' `email` = '$_POST[input15]' `address` = '$_POST[input16]' WHERE ID = $_POST(sno)"; mysql_query($u) or die(mysql_error()); echo "User has been modified!"; header("Location: index.php"); } ?> ?> On my second page I am receiving the following errors after typing random letters as info into the fields and submitting it: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`sname` = 'sds' `init` = 'gfg' `fname` = 'rtr' `title` = '' `msname`' at line 3 Hey there is no error with this code it works just fine but I would love to know if there is unnecessary coding in it for example do i have to do the global variables? is there a better way to do mysql editing page? thanks <?php include "../configdb.php"; $id = $_GET['id']; if(isset($_POST['submit'])) { //global variables $name = $_POST['name']; $footer = $_POST['footer']; //run the query which adds the data gathered from the form into the database $result = mysql_query("UPDATE pages SET name='$name', footer='$footer' WHERE id='$id' ",$connect); echo "<b>Your Page have been edited successfully"; } elseif($id) { $result = mysql_query("SELECT * FROM pages WHERE id='$id' ",$connect); while($row = mysql_fetch_assoc($result)) { $name = $row['name']; $footer = $row['footer']; ?> <h3>::Edit Page</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>?id=<?php echo $row['id']?>"> <input type="hidden" name="id" value="<?php echo $row['id']?>"> <input name="name" size="40" maxlength="255" value="<?php echo $name; ?>"> <input name="footer" size="40" maxlength="255" value="<?php echo $footer; ?>"> <input type="submit" name="submit" value="Submit"> <?php } } Please help me out with sessions . I m new to this topic.
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? |