Refresh button on Browser - php

I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!

Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference

It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.

You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}

Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.

Related

Redirect page after delete account in php

I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help

Sessions in php do not load profiles, php + mysql

I need to be able to orientate with a php code that communicates with data from a mysql database, this file is called "validate.php". Its main functions are to verify that there are no empty fields at the time of login, and assign a profile if a user has value 1 and another profile when the value is 0 in the records of the table "users"
The idea is that "validate.php" check the user and direct it to a page according to their profile, but I can not do that.
My code is:
<?php
require('access_db.php');
session_start();
if(isset($_POST['send'])) { // We verify that the form data has been sent
//We verify that the user_name and the user_pass fields are not empty
if(empty($_POST['user_name']) || empty($_POST['user_pass'])) {
echo"
<script>
alert('Please enter your username and password correctly ');
location.replace('login.php');
</script>
";
}else {
//"Clean" the form fields of possible malicious code
$user_name = mysqli_real_escape_string($link,trim($_POST['user_name']));
$user_pass = mysqli_real_escape_string($link,trim($_POST['user_pass']));
// We verify that the data entered in the form match those of the DB
$query=mysqli_query($link,"select user_id,user_name,user_admin FROM users WHERE user_name='".$user_name."' and user_pass ='".$user_pass."'");
$row = mysqli_fetch_array($query);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row["user_name"];
$_SESSION['user_admin'] = $row["user_admin"];
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
{
}
}else{
header("Location: login.php");
}?>
My main problem is here:
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
When I login with my admin user in my page "login.php" you should check the information and go to a page according to your profile, only appears in the browser "http://localhost/proyect/validate.php" and the text "dashboard" on the page, But, if I write in the browser "http://localhost/proyect/dashboard.php" load the page with all the information.
I do not know what I'm doing wrong.
Someone can help me, I'll be very grateful, I've been on this for days.
Thanks.
Don't print, try this instead:
if($_SESSION['user_admin']==1){
header('location:dashboard.php');
exit;
}else{
header('location:dashboard2.php');
exit;
}
Thanks for the suggestion Magnus Eriksson
you need to redirect not echo out the contents of the php file
and also do check for { as there are extra ones
if($_SESSION['user_admin']==1){
header("Location: dashboard.php");
}else{
header("Location: dashboard2.php");
}

Click the button, save the data and go to next php page

I don't know what is the problem. After i click the button, it only the data into database but will not go to next php page. Help me find out what is problems. Thank you.
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
header('Location: mcreport.php');
if($AddMCResult)
echo "<script>alert('Record Added.');</script>";
}
//button
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit"/>
Try this
<?php
if(isset($_POST['btnSubmit']))
{
$txtName=$_POST['txtName'];
$txtFrom=$_POST['txtFrom'];
$txtTo=$_POST['txtTo'];
$txtReason=$_POST['txtReason'];
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('$txtName','$txtFrom','$txtTo','$txtReason')";
$AddMCResult = mysql_query($AddMCQ,$link);
if($AddMCResult)
{
echo "<script language=\"JavaScript\">\n";
echo "alert('Record Added.');\n";
echo "window.location='mcreport.php'";
echo "</script>";
}
}
?>
Your "Problem" is the result in $AddMCResult
After your have use header('Location: mcreport.php');
Your Script redirect to the given url and the result in $AddMCResult is not given any more
So a quick and dirty solution could be
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
$_SESSION['AddMCResult'] = $AddMCResult;
header('Location: mcreport.php');
}
AND on mcreport.php
if(isset($_SESSION['AddMCResult']) && $AddMCResult)
echo "<script>alert('Record Added.');</script>";
...
But check, that session_start() was called on both files ...
Check Carefully Table Name and Passing Parameters - Through one to another page - see get and post method-
<?php
include 'config.php';
$submit="submit";
$page = $_SERVER['PHP_SELF'];
$sl_no=$_POST['sl-no'];
$f_name=$_POST['f_name'];
$l_name=$_POST['l_name'];
if($submit)
{
$sql = "INSERT INTO table_name(sl_no,f_name,l_name) values('$sl_no','$f_name','$l_name')";
$result = mysql_query($sql);
echo "Thank you! Information entered.\n";
}
else
{
echo "There Is Something Going Wrong While Insertion";
header('Location: error.php');
}
After your header put die() like
header('Location: mcreport.php');
die();
And better you use Absolute urls.Also you can use exit() instead of die().

How to condition a user to fill the form than to oppen an specific site up

i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)

PHP, refresh page on insert

this is the updating function:
public function update($id) {
$id = $_GET['id'];
$stmt9 = $this->conn->prepare("UPDATE users SET `name`= :name, `email`= :email WHERE `id` = :id");
$stmt9->bindParam(':name', $this->name);
$stmt9->bindParam(':email', $this->email);
$stmt9->bindParam(':id' , $id, PDO::PARAM_INT);
$stmt9->execute();
if ($stmt9) {
$message = "User updated Sussesfully!";
header('location:');
}else {
header("location:");
}
}
}
Now on update here i want the page to be refresh so i could see the updated data, but here now if it update it's will keep user in edite page, and will show the data of privous entered if i see in database the data has been updated and if i refresh the page with f5 it will show the on edit page is been update with out that when i submit the form it will get update but on the form it will show the prevouse data,
so how i can make the page to get refresh after submitting. on redirection if if redirect to list page it will show that it's been updated, but here i want on mean time stay on edit page and reaload page so i could see the updated data.
regards
Simple:
header('Refresh: 0'); // 0 = seconds
Even you can specify new location
header("Refresh:2; url=new_page.php");
But when working with header function there should not be anything echoed before calling it,
but if you have already echoed anything, then you can use html or javascript:
HTML
<meta http-equiv="refresh" content="0">
<!--here you can also specify new url location-->
<meta http-equiv="refresh" content="0; url=http://url.com/">
JS
window.location.reload();
Update: because you can't use header do this:
if ($stmt9)
{
$message = "User updated Sussesfully!";
echo '<meta http-equiv="refresh" content="0">';
}
else
{
echo '<meta http-equiv="refresh" content="0">';
}
you should redirect to update url rather than reload
eg.
header("location:updateurl?id=1");
You can do it by using jquery.
location.reload();
If you wish to redirect to the exactly same page, you can use variable $_SERVER['REQUEST_URI'].
header('location:' . $_SERVER['REQUEST_URI'] );
This code is familiar with re-write rules if any.
Warning: Cannot modify header information - headers already sent by (ou
You need to switch on output buffering in PHP. If this option is enabled, then you need check if your code doesn't flush output buffer somewhere earlier.
Its simple, change this code:
if ($stmt9) {
$message = "User updated Sussesfully!";
header('location:');
}else {
header("location:");
}
like this
if ($stmt9) {
$message = "User updated Sussesfully!";
header('location: ?message='.$message);
}else {
header("location: ?message=error");
}

Categories