I have a webpage that allows users to submit a query and get result in email.The user selects values for three variables and the email address. My problem is that everytime I refresh the page the form resubmits itself with old values and send the email (i.e I am not even clicking on submit query). I tried using $_POST=array() but it is still not working.
Here is my code:
<?php
if(isset($_POST['submit'])){
$varApp= $_POST['App'];
$varConfig = $_POST['Config'];
$varCtrType = $_POST['CtrType'];
$varEmail = $_POST['mailid'];
exec("/py $varApp $varConfig $varCtrType 2>&1",$output );
if ($output[8] == "Empty"){
echo "<div style ='font:22px Arial,tahoma,sans-serif;color:#ff0000'><br>No Data Available! <br></div>";
}
else {
exec(' printf "Please find attached the query result for following selection:\n\nApp: '.$varApp.' \nConfig: '.$varConfig.' \nCounter Type: '.$varCtrType.' \n\n Thanks! " | /bin/mail -s "Database Query Result" -a '.$output[8].' '.$varEmail.' 2>&1', $output2 );
echo "<div style ='font: 18px Arial,tahoma,sans-serif;color:#10ac84'><br><b> Please check your email for result !<b> <br>";
echo '<script language="javascript">';
echo 'alert("Please check your email for result! Submitted Query details: Selected App: '.$varAPP.' Configuration:")';
echo '</script>';
}
$_POST=array();
}
?>
</body>
I have not given the html part here.
So, everytime a user refreshes the page he gets an email again with previous session query results.
Any guidance here is highly appreciated.
Note: I am not using mail or pHPmailer here but that is not what I need to discuss here.
Thanks,
Taken from this answer:
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.
Related
What could be the query or what could be the solution of inserting values in database through html form via PHP but everytime I refresh the page the previously inserted value gets inserted again?
if (isset($_POST["insert1"])) {
$inrtno = $_POST["inrouteno"];
$instp = $_POST["instop"];
if ($inrtno !=''||$instp !='') {
$query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
Anytime you refresh the page you are resubmitting the POST variables, so the PHP still runs. Additionally, your query is in danger of SQL injection. Consider using PDO.
As stated previously (and for my own understanding), every time you refresh the page, the request is sent again. Mind me for forgetting that, thank you #ADyson.
So, a solution for that would be redirecting the user to the same form after the insertion is made.
Assuming this file would be test.php, for example:
if (isset($_POST["insert1"])) {
$inrtno = $_POST["inrouteno"];
$instp = $_POST["instop"];
if ($inrtno !=''||$instp !='') {
$query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
sleep('3');
header('Location: /test.php');
exit();
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
When you reload the page the browser asks you to re-submit the request, so the value gets transferred again. So put a condition when you insert data that will check if the record already exists or not.
I am trying to navigate to a different page whenever a user clicks on a particular link [basically these are user links which navigate to user profile page when clicked].
My problem if I store the SESSION variable and display it in the same page as the link, it echos out all the emails ids corresponding to that user, but as soon as I navigate to a different page,I can see SESSION displays the wrong result [some other email id].
Here is my code.
<?php echo $firstName.' '.$lastName;?>
This link is displayed as many times as there are records in the database.
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'] = $email;
echo $_SESSION['email'];
header('location: home.php');
}
?>
Now if I just echo the email like above on this page itself, it displays all the emails corresponding to that user. Like this.
user1 : emailid1
user2 : emailid2
But as soon as I navigate to home.php, the SESSION variable always prints out the first email only.
home.php
session_start();
echo 'email id is '.$_SESSION['email'];
I know I am going wrong somewhere but any suggestions would be of great help.
Try with below code.
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
session_start();
$_SESSION['email'] = $email;
echo $_SESSION['email'];
header('location: home.php');
}
?>
I'm setting up a RSVP type form on a wordpress page. Everything is sortof working but would like to fine tune things. Since I'm kindof new to PHP I thought I would ask some experts. I'm coming up with two problems.
1) When the page displays it starts checking for the email automatically before hitting submit. Is there a way to show nothing before hitting submit. Right now it is displaying the echo for the else.
When hitting submit the only way I was able to get the page to go to another url was through refresh. I couldn't get the header function to work it just kept going to a blank page.
I appreciate all the help. Here is my code.
<?PHP
if($_POST['email'] != ''){
// the email to validate
$email = $_POST['email'];
$query = mysql_query("SELECT * FROM tablename WHERE rsvpemails='$email'");
}
if(mysql_num_rows($query) != 0) {
echo '<div class="good"><h2>Your email is approved</h2>RSVP please continue to the RSVP form</div>';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=url">';
exit;
}
else {
echo '<div class="bad">Please enter your email address we used for the invite. If you have any questions or problems please email us at none#none.com</div> ';
}
?>
<form method="POST">
<input type="text" name="email">
<input type="button" value="submit">
</form>
One thing to note is that your SQL query is vulnerable to SQL Injection.
https://en.wikipedia.org/wiki/SQL_injection
You should be sanitizing your POST variables, like ->
$email = mysql_real_escape_string($_POST['email']);
To your actual question, however -
Move your if(mysql_num_rows($query) != 0) block into the if($_POST['email'] != '') block so that it only checks for row data if $_POST['email'] is set (and consequently $query will be populated with something).
Here's also some more info on meta refresh tags.
https://en.wikipedia.org/wiki/Meta_refresh
Put entire PHP code in condition.
<?php
if($_POST['email'] != ''){
// the email to validate
$email = $_POST['email'];
$query = mysql_query("SELECT * FROM tablename WHERE rsvpemails='$email'");
if(mysql_num_rows($query) != 0) {
header("location: $url"); // Redirect
exit;
}
else {
echo '<div class="bad">Please enter your email address we used for the invite. If you have any questions or problems please email us at none#none.com</div> ';
}
}
?>
You need to check if a form was submitted, BEFORE you start doing the verification:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, validate it
}
You're running your query only if something was submitted, but checking the database result regardless. So if nothing gets submitted, you STILL check the number of rows returned, which is obviously zero, since you never ran the query in the first place.
Just trying to make a login page in php.. Here the if code is working but else code is not working.. it is also working if code.. instead of printing message..
here is the code:
session_start(); //session starts
$con=mysql_connect('localhost','root','');// connecting to ..........
mysql_select_db('news_db'); //connectin to db
if(isset($_POST['login'])) //if button login is pressed
{
$name=$_REQUEST['username'];//getting name
$password=$_REQUEST['password']; //getting password
$qyer=mysql_query("select * from news_tb where username='$name' and password='$password'"); //selecting fields
$row=mysql_fetch_array($qyer); //fetching values in row
if($row['username']==$name && $row['password']==$password)// condition to match the fields with database
{
header("location:news1.php"); // on else also this page is opening
}
else
{
echo "pls enter valid information"; //redirects to if condition and doesnt print the msg
}
}
Its because by pressing send or whatever, you post the code to the script. All you are doing is checking if it has been posted, not if the variables themselves are empty. Then if you have an empty row in mySQL, you will never use the else.
I have a membership service on my website. Currently when someone logs out they are redirected to logout.php that has this code on it:
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//display success message
echo "<center>You have successfully logged out!<br><a href = '/review-pratt/index.php' class='icon-button star'>Return Home</button></center>";
}
?>
Instead of having the users be taken to "logout.php" and viewing a boring page that says they logged out. I want them to be redirected to index.php. That part is easy, I know.
I am wanting a notification bar across the top to appear notifying them that they successfully logged out. I have tried to do this before and never got anything to work. Any help or suggestions would be appreciated!
Update
I have changed the logout.php code to:
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//Redirect with success message
header('Location: /index.php?msg=' . urlencode("You have been successfully logged out!"));
}
?>
and added the following code to my index.php:
<?php
if ($_GET['msg'])
{
echo '<div class="success_message">' . base64_decode(urldecode($_GET['msg'])) . '</div>';
}
?>
And when I log out I receive this error:
Warning: Cannot modify header information - headers already sent by (output started at /home/content/38/10473938/html/review-pratt/business_profiles/logout.php:19) in /home/content/38/10473938/html/review-pratt/business_profiles/logout.php on line 35
you could do something like this:
header('location: index.php?status=loggedout');
and in your index.php file just look to see if status is not empty, and show a div with the status like this:
<?php
if(!empty($_GET['status'])){
echo '<div>You have been logged out!</div>';
}
?>
also inside that if statement you can clear user session aswell..
There are many solutions to this, but almost all of them require logout.php to pass the message, and index.php to have code to display the message.
My preferred method is to pass the message as a URL parameter. Use header to re-direct, use base64_encode to shorten the text in the url, and url_encode to make sure that the URL doesn't get junked up.
//Redirect with success message
header('Location: /index.php?msg=' . urlencode(base64_encode("You have been successfully logged out!")));
Then, on your index.php page
if ($_GET['msg'])
{
echo '<div class="success_message">' . base64_decode(urldecode($_GET['msg'])) . '</div>';
}
Edit: If your headers have already been sent out (have you echoed out some text on a line above these?), you can use Javascript to do the redirection.
Replace header('Location: ') with this: echo '<meta http-equiv="Refresh" content="0;url=http://example.com/index.php?msg=' . urlencode(base64_encode('You have been successfully logged out!')) . '">';
You could use "Noty" plugin to enable notifications on your web-app.
see here: http://needim.github.com/noty/
Implementation should look something like that:
Redirect the user to index.php?logout=1
Use the Query String parameter to populate a hidden field.
Use noty to display the hidden field value when page loads.
Here is a code example:
<?php
if(!empty($_GET['logout'])){
echo '<input id="logoutMsg" value="You have been logged out!" />';
}
?>
<script>
var logoutMsg = $('#logoutMsg').val();
var noty = noty({text: logoutMsg });
</script>
If you want to redirect right after the success message, then use the following code:-
<?php
//check if the login session does no exist
if(strcmp($_SESSION['uid'],”) == 0){
//if it doesn't display an error message
echo "<center>You need to be logged in to log out!</center>";
}else{
//if it does continue checking
//update to set this users online field to the current time
mysql_query("UPDATE `users` SET `online` = '".date('U')."' WHERE `id` = '".$_SESSION['uid']."'");
//destroy all sessions canceling the login session
session_destroy();
//display success message
echo "<center>You have successfully logged out!
echo '<meta http-equiv="Refresh" content="0;url=http://url.which.you.want.to.be.redirected.to">';
}
}
?>