PHP, refresh page on insert - php

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");
}

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

Redirecting to same page along with Success Message with Php [duplicate]

This question already has answers here:
Redirect to another page with a message
(6 answers)
Closed 8 months ago.
What's the best way to display a success message after redirecting to same page? I've been thinking about doing that with javascript but maybe there's a way to do this with Php? The user submit from profile.php and gets redirected to same page. I'd like to grab a variable... Can I concatenate after $_SERVER['HTTP_REFERER']? Whats the best approach?
here a snippet of code: query.php
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$stmt->close();
$db->close();
}
You could skip the session, and pass a url query parameter as a code or the message.
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?message=success1');
exit;
}
$stmt->close();
$db->close();
}
Then have code that checks for $_GET['message] ...etc
You can use sessions. Just start session, save message in global array $_SESSION, then in profile.php check if $_SESSION with your key is set and it isn't empty show it. After it you can unset your key in $_SESSION.
query.php
<?php
session_start();
//your code
if($stmt) {
$_SESSION['myMessage'] = 'Some message';
//your code
}
//rest of your code
profile.php
<?php
session_start();
//your code
if(isset($_SESSION['myMessage']) && $_SESSION['myMessage'] !== '') {
//display message or do with it what you want
}
//rest of code
If you're processing your form in the same page, then you don't have to do any redirection. The solution to achieve the desired result would be like this:
Put your form processing code at the very top of your PHP script i.e. profile.php page.
Use a boolean variable to hold the status of ->execute() statement, and use that same variable at later point of your code.
So the code would be like this:
// Declare a boolean variable at the beginning
$status = false;
// your code
$status = $stmt->execute();
$stmt->close();
$db->close();
}
if($status){
// Data submitted succesfully
}else{
// Data couldn't get submitted
}
If you want to process the form at the same file, you don't need to redirect again to the same page.
As mention by the other answer, you process the form at the top of the page.
To display a message after success or failure, you store the message in a variable. Later with the from you echo the message variable if it is set.
// Check if form was submitted
if(isset($_POST['submit'])) { // I name the submit button "submit"
// process the form
if ($stmt->execute()) {
$message = "<div> Success </div>";
} else {
$message = "<div> Failed </div>";
}
}
// Display The form and the message if not empty
if (! empty($message)) {
echo $message;
}
// Form

Check redirect source

I have a form to edit an entry, after the user presses the submit button it executes the includes/edit.php?id=XXX script and then redirects using the header('Location: ../index.php'); to the index page where all the entries are being displayed.
On the index page, I want to create a condition:
if the index page is accessed via a redirect from the edit.php?id=XXX page, then show a success message to notify the user that the edit was succesfull.
How should this condition look like?
<?php
require_once('includes/session.php');
require_once('includes/config.php');
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
}
$query = ("SELECT * FROM archive ORDER by id DESC");
$result = mysqli_query($link, $query) or die (mysqli_error());
/*if (condition){
//show success message
}*/
?>
You should take a look at this var :
$_SERVER['HTTP_REFERER'];
As it will return the page from where you come before this one:
So you could just do :
if($_SERVER['HTTP_REFERER'] == "edit.php?id=XXX"){
// your code here
}
you can simply try this :
if(isset($_GET['id']) && !empty($_GET['id']))
{
// your success message
}
If you set a $_SESSION variable with messages you can then display all messages and clear the list afterwards.
Adding a message:
if ( ! isset($_SESSION['messages']) ) {
# initialize messages
$_SESSION['messages'] = [];
}
# Add a new message:
$_SESSION['messages'][] = 'Something was a success!';
Reading messages:
# If there are messages not displayed
if ( isset($_SESSION['messages']) && is_array($_SESSION['messages']) ) {
foreach ( $_SESSION['messages'] as $message ) {
echo $message . '<br>';
}
# Clear messages
unset( $_SESSION['messages'] );
}
The suggested 'HTTP_REFERER' can be manipulated and browsers are not required to send it.
I would suggest to redirect immediately and not execute more code after the location header is set:
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
exit();
}
If $_SESSION['login'] is not set: redirect and exit.
You might consider the rest of the code as one big "else" (= if $_SESSION['login'] is set).
To answer the question from comments: without the exit, the code below will be executed .. and doing that query is not really necessary. Thats why its better to end the program flow by adding an exit. Referencing: Why I have to call 'exit' after redirection through header('Location..') in PHP?
And for the condition you could use $_SERVER['HTTP_REFERER'] or $_GET['id'] to check the page you are coming from. Just compare the strings or parts of them.

why php headers are getting huge time to redirect?

Im developping a very simple script with php and mysql. the problem is php header redirect getting huge time to redirect. without redirect script working very fast. Im using php header redirect for remove cashed form data and redirect process.php to root index..
here is my index.php code...
<?php ob_start(); ?>
<html>
<head>
<title>myWall ~ V.02</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<?php
// import connect.php file.
require 'connect.php';
require 'form.php';
// checking form set || not && form empty || not.
if (isset($_POST['status'])){
if (!empty($_POST['status'])){
$status = nl2br(htmlentities($_POST['status']));
// sql query string for insert a status to database.
$insertAStatus = "INSERT INTO `database`.`table` (`id`, `status`) VALUES (NULL, '".$status."');";
mysqli_query($con,$insertAStatus);
//echo 'added a status';
// redirecting to main root for clear form submitted data.
header('location: ../mywall');
} else {
echo 'Please enter a status.<br>';
}
} // end. if isset.
// getting number of rows in db.
$getNumRows = "SELECT * FROM `status`;";
$gotNumRows = mysqli_query($con,$getNumRows);
$numOfRows = mysqli_num_rows($gotNumRows);
if ($numOfRows != 0){
echo 'You have '.$numOfRows.' Status.';
} else {
return NULL;
}
// display data in database.
$getData = "SELECT * FROM `status` ORDER BY `status`.`id` DESC";
$dataFromDb = mysqli_query($con,$getData);
// display data through while loop.
while ($row = mysqli_fetch_array($dataFromDb,MYSQLI_ASSOC)){
echo "<div style='padding: 5px; background:#F1F1F1; margin: 5px;'>".$row['status']."<a style='float:right' href='process.php?delete=".$row['id']."'>[delete]</a><a style='float:right' href='#'>[edit]</a><div style='clear:both'></div></div>";
}
?>
</body>
</html>
<?php ob_end_flush(); ?>
here is my online demo of above script
http://dzine.us/dev/mywall/
Note that the code after the header() function is still executed.
This means that even when you want to redirect, the queries are still executed.
Try putting a die(); or exit(); line after your header('location: ...');
This will stop the rest of code to execute when you want to redirect.
The header() function changes the header location but doesn't redirect you till the rest of the code is executed. You can do this to make it redirect immediately:
header("Location: ...");
exit(0); //This should come just after header statement.
This will redirest to the other webpage as soon as you want, because the rest of the code will not be executed.

Refresh button on Browser

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.

Categories