PHP - Submitting Data From Dynamic Form
Hi,
I have a dynamic form which uses javascript to add rows on the fly. The name of the element on my test page is txtRow1, txtRow2, etc; the number is added when I add a new row. I am trying to figure out how I will extract the data once the form had been POSTED. I have tried Code: [Select] $tags = $_POST['txtRow']; foreach ($tags as $t) { echo "$t<br />"; } but that shows nothing. I would be grateful for any assistance. Thanks Similar TutorialsHi - I have a form which is populated with values from a DB. This is done by looping through the DB values using a foreach. It works fine. I populate my form with those values. However, I want to be able to amend those values, and then submit the new values back to the DB with 1 single submit button. I don't want a separate submit button for each row of my form. The problem is that because the form is built with a foreach, as the it loops through the variables on each pass of the DB, only the final row of DB are present in the form variables. Question: My 'foreach' approach must be faulty. What is the mechanism or approach I need to use to update the values from the whole form ?? MANY THANKS for all your help !! Hi guys, I really hope this will make sense. I am creating a dynamic field on a button click for Pickup Location. That works fine and submitting the form to the database works fine. However, instead of one entry, each time I submit the form with multiple Pickup Locations, it creates multiple separate database entries. Here is the PHP for submitting: if(isset($_POST['new']) && $_POST['new']==1){ $pickups = ''; foreach($_POST['pickups'] as $cnt => $pickups) $pickups .= ',' .$pickups; $locations = count($_POST["pickups"]); if ($locations > 0) { for ($i=0; $i < $locations; $i++) { if (trim($_POST['pickups'] != '')) { $name = mysqli_real_escape_string($con, $_POST['name']); $price = mysqli_real_escape_string($con, $_POST['price']); //$origin = $_POST['origin']; $pickups = $_POST["pickups"][$i]; $destination = mysqli_real_escape_string($con, $_POST['destination']); $dep_date = mysqli_real_escape_string($con, $_POST['dep_date']); $ret_date = mysqli_real_escape_string($con, $_POST['ret_date']); $fleet_number = mysqli_real_escape_string($con, $_POST['fleet_number']); $driver = mysqli_real_escape_string($con, $_POST['driver']); $itinerary = mysqli_real_escape_string($con, $_POST['itinerary']); $submittedby = mysqli_real_escape_string($con, $_SESSION["username"]); $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s")); $query="insert into tours (`name`, `price`, `pickups`, `destination`, `dep_date`, `ret_date`, `fleet_number`, `driver`, `itinerary`, `submittedby`, `trn_date`)values ('$name', '$price', '$pickups', '$destination', '$dep_date', '$ret_date', '$fleet_number', '$driver', '$itinerary', '$submittedby', '$trn_date')"; mysqli_query($con,$query) or die(mysqli_error($con)); if(mysqli_affected_rows($con)== 1 ){ $message = '<i class="fa fa-check"></i> - Record Inserted Successfully'; } } } } } Here is the HTML form: <form role="form" method="post" name="add_tour" id="add_tour" action""> <input type="hidden" name="new" value="1" /> <div class="modal-body"> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="name" class=" form-control-label">Name</label><input type="text" id="name" name="name" placeholder="Tour Name" class="form-control"> </div> </div> <div class="col-6"> <div class="form-group"><label for="price" class=" form-control-label">Price</label><input type="text" id="price" name="price" placeholder="0.00" class="form-control"> </div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group origin" id="pickupsfield"><label for="pickups" class=" form-control-label">Pickup Location</label><input type="text" id="pickups" name="pickups[]" placeholder="Start Typing..." class="form-control"></div> <button type="button" class="btn btn-success add-field" id="add" name="add">Add New Location <span style="font-size:16px; font-weight:bold;">+ </span> </button> </div> <div class="col-6"> <div class="form-group"><label for="destination" class=" form-control-label">Destination</label><input type="text" id="destination" name="destination" placeholder="Start Typing..." class="form-control"></div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="dep_date" class=" form-control-label">Departure Date</label><input type="date" id="dep_date" name="dep_date" placeholder="" class="form-control"></div> </div> <div class="col-6"> <div class="form-group"><label for="ret_date" class=" form-control-label">Return Date</label><input type="date" id="ret_date" name="ret_date" placeholder="" class="form-control"></div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="fleet_number" class=" form-control-label">Fleet Number</label> <select class="form-control" id="fleet_number" name="fleet_number"> <option value="Select">== Select Fleet Number ==</option> <?php $sql = "SELECT fleet_number FROM fleet"; $result = $con->query($sql); while(list($fleet_number) = mysqli_fetch_row($result)){ $option = '<option value="'.$fleet_number.'">'.$fleet_number.'</option>'; echo ($option); } ?> </select> </div> </div> <div class="col-6"> <?php ?> <div class="form-group"><label for="driver" class=" form-control-label">Driver</label> <select class="form-control" id="driver" name="driver"> <option value="Select">== Select Driver ==</option> <?php $sql = "SELECT name FROM drivers"; $result = $con->query($sql); while(list($driver) = mysqli_fetch_row($result)){ $option = '<option value="'.$driver.'">'.$driver.'</option>'; echo ($option); } ?> </select> </div> </div> </div> <div class="form-group"><label for="itinerary" class=" form-control-label">Itinerary</label> <textarea class="form-control" id="itinerary" name="itinerary"></textarea> </div> <div class="modal-footer"> <button type="reset" class="btn btn-warning">Clear Form</button> <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button> </div> </form> And the Javascript for adding the new fields: <script> $(document).ready(function(){ var i = 1; $("#add").click(function(){ i++; $('#pickupsfield').append('<div id="row'+i+'"><input type="text" name="pickups[]" placeholder="Enter pickup" class="form-control"/></div><div><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></div>'); }); $(document).on('click', '.btn_remove', function(){ var button_id = $(this).attr("id"); $('#row'+button_id+'').remove(); }); $("#submit").on('click',function(){ var formdata = $("#add_tour").serialize(); $.ajax({ url :"", type :"POST", data :formdata, cache :false, success:function(result){ alert(result); $("#add_tour")[0].reset(); } }); }); }); </script> Anyone have any idea where I am going wrong? Before you say it, Yes, I know, Use Prepared statements 😷 Edited February 6 by DanEthicalAdded tags Kindly help. Am a new php programmer and am learning how to HTML form data to a php script. Have tried several times but information on html form never get submitted. For some unknown reasons, the codes are failing . Here are my codes:
<html>
and
<html>
<body> Hello, I am just getting interested in PHP, so please excuse my ignorance. Something I thought might help me learn is this challenge. http://penn-station.com/gift2010.php is a daily enter sweepstakes. I'm wanting to automate a daily entry. I was able to do so using AutoIT (windows automation), but the result was rather janky. Anyways, I found how to enter my name in the Name field of the form by modifying the value attribute of the textbox. (I used Chrome's DOM inspector plug-in) <input type="text" class="EH_Form_Textbox" name="Name" size="30" value="Fred"> How would I go about actually submitting this? Thank you very much, Fred Hi Guys I've constructed a modified shopping cart system using the tutorial he http://v3.thewatchmakerproject.com/journal/276/ I'm not great at PHP but have managed to have it working great. My question is: How can I send the data stored in my session, via email using the form? On the final page before the submission is made to email the data - i've got contact detail inputs for the form, and the cart items shown. I just don't know how to send that info onwards. Many thanks.... I have looked up tutorials on Google. I am still confused. I built a php script that receives the data from my html form then filters out bad words. I am trying to get the script to resend the data to pm.cgi. The form was originally targeting pm.cgi but it needed filtered. This is why i am using php in the first place. Please help me pass these variables from the php script to the cgi script the same way that a html form would. Thank you. Here is my code, it prints correctly. I cannot get cURL to work. <?php $action = $_GET['action'] ; $login = $_REQUEST['login'] ; $ID = $_REQUEST['ID'] ; $text = $_REQUEST['Unused10'] ; $submit = $_REQUEST['submit'] ; function filterBadWords($str){ // words to filter $badwords=array( "badword1", "badword2"); // replace filtered words with random spaces $replacements=array( "****", "***", "****" ); for($i=0;$i < sizeof($badwords);$i++){ srand((double)microtime()*1000000); $rand_key = (rand()%sizeof($replacements)); $str=eregi_replace($badwords[$i], $replacements[$rand_key], $str); } return $str; } $text = filterBadWords($text); print_r($action); print_r($login); print_r($ID); print_r($text); print_r($submit); ?> I need to send the variables that i printed above to pm.cgi. Can you point me in the right direction? Thanks again! Hi - I'm trying to speed up part of my business. I sell photos taken on site...I dump said photos in a directory and my little app pulls all images from a given directory and displays them on a page. I can get the filename etc displayed on screen, added to the image attributes, whatever. I'd like to have a checkbox next to each image, and the user checks a few and it'll send an email to me so I can fill their order. Looks like this: http://www.limitedwave.com/reflex/ I can use a sendmail like I've tried, but it can take like 10 minutes to actually send from the server which is lame. I'd be cool with just dropping the data in my database, then retrieving selections by user's name, but I don't know how to set up a form/insert page that will insert from a somewhat random set of checkboxes. Thoughts? Thanks. So, it's me again. Hope you dont mind I try to fetch data from mysql and list it to select option like this Code: [Select] <td>Category</td> <td>: <select name="category"> <?php $query = "SELECT DISTINCT category FROM dress"; $sql = mysql_query($query); while($result = mysql_fetch_array($sql)){ echo "<option value='".$result['category']."'>".$result['category']."</option>"; } ?> <option value="other">New Category --></option> </select><input type="text" name="categoryOther"></td> </tr> ...and success. BUT, when I try to echo submitted value it return nothing this is the code to process above form Code: [Select] if(isset($_POST['categoryOther'])){ $category = $_POST['categoryOther']; } else { $category = $_POST['category']; } if(isset($_POST['subcategoryOther'])){ $subcategory = $_POST['subcategoryOther']; } else { $subcategory = $_POST['subcategory']; } echo "category : ".$category."<br>"; What did I do wrong here? Hey all, Another question for you. How does one make it so that the selections (choices) a user selects for dynamic selection boxes remain after the form is posted, which does post back to itself? I've tried JavaScript using the "name" of the selection box as the id but I must be doing something wrong because it's not working..as usual lol. The values in the selection boxes are populated dynamically so I'm not sure how to do this. Thank you. Sometimes when I submit data to a table (example a blog), it does not get added to the table. I am thinking the reason it has something to do with " / , etc... those kind of symbols, do I need to escape them some how before adding the data to the table? Hey folks, I thought this would be simple but obviously not. I can get the data to display in the textarea from the text file. That's not an issue. The issue is, updating the text from the textarea and saving it in the file, while keeping the text in the textarea. Basically, I want to create a personal notepad inside the site I am making. Here is the code I am using: <form action="?admintext.txt" method=post> <textarea name="file_content" class="textarea1"><? include "admintext.txt"; ?></textarea><br/> <input type=submit name=submit value=Update> </form> Can anyone help with this? I tried loads of tips I found from Google but none worked. Hello, I'm new to this forum and I need some help. I'm creating a simple database that it submits data from a user input. Unfortunatly, it's not sending any data to mysql also the form is not validating each field. Code: [Select] <?php if (isset($_POST['submitted'])){ $fields = array( 'email', 'state', 'district', 'gender', 'age', 'profession', 'survey', ); foreach($fields as $fieldName) { if(isset($_POST[$fieldName]) and trim($_POST[$fieldName]) !==''){ $fieldName = trim($_POST[$fieldName]); }else { $errors[] = "Please enter your". $fieldName .""; //code to validate fields } } if(isset($errors)){ require_once('Connections/encourage.php'); $query = "INSERT INTO participants (email, state, district, gender, age, profession, survey) VALUES ('$email', '$state', '$district', '$gender', '$age', '$profession','$survey')"; //databasse connection $result = mysql_query ($query); if ($result){ echo '<h1 id="mainhead">Thanks for submitting</hl> <p>You are now registered</p>'; exit(); }else{ echo '<h1 id="mainhead">System Error</hl> <p>Your registration could not be completed due to a system error We apologize for any incovience</p>';//gives system error echo 'p' . mysql_error(). '<br /><br />Query: ' . $query . '</p>'; exit(); } mysql_close(); } else { echo '<h1 id="mainhead">Error!</h1> <p class="error">The following error(s) occurred:<br />'; foreach($errors as $msg) { echo " - $msg<br/>\n"; } echo '</p><p>Please try again.</p><p><br/></p>'; } } ?> <form id="form1" name="form1" method="post" action"registration.php"> <fieldset class="first"> <label class="lableone" for="email">Email:* </label> <input name="email" value="<?php if(isset($_POST['email'])) echo $_POST['name'];?>"/> <label for="state"/>State:* </label> <input name="state" value="<?php if(isset($_POST['state'])) echo $_POST['state'];?>"/> <label for="schooldistrict"/>School District:* </label> <input name="schooldistrict" value="<?php if(isset($_POST['district'])) echo $_POST['district'];?>" /> <label for="gender">Gender:* </label> <select name="gender"> <option>Choose Your Gender</option> <option value="male" <?php echo ($form['gender'] == 'male' ? ' selected' : ''); ?>>Male</option> <option value="female"<?php echo ($form['gender'] == 'female' ? ' selected' : ''); ?>>Female</option> </select> <label for="age"/>Your Age:* </label> <input name="age" type="text" class="age" maxlength="2" value="<?php if(isset($_POST['age'])) echo $_POST['age'];?>" /> <label for="profession"/>Profession:* </label> <input name="profession" value="<?php if(isset($_POST['age'])) echo $_POST['age'];?>" /> <label for="surveys"/>Willingness to participate in future surveys: </label> <input name="surveys" type="checkbox" id="surveys" value="yes" <?php echo ($form['survey'] == 'yes' ? 'checked' : '');?>/> </fieldset> <fieldset> <input class="btn" name="submit" type="submit" value="Submit" /> <input class="btn" name="reset" type="reset" value="Clear Form" /> <input type="hidden" name="submitted" value="TRUE" /> </fieldset> </form> Can someone help me out? Thanks in advanced! i have a php script and i want it to submit to itself having the php script on the same page, the problem is when i do it it tries to upload the file without waiting for the form resaulting in format you tried to upload was not allowed" (its an image uploader) heres my code Code: [Select] <?php // Configuration - Your Options $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation. $max_filesize = 1524288; // Maximum filesize in BYTES (currently 1.5MB). $upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory). $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension). $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename. // Check if the filetype is allowed, if not DIE and inform the user. if(!in_array($ext,$allowed_filetypes)) die('<font size="4"><font color="red">The file you attempted to upload is not allowed.</font></font>'); // Now check the filesize, if it is too large then DIE and inform the user. if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) die('The file you attempted to upload is too large.'); // Check if we can upload to the specified path, if not DIE and inform the user. if(!is_writable($upload_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); // Upload the file to your specified path. if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) echo '<font size="4"><span style="color: white; text-shadow: lime 0px 0px 3px;"><h2>Upload Successful!</h2><br> <img src="' . $upload_path . $filename . '"><br> <p id="codes"><label for="codedirect">Direct Link:</label><br /> <input type="text" id="codebb" value="http://imageplanet.site90.net/' . $upload_path . $filename . '" onclick="javascript:this.focus();this.select();" readonly="true" /><br /> <label for="codehtml">HTML code:</label><br /> <input type="text" id="codehtml" value="<img src="http://imageplanet.site90.net/' . $upload_path . $filename . '">" onclick="javascript:this.focus();this.select();" readonly="true" /><br /> <label for="codebb">IMG code:</label><br /> <input type="text" id="codebb" value="[IMG]http://imageplanet.site90.net.info/' . $upload_path . $filename . '[/IMG]" onclick="javascript:this.focus();this.select();" readonly="true" /></p></div> </span></font>'; // It worked. else echo '<font size="4"><font color="red">There was an error during the file upload. Please try again.</font</font>'; // It failed :(. ?> <form action="upload.php" method="post" enctype="multipart/form-data"> <p> <label for="file"><font color="white">Select a image:</font></label> <br><br> <input type="file" name="userfile" id="file"> <br /> <button>Click Here To Upload</button> <p> <br> <br> <font color="#006FFF"><span style="font-family: Criovision; font-weight: normal; font-style: normal; text-decoration: none; font-size: 15pt;">Max File Upload Size: 1.5MB<br></span></font> </div> </span> i just want it so it doesn't display that error I have this HTML form that isn't doing anything when the submit button pressed, I am using PHP to validate it. I know I am missing something, can you help me? :/ Thanks in advance! Code: [Select] <?php require("styles/top.php");?> <div id="head_reg"> <div id="head_cen_reg"> <div id="head_sup_reg" class="head_height_reg"> <p class="search"> <label>SEARCH</label> <input name="search" type="text" class="txt" /> <input name="search-btn" type="submit" class="btn" value="SEARCH" /> </p> <h1 class="logo"></h1> <?php require("scripts/links.php"); ?> </div> </div> </div> <div id="content"> <br /> <div id="register_form"> <form action="register.php" method="post" enctype="multipart/form-data"> <center> <table> <tr> <td>Desired Username </td> <td><input type="text" name="username" class="textbox" /></td> </tr> <tr> <td>E-Mail </td> <td><input type="text" name="email" class="textbox" /></td> </tr> <tr> <td>Password </td> <td><input type="text" name="pass" class="textbox" /></td> </tr> <tr> <td>Confirm Password </td> <td><input type="text" name="repass" class="textbox" /></td> </tr> <tr> <td><p class="register"> <input name="reg-btn" type="submit" class="btn" value="REGISTER" /> </p></td> </tr> </table> </center> </form> </div> <center><a href="#" id="showreg">Why register? Click here</a></center> <div id="content_cen"> <div id="content_sup"> <div id="welcom_pan"> <h3><span>Why</span> Register?</h3> <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla vitae diam magna, eget fringilla tellus. Curabitur est velit, suscipit eu faucibus eget, aliquam ac enim. per inceptos himenaeos. Nulla vitae diam magna, eget fringilla tellus.</p> </div> </div> </div> </div> <div id="foot"> <div id="foot_cen"> <ul> </ul> <p></p> </div> </div> <?php if(isset($_POST['reg_btn'])){ $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['pass']; $repassword = $_POST['repass']; if ($username && $password && $repassword && $email){ if ($password == $repassword){ if (strstr($email, "@") && strstr($email, ".") && (strlen($email) >= 6)){ $query = mysql_query("SELECT * FROM users WHERE username='$username'"); $numrows = mysql_num_rows($query); if ($numrows == 0){ $query = mysql_query("SELECT * FROM users WHERE email='$email'"); $numrows = mysql_num_rows($query); if ($numrows == 0){ $pass = md5(md5($password)); $ip = $_SERVER['REMOTE_ADDR']; $date = date("F,d,Y:g:i:s A"); mysql_query("INSERT INTO users VALUES ('', '$username', '$pass', '$email','Member', '$date', '', '$ip', '0')"); } else echo"That email is already in use!"; } else echo"That username is already taken!"; } else echo"That email is too short!"; } else echo"Those passwords do not match!"; } else echo"<script type='text/javascript'>alert('You did not fill out the entire form!')</script>"; } ?> I have a firm that post to my database. When I tested it always posted my information correctly. I require the user to be logged in before they can access the page with the form. I do I ensure that each php variable has a value in it before the data is posted? Any help would be appreciated. I can post my code if needed. I have PHP forms that are not submitting to my database. I think it is something minor but I just can't see it! Can anyone help? At the beginning of index.php, the page holding the forms, I have this: Code: [Select] [b]<?php include("functions/globals.php"); ?> <?php include("functions/userfunctions.php"); ?>[/b] [b]Here are these pages:[/b] [b]globals.php[/b] <?php ob_start();//Required for the redirect to work?> <?php include("loginstatus.php");?> <?php session_start(); ?> [b]((Here's loginstatus.php for good measu [/b] <?php class cUser { public $username = "";//The User Name public $userid = "";//The User ID public $type = "";//The Type Of User } ?> [b]))[/b] [b]And here is userfunctions.php[/b] <?php include_once("databasefunctions.php"); (this holds the connection) $userdbtable = "users"; function GetHeaders() { $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= "To: {$username} <{$email}>" . "\r\n"; $headers .= 'From: My Website <[email]noreply@myswebsite.com[/email]>' . "\r\n"; return $headers; } function CreateAccount($firstname, $lastname, $username, $password, $email, $type) { global $userdbtable; openDatabase(); $firstname = mysql_real_escape_string($firstname); $lastname = mysql_real_escape_string($lastname); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $email = mysql_real_escape_string($email); $type = mysql_real_escape_string($type); $nonencrypted = $password; $password = sha1($password); $result = QuickQuery("INSERT INTO {$userdbtable}(firstname, lastname, username, password, email, type) VALUES('{$firstname}','{$lastname}','{$username}','{$password}','{$email}',{$type}')"); if($result) { $headers = GetHeaders(); $message = "\"Welcome to my website!\"<br /> <br /> Your username is: {$username}<br /> Your password is: {$nonencrypted}<br /> <br /> Signed,<br /> <br /> Me "; mail($email, "Account Creation", $message, $headers); mail("[email]myemailaddress@me.com[/email]", "Account Created", "{$username} has created a new account", $headers); } } function ValidateUser($username, $password) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); if(!mysql_result($result,0,"username"))//Make sure the user exists return "User Does Not Exist"; $temppwd=mysql_result($result,0,"password");//Make sure the passwords match if(sha1($password) != $temppwd) return "Password Does Not Match"; return 1; } function GetUserID($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT id FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); if($result) return(mysql_result($result,0,"id"));//Get the user id else return 0; return(mysql_result($result,0,"id"));//Get the UserID } function GetUserType($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT type FROM {$userdbtable} where username = '{$username}'"); closeDatabase(); return(mysql_result($result,0,"type"));//Get the user type } function GetUserEmail($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT email FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); return(mysql_result($result,0,"email"));//Get the user email } function ConfirmPassword($id, $password) { global $userdbtable; openDatabase(); $password = mysql_real_escape_string($password); $password = sha1($password); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE id = '{$id}' AND password = '{$password}'"); closeDatabase(); if(!$result) return 0; else return 1; } function ChangePassword($id, $password) { global $userdbtable; openDatabase(); $password = mysql_real_escape_string($password); $password = sha1($password); return QuickQuery("UPDATE {$userdbtable} SET password='{$password}' WHERE id={$id}"); } function ResetPassword($email) { global $userdbtable; openDatabase(); $email = mysql_real_escape_string($email); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE email = '{$email}'"); $num = mysql_numrows($result); if(!$num) return 0; $user = mysql_result($result, 0, "username"); $email = mysql_result($result, 0, "email"); $randompwd = RandomPwd(); $temp = sha1($randompwd); $headers = GetHeaders(); mail($email, "Blah blah blah. Your newusername is: {$user}, and your new password is: {$randompwd}. ", $headers); if(QuickQuery("UPDATE {$userdbtable} SET password='{$temp}' WHERE email='{$email}'")) return 1; } function RandomPwd() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } ?> [b]Here is the info on index.php for login and registration[/b] [b]Login:[/b] <?php if($_GET['logout'] == 'logout') { session_destroy(); Redirect("index.php"); } if($_POST['submitted'] == "login") { // echo ValidateUser("Jimmy", "password"); //CreateAccount($name, $password, $email, $type); if(ValidateUser($_POST['username'], $_POST['password']) == 1) { $_SESSION['user'] = new cUser; $_SESSION['user']->username = $_POST['username']; $_SESSION['user']->usertype = GetUserType($_POST['username']); $_SESSION['user']->userid = GetUserID($_POST['username']); Redirect("index.php"); } // CreateAccount("test", "test", "[email]me@website.com[/email]", "user"); } ?> [b]Registration[/b] <?php if($_POST['submitted'] == "register") { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $confirmpwd = $_POST['confirmpwd']; if(!$firstname) $error = "Invalid First Name"; else if(!$lastname) $error = "Invalid Last Name"; else if(!$username) $error = "Invalid User Name"; else if(!$email) $error = "Invalid Email"; else if(!$password) $error = "Invalid Password"; } ?> <?php if($_POST['submitted'] && !$error) { $result = QuickQuery("SELECT username FROM users WHERE username='{$username}'"); if(mysql_numrows($result) > 0) $error = "Be More Creative. Someone Already is Using That Username."; else { $result = QuickQuery("SELECT email FROM users WHERE email='{$email}'"); if(mysql_numrows($result) > 0) $error = "Email Already Being Used. Maybe you already registered."; else if($confirmpwd != $password) $error = "Matching passwords means the second password must be exactly like this first."; else { CreateAccount($firstname, $lastname, $username, $password, $email, "user"); } } } ?> [b]Both forms are here[/b] <div class="btn-show"> <p>Login</p> </div> <div class="pushup-form"> <div class="btn-close"> Close </div> <div class="clear"> </div> <form action="index.php" method="post"> <p style="font-size:14px">Login</p> <p>Username:<input type="text" name="username" style="font-size:12px;"/></p> <p>Password:<input type="password" name="password" style="font-size:12px;"/></p> <p><input class="login" type="submit" name="submitted" value="login" /></p> <p><a href="pwd.php?pwd=lostpwd" style="font-size:10px">Forgot Username or Password?</a></p> </form> <div class="panel"> <form action="index.php" method="post"> <p>First Name:<input type="text" name="firstname" value="<?php echo $firstname;?>" /></p> <p>Last Name:<input type="text" name="lastname" value="<?php echo $lastname;?>" /></p> <p>Username:<input type="text" name="username" value="<?php echo $username;?>" /></p> <p>Email:<input type="text" name="email" class="clear" value="<?php echo $email;?>" /></p> <p>Password:<input type="password" name="password" value="<?php echo $password;?>" /></p> <p>Confirm Password:<input type="password" name="confirmpwd" value="<?php echo $confirmpwd;?>" /></p> <p class="clear"> <p><input class="register" type="submit" name="submitted" value="register"/></p> </p> </form> </div> <p style="text-align:center;" class="flip">Need to Register?</p> </div> [code] These forms open from the right side of my website by clicking "Register." The top of the form has an option for login and by clicking "Need to Register?" The rest of the form expands. Any ideas? My database is set up correctly. MOD EDIT: code tags added. Hello, I have a problem with my login form, when i press the submit button, it returns a valitation error that I made. The error message is triggered when the submit button isn't pressed, but the form still tries to submit. session_start(); include "sources/php/class.php"; $e = $_POST['loginname']; $p = $_POST['loginpass']; $s = $_POST['submit']; if(!isset($s)) { header('location: '.$_SESSION['psite'].'.php?p=error&ploca=login&pid=0'); exit(); } Heres a piece of my code, first i define the variables, then check if the button was pressed, but something is wrong there? - But what? Hope you can help me. Thanks in advance. I am trying to learn how to program in PHP. For a long time i was using WAMP and my localhost. When i ran into trouble i searched the web, watched videos and eventually find a solution.
Trying to upload my scripts into a shared hosting web server i had some difficulties in basic things, like using $_SESSION superglobal variable.
What i want to do is to use a hidden field with a value inside a form, and after submitting the form, to compare the $_SESSION variable to the $_POST variable in order to check for CSRF.
<?php //call all custom functions require_once('Custom_Functions/functions.php'); //session must be send before HTML headers secure_session_start(); ?> <!DOCTYPE html> <html lang="en"> <body> <?php if(isset($_POST['submit'])) { $postvalue = $_POST['input1']; $sessionvalue = $_SESSION['hashed_token']; echo '<br />==========================<br />'; echo '<br />AFTER PRESSING SUBMIT<br />'; echo '<br />==========================<br />'; echo 'Value of $_POST["hashed_token"] = '.$postvalue.'<br />'; echo 'Value of $_SESSION["hashed_token"] = '.$sessionvalue.'<br />'; } $hashed_token = hash('sha256', uniqid(mt_rand(), TRUE)); $_SESSION['hashed_token'] = $hashed_token; echo '<br />==========================<br />'; echo '<br />BEFORE PRESSING SUBMIT<br />'; echo '<br />==========================<br />'; echo '<br />Value of $_SESSION["hashed_token"] = '.$hashed_token.'<br />'; ?> <form action="" method="POST"> <input type="hidden" name="input1" value="<?php echo $hashed_token; ?>" /> <p><input type="submit" name="submit" /></p> </form> </body> </html>In this script i have 1 custom function: a) secure_session_start() function secure_session_start(){ //Set a custom session name $session_name = 'TESTSESSID'; ini_set('session.use_only_cookies', 1); ini_set('session.entropy_file', '/dev/urandom'); if (in_array('sha512', hash_algos())) { ini_set('session.hash_function', 'sha256'); } ini_set('session.use_trans_sid', 0); ini_set('session.hash_bits_per_character', 5); ini_set('session.cookie_secure', 1); $secure = TRUE; $httponly = TRUE; $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], $secure, $httponly); session_name($session_name); ini_set("session.save_path", "/home/SESSIONS"); session_start(); }The procedure goes as follows: FIRST COMMUNICATION WITH THE SERVER: The superglobal variable $_SESSION['hashed_token'] is assigned the random hash value, which is then passed to the hidden input field. I then echo it. RESULT: ========================== BEFORE PRESSING SUBMIT ========================== Value of $_SESSION["hashed_token"] = 93438a1b9b72085ce9430291acebdc4cfdee9d001b91a26207aebc22e04689fc SECOND COMMUNICATION WITH THE SERVER: The user press the submit button, the script then checks if the submit button is pressed, and gets in the if statement(because is TRUE). Then i collect the $_POST and $_SESSION values and echo them. New random hash is assigned to the $_SESSION superglobal variable. RESULT: ========================== AFTER PRESSING SUBMIT ========================== Value of $_POST["hashed_token"] = 93438a1b9b72085ce9430291acebdc4cfdee9d001b91a26207aebc22e04689fc Value of $_SESSION["hashed_token"] = 8f176aeb3a09a1b30e0ea862c78625d7c11743da933d366cface3fa238388e57 ========================== BEFORE PRESSING SUBMIT ========================== Value of $_SESSION["hashed_token"] = c3442382b146f03394ad86911018247c57fa19d4a653d0bf6bb9bc7506e88ca0 For me this is very weird. The random hash is assigned to the $_SESSION variable, but when i try to call it after the submit is pressed its giving me a complete different value. If i remove the function secure_session_start() and just use session_start() it works: RESULT (using session_start() ) ========================== AFTER PRESSING SUBMIT ========================== Value of $_POST["hashed_token"] = a5eaaaa38c428af623a599e664ea9c64a2ff0674e18e9250c54e52bbc586b614 Value of $_SESSION["hashed_token"] = a5eaaaa38c428af623a599e664ea9c64a2ff0674e18e9250c54e52bbc586b614 ========================== BEFORE PRESSING SUBMIT ========================== Value of $_SESSION["hashed_token"] = e2d4acc239a747217860d71a80553abd41142dbeb8f6fafab511caff8a081fc4 Any ideas why this is happening? The problem is inside the secure_session_start() function but i cant find out why. Also, when i use the secure_session_start() function and more specifically the ini_set("session.save_path", "/home/SESSIONS"); i am forcing the session to be stored inside the /home/SESSIONS folder. But when i only use the session_start() the session i still gets stored inside that path. I checked my .htaccess and there is nothing storing the sessions in that folder. Why is that? One last thing: When using FIREBUG-->Cookies is see 2 names: the custom one (TESTSESSID) and PHPSESSID(which is the default). Shouldnt i only see the custom session name only? Thanks in advance. Got this page, a player clicks the "accept challenge" button, then it is recorded in the database that the challenge as been started and once the form has been self submitted, the button is disabled. It does what I expect, but I have to refresh the page again for the button to be displayed as disabled. How can I do it so the page is changed once the form has been submitted? Code: [Select] <?php session_start();what but after clicking a button I have to refresh the page again, before the button is displayed as disabled include('functions.php'); connect(); ?> <!DOCTYPE html> <html> <head> <title>University Crusade</title> <link rel="stylesheet" href="css/style.css" type="text/css" media="screen"> <meta name="viewport" content="width=device-width, minimum-scale=1,maximum-scale=1, user-scalable=no"> </head> <body> <?php if (isset($_SESSION['userid'])) { include('safe.php'); if (isset($_POST['start1'])) { mysql_query("UPDATE chal1 SET start1=1 WHERE userid='".$_SESSION['userid']."'") or die ("Could not update start1"); } if (isset($_POST['start2'])) { mysql_query("UPDATE chal1 SET start2=1 WHERE userid='".$_SESSION['userid']."'") or die ("Could not update start2"); } if (isset($_POST['start3'])) { mysql_query("UPDATE chal1 SET start3=1 WHERE userid='".$_SESSION['userid']."'") or die ("Could not update start3"); } ?> <ul id="tab-nav"> <li><a href="stats.php" id="tab-character">Character</a></li> <li><a href="games.php" class="active" id="tab-games">Games</a></li> <li><a href="account.php" id="tab-account">Account</a></li> </ul> <div id="wrapper"> <h2 id="name">Select a Challenge</h2> <ul id="table-view"> <li> <fieldset> <legend>"Easter Egg" Challenge</legend> <div id="rewards"> <p class="instructions"> Find each of the 4 "Easter Egg" barcodes around the university campus. </p> <p> Rewards: Every egg is worth <span class="stat">50</span> XP and <span class="stat">35</span> gold coins. </p> </div> <form action="games.php" method="POST"> <?php if ($start1 == 1) { echo "<br />The value is 1"; echo "<button class=\"buttons\" type=\"submit\" name=\"start1\" disabled=\"disabled\">Accept challenge</button>"; } elseif ($start1 == 0) { echo "<br />The value is 0"; echo "<button class=\"buttons\" type=\"submit\" name=\"start1\">Accept challenge</button>"; } ?> </form> </fieldset> </li> <li class="even"> <fieldset> <legend>Increase Strength</legend> <div id="rewards"> <p class="instructions"> You'll find the barcode in the Sports Centre. </p> <p> Rewards: Every time you visit the Sports Centre you'll receive <span class="stat">2</span> Str. points. </p> </div> <form action="games.php" method="POST"> <?php if ($start2 == 1) { echo "<br />The value is 1"; echo "<button class=\"buttons\" type=\"submit\" name=\"start2\" disabled=\"disabled\">Accept challenge</button>"; } elseif ($start2 == 0) { echo "<br />The value is 0"; echo "<button class=\"buttons\" type=\"submit\" name=\"start2\">Accept challenge</button>"; } ?> </form> </fieldset> </li> <li> <fieldset> <legend>Increase Intelligence</legend> <div id="rewards"> <p class="instructions"> You'll find the barcode in the university Library. </p> <p> Rewards: Every time you visit the Library you'll receive <span class="stat">2</span> Int. points. </p> </div> <form action="games.php" method="POST"> <?php if ($start3 == 1) { echo "<br />The value is 1"; echo "<button class=\"buttons\" type=\"submit\" name=\"start3\" disabled=\"disabled\">Accept challenge</button>"; } elseif ($start3 == 0) { echo "<br />The value is 0"; echo "<button class=\"buttons\" type=\"submit\" name=\"start3\">Accept challenge</button>"; } ?> </form> </fieldset> </li> </ul> </div> <div id="footer"> <a class="buttons" href="logout.php">log me out</a> </div> <?php } else { die (" <div id=\"wrapper\"> <p>Opps! You don't seem to be logged in...</p> <a class=\"buttons\" href=\"index.php\">login now</a><br /> <p>Don't have an account? No worries, just <a class=\"buttons\" href=\"register.php\">register for one.</a></p> </div> "); } ?> Thanks |