I'm a beginner in PHP. In my code, i want the php script to be executed only when the submit button is clicked (set). So when the page is refreshed, the isset() function should return false. Here is the code for test.php
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else{
$username = "";
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="test.php">
<Input Type = "text" Value ="<?php print $username?>" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</form>
</body>
</html>
After clicking the login button the script is executed and the output is "You are not a member", but when i refresh the page,the message from the script still remains on the screen. I believe isset() should return false until i click the button again? What's wrong with the code.
Thanks.
Realized that my comment was really an answer...
When you "refresh", you refresh the page INCLUDING the POST data (since that was the last "request" made). You would have to re-enter the address of the page to clear it. Sometimes you see "do you really want to send this form again?" prompt when you refresh - this is why...
Isset() is used to check if a variable example : $variable is actually "set" and is not null. Also when doing a refresh you also refresh the action you have committed and the form data that you have passed. You can think of it as this :
If you go to a shopping website and they tell you to not refresh while your order is processing that means that if you refresh your post data is submitted again meaning you buy 2 microwaves rather then 1 :)
So in coding it will look like this :
if (isset('$_POST['username']')) {
$username = $_POST['username'];
if($username == 'letmein') {
echo ("welcome back, friend!");
}
}
Hopefully this helps a bit. Good luck! Also if your ever on the "John" and need reading material take a look at the php manual page!
Refreshing the page will post the already posted form variables again so every time you refresh your page you are re submitting your form and by this you will have always the isset condition to true :)
I f you need more explaining tell me :)
Related
I have a form, which redirects the user to "page1.php" after the form is submitted. What I want to do is to redirect the user to "page2.php" after the form is submitted, but I need to make sure that the POST request was sent. Example:
<form action="page1.php" method="POST">
<input type="text" name="username" />
<input type="text" name="age" />
<input type="submit" value="" />
</form>
When the user clicks on Submit, it redirects him to page1.php. I want to redirect him to page2.php, but I need to make sure that the data is sent to the server. I can't use AJAX. Is there any way to do it with cURL or something like that? Any examples?
Thanks!
I guess this works !!
In page1.php
<?php
//do establish session
//and check for the input fields obtained via $_POST
if(isset($_POST['name_of_your_field']) && !empty($_POST['name_of_your_field'])){
if(!mail($to,$subject,$message)){
header('location:form.php?msg=error');
}else{
header('location:page2.php?msg=succes');
}
}
?>
You can check if the POST request was sent with something like:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// do something...
}
You can create a hidden input in your form and send additional info about the form that is submitted, e.g. action.
Inside you will do your magic and redirect user with:
header('Location: page2.php');
exit();
In your 'page1.php' processor, add a 'header' redirect to 'page2.php'.
header("Location: page2.php");
exit;
you could do a check if query is complete
example
<?php
$query=mysqli_query(".......your query statement")or trigger_error(mysqli_error());
if($query){
header("Location:page2.php");
}
else{
die('error');
}
?>
In your situation, you can just simple check for the posted data. Like
$username = $_POST['username'];
$age = $_POST['age'];
if($username&&$age){ /* This is to check if the variables are not empty */
// redirect to page2
}
It is logical that if those are not empty, meaning they are posted. Even if they are empty, as long as you get there, that means it was posted. There is no need to check if posted or not, what needs to be checked was, if posted data was there.
I hope I made it clear. ^_^ but making sure is not bad at all. Happy coding friend.
I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.
current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.
If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.
To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.
Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.
The problem is the form is getting submitted again, you can make header redirect to this same page,
header("location: index.php) after updating your database and this will solve your issue.
Create one button in html
<input type="submit" name="submit"/>
In php Code, you can write like
<?php
if(isset($_POST['submit']))
{
//place your total code here
}
?>
As soon as the form is submitted once it has got the $_POST-Array in the site request. When you reload the page after the first submit, it will always send the data again.
You got multiple possibilities to resolve this problem:
1)
Reload the page after the execution of the PHP code. To do so put the PHP code at the top of the page (before writing anything in HTML) and reload the page after the execution of the query:
if(isset($_POST["save"])) {
/* MySQL Query */
$back = $_SERVER['HTTP_REFERER'] ; // the site who called this site
header("Location: $back") ; // Link back to this site
}
2)
Personally I prefer to execute my PHP scripts with an Ajax call, which would look as follows in jQuery.
function ajaxCall()
{
$.ajax({
type: "POST",
url: "handler.php",
data: {save: 1, textfield: $("#textfield").val()}
}) ;
}
Don't forget, that the forms action isn't the redirect to another site anymore, it is the call to this function ajaxCall. If you want more fields to submit, have a look at the serialize-function. The handler.php-file contains only your php-Code:
<?php
ob_start();
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
exit(0) ;
?>
In the ajax function you could also handle what happens when the call is successful (e.g. redirect). Have a look at the $.ajax-reference of jQuery. If you want you could also use ajax without jQuery.
3)
You could also make your page in action similiar to the handler.php in the second possibility.
<form action="handler.php" method="POST"></form>
In this case you had to replace the exit-statement with the $back and header-call in possibility 1 (similar to the response of Konerak).
Is there any way to know if the page was refreshed or data was posted data on the same page?
To be little more specific:
I have to post data on the same page.
This affects the where condition of the query.
If the page was refreshed, then the where condition must be 1.
Otherwise, where condition contains some id to get specific data from
the table.
Your best bet is to use PHP sessions, along with your submitted data in $_POST. Let's presume for this example you have the following form:
<form action="this_page.php" method="post">
<input type="text" name="important-info" />
<input type="submit" value="Submit" />
</form>
Then elsewhere in the same page is the PHP code:
<?php
// example code
session_start();
if (!isset($_SESSION['previousVisitor']) && isset($_POST['important-info'])) {
// this is a new visitor who has submitted the form
$_SESSION['previousVisitor'] = true;
// where is based on $_POST['important-info']
} else () {
// where is 1
}
// close the session after you do what you need - this stops large pages causing hang
session_destroy();
Please note that they can clear this session variable by deleting their cookies.
on the top of the page just include
if(isset($_POST['name']) && $_POST['name']!=''){
//your code goes here
}
I suggest you to check request
//Here goes the code
session_start();
$counter = 0;
$counter = (isset($_SESSION['param'])) ? $counter++ : 0;
if($counter == 0)
echo "data GET or POST";
else
echo "refreshed";
** If you want only POST param, use $_POST instead of $_REQUEST
I have faced a problem in all of my php projects is that since i used OOP is that if there is a user submitting a form
when it goes to processing it and if it has an error i save a message in the session and redirect them to the same page
this is a sample and of course when it redirects it wipes all the fields that was there
like let's say i have a register form that had
<?php if(!empty($message)) { echo $message } ?>
<form action ="forms/register.php">
first name: <input type="text" name="first_name" />
username:<input type="text" name="username" />
<input type="submit" value = "submit" />
</form>
and this is what the code in forms/register.php
if(isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$username = $_POST['username'];
if(empty($first_name) || empty($username) {
$session -> message("please fill in all the fields");
redirect("../register.php");
} else {
// do something else like insert query
}
}
my problem is if first_name or user_name is empty and it redirects to register.php
and it echos the error message no problem in that
but the fields are empty the first_name and the user_name are empty
so the user has to fill it all again
so one of my friends suggested to save it in the session or something
so i would like to know if that is possible then how and what i mean by how so nobody would get it wrong, i mean the way not the code to just copy it and paste it
Thanks in advance
and sorry for being long and annoying
You can store whatever values you want to keep persisted in the form after the page redirects in session variables, then retrieve those values on the form page and echo them in the value attribute of the form elements.
session_start(); $_SESSION['nick'] = $_GET['nick'];
more / better examples:
http://php.net/manual/en/function.session-start.php
Not sure what issue you exactly are facing (also what $session is inside your workflow?).
However, i recommend using PHP inbuild session support.
http://php.net/manual/en/features.sessions.php
From the above link itself:
<?php
session_start();
if(isset($_SESSION['views']))
{
$_SESSION['views']=$_SESSION['views']+1;
}
else
{
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
}
?>
Above code simply keeps track of page views. $_SESSION variable persists between page loads and you should be using the same for all your session requirements.
I'm trying to write my first PHP script (hopefully). I want to send user input from a form inside an HTML page to a PHP script and validate them inside script. then, if there is any problem with input data, return to first page and highlight wrong fields. else go to another page (something like successful).
How do i send feedback from second script to first page without using forms?
In short, you'd have something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$name = $_POST['name'];
if ($name !== 'Fred') {
$errors[] = 'Please enter "Fred"';
}
... validate more fields ...
if (count($errors) == 0) {
... form is ok ...
header('Location: everything_is_ok.php');
exit();
}
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
Enter 'Fred': <input type="text" name="name" value="<?php echo htmlspecialchars($name) ?>" /><br />
<input type="submit" />
</form>
Basically: Have the form page submit back to itself. If everything's ok, redirect the user to another page. Otherwise redisplay the form.
Just make your Form POST to itself, then in your PHP check the values and if they are valid, don't display your form and do your submit code. If they are invalid, display the form with the values and errors displaying.
Reload the first page and send the feedback in the session, for example. If session['errors'] exist, echo them. Note you'll have to include some php tags in your html page anyway.
Use a session... here's a link to help you get started: http://www.tizag.com/phpT/phpsessions.php