PHP - How To Stop A Form Submitting When Page Is Refreshed.
Hi Guys,
Im trying to create a registration form so users can sign up to my website, however i have noticed that when the page is refreshed the form automatically submits. Please could somebody help me stop this? Thanks <body> <form name="registration_form" method="post" onsubmit="return Validate();"> First Name: <input type="text" name="first_name"><br /> Last Name: <input type="text" name="last_name"><br /> Email: <input type="text" name="email"><br /> Confirm Email: <input type="text" name="confirm_email"><br /> Username: <input type="text" name="username"><br /> Password: <input type="password" name="password"><br /> Confirm Password: <input type="password" name="confirm_password"><br /> <input type="submit" value="Register"> </form> <?php $connect=mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database",$connect) or die (mysql_errno().":<b> ".mysql_error()."</b>"); $insert_query = 'insert into users (username,first_name,last_name,email,password) values ( "' . $_POST['username'] . '", "' . $_POST['first_name'] . '", "' . $_POST['last_name'] . '", "' . $_POST['email'] . '", "' . $_POST['password'] . '" )'; mysql_query($insert_query); ?> </body> Similar Tutorialsi have a problem i just noticed....i've built a shopping cart that totals quantities of items and shipping etc then a submit button to a payment page... but if a user refreshes the same page after first coming to the cart page it messes up all the totals and data..... i know this has to be a common problem with webpages... does anyone have any advice on combating this issue? any advice is much appreciated..thanks! How do I stop the below form from submitting if any field or atleast if field Weight is blank? also an error echo would be great. I have been trying to figure this out but cant do it. Code: [Select] <table width="500" border="0" align="center" cellpadding="10" cellspacing="0"> <tr> <td> <form action="insert.php" method="post"> <input name="Date" type="hidden" value="<?php PRINT "$today"; ?>" /> First Name: <input type="text" name="Firstname" /><br><br> Last Name: <input type="text" name="Lastname" /><br><br> Weight: <input type="text" name="Weight" /><br><br> <input type="submit" value="Submit Profile" /> </form> </td> </tr> </table> Hello all, As the title says: For sake of example, let's say I have a form with a couple text boxes and a submit button. When you hit submit, the data from the text boxes is translated into a database record. Howver, refershing the page will this record again and again -- which I do not want. How can I prevent this? Keeping in mind the business logic of my applicatoin allows the same record to be entered twice -- however, it should only happen if the user intentionally visits the form agian, and enters the same data. It should not happen on a page refresh. I assume this is a common problem...? Any thoughts? Thanks! Ive tried using header and form action and my page will not load into another page after submitting ! Any ideas?
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Task2 - App</title> <meta name="description" content="The Task2 App"> <meta name="author" content="SitePoint"> </head> <body> <h1>Task 2 - Web App</h1> <br><br> <div class ="submission"> <form action="" method="POST" name='submit'> <label>N:</label> <input type="text" name="number-entered" id="number"/> <input name="form" type="submit" value="Submit"/> <br><br> </form> </div> </body> </html> <?php $number = $_POST['number-entered']; $form_result = $_POST['form']; if(isset($form_result)) { if(($number < 5) || ($number > 25)) { echo 'Input out of range'; } else { $number = $_POST['number-entered']; foreach ( range(1, $number) as $i ) { $triangle_numbers[] = $i * ( $i + 1 ) / 2; } //make a file $contents = fopen('gs://a1-task22020.appspot.com/triangular_' .$number. ".txt", "w"); fwrite($contents,implode(',', $triangle_numbers)); //open the file $contents = fopen('gs://a1-task22020.appspot.com/' . $content, 'w'); //re-open the document if you put something in it fwrite($contents, $number); fclose($contents); } } ?>
people on my forum (speakwhatsreal.com) submitting blank spaces Code: [Select] like they just copy/paste the blank space in the textarea and how do I check input on that, does strlen work? Hi All, Is there any way that PHP can detect if a page has been refreshed? Basically I have a form that when submitted, inserts a row in to a database, but I am finding that when I refresh the page, it repeats the insert statement. Any ideas? Thanks Matt How can I detect if the page was refreshed? I thought the following worked, however, after much head scratching, discovered it does not work for a POST request using the Chrome browser. Thanks
<?php $refresh=isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0'; echo(($refresh?'refresh':'not refresh').'<br>'); echo('$_GET<pre>'.print_r($_GET,1).'</pre>'); echo('$_POST<pre>'.print_r($_POST,1).'</pre>'); ?> <ul> <li><a href="refresh.php?id=1">one</a></li> <li><a href="refresh.php?id=2">two</a></li> <li><a href="refresh.php?id=3">three</a></li> </ul> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input type="text" name="text" value="hello"> <input type="submit" name="submit" value="submit"> </form> when the user clicks the submit button from a html form, it needs to go back two pages with that loaded page refreshed. for the javascript i only have history.go(-2); with php, I have tried cookies and sessions which i discovered that neither will work because the loaded page is not refreshed. I could do a html body onload but that would break the w3c validator. what are my options?
Hi guys, On my website i have a message inbox, and the code below is used to display and delete messages. When i tick the checkbox and click the delete button, the message gets deleted. The page appears to refresh after the submit button is clicked, however the message remains in the inbox, i have to refresh the page a second time for the message to disappear. Im trying to get it that when i press the submit button and the page reloads, the message disappears. Does anybody know of a technique that im not using or does anybody know if the code im using is wrong? <?php $messages_query = mysql_query("SELECT * FROM messages WHERE recipient='$username'"); if (mysql_num_rows($messages_query) > 0) { echo "<form method='POST' action='inbox.php'>"; while ($messages_row = mysql_fetch_array($messages_query)) { if ($messages_row['message_read'] == 0) { echo "<div style='background-color:#FFCCCC;'>"; } $message_id = $messages_row['id']; echo "<a href='message.php?id=$message_id'>"; echo "From: " . $messages_row['sender']; echo "Subject: " . $messages_row['subject'] . "<br />"; echo "</a>"; echo "<input type='checkbox' name='message[]' value='$message_id' />"; if ($messages_row['message_read'] == 0) { echo "</div>"; } } } else { echo "No messages"; } if ($submit) { foreach ($_POST['message'] as $msgID) { mysql_query("DELETE FROM messages WHERE id='$msgID'"); } } ?> <html> <input type="submit" name="submit" value="Delete" /> </form> </html> Many thanks When I use the following code, it doesn't print out "test" until after I refresh the page. unset($_SESSION["product"]);
if ( !empty($_SESSION["product"]) && ($_SESSION["product"] != NULL)) { When I use: var_dump($_SESSION["product"]); It shows: array(0) { } I'm wondering it that's the problem. That it's array(0) when it should be array(). 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 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 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 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. Hi - 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 !! 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. This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=316807.0 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 |