<body>
<?php
if(isset($_POST['vendor_add_submit'])){
//INSERT INTO DB
unset( $_POST['vendor_add_submit'] );
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<label>Email</label>
<input type="text" name="vendor_email" value="" />
<input type="submit" name="vendor_add_submit" value="SAVE" />
</form>
</body>
unset( $_POST['vendor_add_submit'] ); is used to prevent more than one time insertion into db on page refresh. I tested with print_r($_POST['vendor_add_submit'] ) before and after the unset and found that the unset() function does not work.
How can I achieve the purpose of the unset function, plz?
Unset isn't going to stop the refresh from being able to replay the POSTed data to the script. The unset function eliminated it for the remaining execution of that script, but a refresh is a fresh execution.
You could simply re-direct the browser to the entry pageafter doing your insert, that way a subsequent refresh will be safe.
//INSERT INTO DB
//...
header('Location: samepage.php');
exit();
I'm sure there are other ways to accomplish this as well.
Your approach cannot work, you would just be editing the data that the PHP script has recieved. If the user refreshes the browser then it will submit the same data again, and PHP will populate a fresh new $_POST with the data the browser sent.
If you want to stop a refresh resubmitting the data, then use the POST-REDIRECT-GET pattern.
The $_POST value will only be removed on the Server-Side Meaning that on that one request PHP will not be able to see or use it (You removed it).
But you are rendering the Submit button on the page's HTML so every time someone visits the page and submit the form they will submit the value again. And you will remove it again for PHP on that current request. So every request would insert the data into the database.
You might want to rather look into rather checking if the record already does exists (OR if the user has one already, not sure what you want) and then redirect them away from the page using header('Location: otherpage.php');.
Hope that helps...
Related
I want to check if the form was filled out correctly but the alert appears after I load the page. I guess a site refresh is submitting the login button.
I try to check the incoming data and if they are wrong, it should show an alert.
<?php
$alert = "";
if ($_POST['username'] == null || $_POST['password'] == null){
$alert = "Please fill in all fields!";
}
if ($alert){
echo $alert;
}
?>
<form method="POST" action=""> <!-- reloads this page -->
<input type="text" name="username"/>
<input type="password" name="password"/>
<button type="submit" name="login">Login</button>
</form>
If I open the page, the alert appears instantly. How should I do the check, that the alert does not appear after the first load.
I hate to suggest javascript as the solution, but in this case, javascript is the best solution.
With javascript, you can interrupt the form submission process - do some stuff (such as validate the form fields) and then either return false (cancels the submit) or do nothing (the form submission will continue). But Barmar is straight-on correct with his explanation of what is happening. (Of course he is: it's Barmar )
So the overview is:
Use $('#yourFormID').submit(function(){}) to trap the form submission process
Inside that function, perform your field validation
If a field fails validation, display a message and return control to the user
If all fields validate okay, do nothing else - the form will finish submitting as if there was no interruption at all.
Here is another question/answer that demonstrates how to do that.
How to direct a user directly to a form
The IF-Statement is fine, so your problem is in your Session or Cache.
You can destroy your Session, if you close your browser, but this maybe need some time to destroy the session, so you could delete cache, cookies, etc in your browser setting.
But you can also use session_destroy(); in php to destroy all Variables of POST or GET.
I have a script that pulls an XML page and uses a form to update and save the values back. When I click the submit button it works, but then the page loads blank. I just want the page to refresh. There are about 100 different threads on this, and nothing I have tried has worked to resolve the issue. Out of curiosity, I just tried to run the window.location script and nothing else, and this piece actually doesn't work at all.
<?php
//if (isset($_POST['submit'])) {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//$ctstatus->nodeValue = $_POST['ctstatusform'];
//htmlentities($xml->save('test.xml'));
echo '<script type="text/javascript">window.location="http://google.ca";</script>';
}
?>
The inner contents of the form don't really matter at this point, I just want it to refresh the page after I hit the submit button.
I previously used isset but from reading it seems like that's obsolete, and my form action="" used to be blank. Either way my XML save works, but nothing to refresh the page. I also tried header and that didn't work either.
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class="save" name="submit" type="submit" value="Save" />
</form>
Out of curiosity I tried an onClick function with a timer and this does work but it's not ideal at all, especially because the page could technically refresh before the POST is finished writing the file. I'd rather know why the echo doesn't execute.
PHP redirect would most likely be preferable to JavaScript redirect.
Typical structure when posting back to same page:
<?php // cannot be any output before this (space, linefeed, etc)
if(isset($_POST['submit']) {
// do stuff with the submission
header('Location: http://google.ca');
exit;
}
// does your script need to do some other data retrieval or calculation? do it here.
?>
<html>
... snip ...
<form method="post">
... snip ...
<input class="save" name="submit" type="submit" value="Save" />
</form>
Following this simple structure for procedural scripts--
Deal with user input / redirect
Do logic (collect, manipulate data)
Show output (using php only to insert variables and looping)
will help you avoid a lot of heartache and technical debt.
Okay, I have gotten this sorted out. It turns out that the problem was embarrassingly simple, but maybe will assist someone in the future. Along with reordering my code, as Tim suggested. I specified HTML as the DOCTYPE, and that worked to resolve the issue. I no longer need to worry about refreshing the page after submit, because it refreshes as it should automatically. Thank you to everyone who commented.
It seems pretty simple but I can't find a good way to do it.
Say in the first page I create a variable
$myVariable = "Some text";
And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).
How can I achieve this?
Thanks!
HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
GET and POST
You can add the variable in the link to the next page:
Page2
This will create a GET variable.
Another way is to include a hidden field in a form that submits to page two:
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
And then on page two:
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.
The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.
Thanks for the answers above. Here's how I did it, I hope it helps those who follow. I'm looking to pass a registration number from one page to another, hence regName and regValue:
Create your first page, call it set_reg.php:
<?php
session_start();
$_SESSION['regName'] = $regValue;
?>
<form method="get" action="get_reg.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
Create your second page, call it get_reg.php:
<?php
session_start();
$regValue = $_GET['regName'];
echo "Your registration is: ".$regValue.".";
?>
<p>Back to set_reg.php
Although not as comprehensive as the answer above, for my purposes this illustrates in simple fashion the relationship between the various elements.
Passing data in the request
You could either embed it as a hidden field in your form, or add it your forms action URL
echo '<input type="hidden" name="myVariable" value="'.
htmlentities($myVariable).'">';
or
echo '<form method="POST" action="Page2.php?myVariable='.
urlencode($myVariable).'">";
Note this also illustrates the use of htmlentities and urlencode when passing data around.
Passing data in the session
If the data doesn't need to be passed to the client side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.
Security
Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file, or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?
As you are clearly just getting started here, its worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!
There are three method to pass value in php.
By post
By get
By making session variable
These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-
$a=$_POST['field-name'];
If we require the value of variable on more than one page than we can use session variable as:-
$a=$_SESSION['field-name];
Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page
session_start();
GET method are generally used to print data on same page which used to take input from user. Its syntax is as:
$a=$_GET['field-name'];
POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.
try this code
using hidden field we can pass php varibale to another page
page1.php
<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
<input type="hidden" name="text" value="<?php echo $myVariable; ?>">
<button type="submit">Submit</button>
</form>
pass php variable to hidden field value so you can access this variable into another page
page2.php
<?php
$text=$_POST['text'];
echo $text;
?>
Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.
**page 1**
<form action="exapmple.php?variable_name=$value" method="POST">
<button>
<input type="hidden" name="x">
</button>
</form>`
page 2
if(isset($_POST['x'])) {
$new_value=$_GET['variable_name'];
}
It works.
Send data throw URL, without form.
$upit = "SELECT * FROM usluga";
$data = $mysql->query($upit);
while ($row = mysqli_fetch_object($data))
{
echo "<a href='"."index.php?tretmanId=$row->tretman_id"."'>$row->naziv</a>";
echo "<br><br>";
}
and you can get this value on the target page with "$_GET['name from URL']", like this
$TrermanIdFromUrl = $_GET['tretmanId'];
You can for example call the page you want by including variables in the url:
header("Location: ../signup.php?newpwd=passwordupdated");
And on your signup.php page, you would have
if (isset($_GET['newpwd']) && $_GET['newpwd'] == "passwordupdated") {
//code here
}
I have a form where i should make the form submit(request to a service) only if the form field is changed, If the field is not changed when the user refresh the page it should not submit the form again.
OBJECTIVE is to reduce the number of form submission as possible, So if the user has the same entered data and he refresh, we shouldn't waste the previous returned datas and try to give new request and show the same datas.
Instead it should be submitted only if the TEXT(searchdirectory) is changed. So there won't be repeating request for same datas.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label>TEXT :</label>
<input type="text" id="search_dir" name="searchdirectory"
value="<?php
if (isset($_POST['searchdirectory']))
{
echo($_POST['searchdirectory']);
}
?>"
/>
<input type="submit" value="Search" name="submit" id="searchB"/>
<?php
if (isset($_POST['submit']))
{
//functions to show results queried from searchdirectory
}
?>
</form>
I guess this would be to deal with refresh behaviour of browsers, Is there a way to stop the form submission if user refresh the page. It should show the same datas.
Use redirect when form data was sent at first.
<?php
if (isset($_POST['submit']))
{
//do function
header("Location: http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
?>
Where "http://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] - is a link to which the user will be redirected after form submit.
There is two ways to go. But I try to address your objective, and not your specific question :)
You can forward the browser to a new url after form submit. This is a very normal procedure. So that when your form submits the browser redirects immediately to a normal GET URL. Now if the user hit refresh the form is not submitted again.
2 The other approach that you should use if the form is login dialog etc. Add a one time session key to a forms hidden field, and store the same key in on the server. Now if the user submits the form check that the keys match. If they do accept the submit, and clear the key. If the user now hit F5 again, and you've already removed the key, simply reject the values submitted.
why don't you clear the form after submitting, or add session for each submit request
Sorry I have posted this question and I googled it alot still Im unable to solve this
I have a php page that has a form and when user clicks refresh or F5 it creates duplicate values in the database and also a message is alerted to the user, indicating resubmitting may insert duplicate values in database.My boss dont want that alert box of the browser to user and also insertion of duplicate values into the database
I know its header(). I read lot of header() in php manual and also server_name functions but still I tried in many ways putting in the top but cant solve it. its very important. can anyone please help me with a sample of code explaining the way to do.any help is greatly appreciated.
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
demo.php
<?php
$firstname = $_POST['fname'];
?>
Tell me what should i add in the demo.php page to stop it from submitting the form again and again and also if user clicks back button on the browser it should not direct to the previous page , it should still redirect to current page.
So if user clicks refresh or back button it should redirect to current page only and should not insert any duplicate values and also alert box should be disabled.Please explain me what to do here, im in deep help.Thanks
There's lots of things wrong with your code, and lots of ways to mitigate the impact.
First, why are you creating duplicate entries?
In addition to the problem of bad data is also implies that your site is vulnerable to CSRF. Go read up on how to prevent CSRF with single-use tokens.
If you've got performance problems with your site, then users will often click on the submit button multiple times. While addressing the duplicate submission problem on the database, use javascript to disable the submit links on the page and provide visual feedback that the page is doing something.
Redirects are not the way to solve the problem.
My boss dont want that alert box of the browser
Are you talking about the duplicate post alert? While you can get around this using PRG, that creates other problems.
You must post a unique id (session_id) and save it in the database.
When your registration, test if the session_id is already present. If so, send a message to THE USER. "You have already post out this form"
The code:
<?php session_start; ?>
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
<input type="hidden" name="session_id" value="<?php echo session_id();?>">
</form>
demo.php
<?php
//test session_id in database
$session_id = session_id();
mysql_connect('localhost','xxx','xxx');
mysql_select_db('xxx');
$return = mysql_query("SELECT COUNT(*) AS nb_data FROM TABLENAME WHERE session_id='".session_id()."'");
$data = mysql_fetch_assoc($return);
if ($data['nb_data'] == 0){
echo 'Your message';
}
else{
$firstname = $_POST['fname'];
//.....
header('location:xxx.php')?
}
?>
I would use php header function to replace the current location so if the user clicks refresh, it won't repost the information and a session to store the posted value and check for resubmissions.
demo.php
<?php
session_start();
if($_POST)
{
if(!isset($_SESSION[fname]))
{
//database queries here
}
$_SESSION[fname] = $_POST['fname'];
header('location:demo.php', true); //true replaces the current location
}elseif(!issset($_SESSION[fname])){
header('location:form.php');
}
$firstname = $_SESSION[fname];
?>
form.php
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
You need ON DUPLICATE KEY , this will update the record instead of creating a copy of it :
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
so it wouldn't matter if they hit refresh or resubmit, if the record existed already it would just get updated.
The solution will be to redirect the page after database operations like insert, update and delete
pageName: test.php
if(isset($_REQUEST['deleteBtn']))
{
$emp_id=$_REQUEST['emp_id'];
$count=mysql_query("delete from employees where emp_id=$emp_id");
header("location:test.php");
}
This way if you click F5 or back button the form data will not get posted again.
What you want is to embed a session id in your form when you create it, and to track that session id on the server. Then, when the form is submitted and you are processing the form on the server, if the form was submitted more than once, you can overwrite the first submission in your database, or respond with an error message, or whatever. (Show the popup only on the first submission, whatever.)
An easy way to do this is to generate a session id, send it as a hidden field in the form, and when the form is submitted store the session id in your database with the constraint that the session id be unique.