How can I do a redirect with PHP inside the same page?

I have a form that I process on the same page. The user submits the form and using the $_GET grab a value in the querystring and then I process the form (insert, update, whatever).

When I am done doing this I want to redirect back to the same page to load the results of my form changes.

In ASP I would do response.redirect "mypage.asp". I've read in PHP that this is done with location: header...but when I try that it tells me the header is already written.

Is there a way (without using javascript) to make PHP 5 redirect or refresh the page?
Donnie WalkerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tben2008Commented:
Too redirect with php you can use this code:

header ('Location: http://youwebsite.com/whatever.php');

But you cannot have any html before it.
0
Donnie WalkerAuthor Commented:
I already mentioned header('Location in my original question. I can't use it.

Is there another way in PHP to do this?
0
abn38Commented:

Here's How:
<?php
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
?>
Change the code on the redirect page to be simply this. You need to replace the URL above with the URL you wish to direct to.
 
Be sure that you do not have any text sent to the browser before this, or it will not work. Your safest bet is to simply remove all content from the page but the redirect code. 
 
<html>
<?php
//this will NOT work, the browser received the HTML tag before the script
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
?>

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

tben2008Commented:
try putting an exit; after the header. Also what about:

<HTML>
<HEAD>
<?php if (whatever) {
echo '<META HTTP-EQUIV="refresh" CONTENT="seconds;URL=the-other-url">';
}?>
</HEAD>
<BODY>

</BODY>
</HTML>
0
Donnie WalkerAuthor Commented:
I don't think I've explained this properly.

I am doing everything inside one script. The form, the form process, etc are all inside one page.

When the form process gets done with it's work I want to refresh the same page and then display the results of the work on the same page.

I do not need a meta redirect or header(location solution....since neither will work in this case.

Is there a way to redirect/refresh in PHP inside the same script?




0
tben2008Commented:
600 is seconds. Is this what you want
<HTML>
<HEAD>
<?php if (whatever) {
echo '<meta http-equiv="refresh" content="600">';
}?>
</HEAD>
<BODY>
 
</BODY>
</HTML> 

Open in new window

0
abn38Commented:
Try a header refresh?
 

This will send the visitor to the forums (assuming you have the forums running under the folder "forums" as ours) after 6 seconds. 
<?php header("Refresh: 6; url=/forums/"); ?>
 
This will send the visitor to www.php.net after 10 seconds. 
<?php header("Refresh: 10; url=http://www.php.net"); ?>
Remember that using the PHP header function you always have to put it at the very beginning of your page, just after the <html> tag. Any other header sent before our header function will make it cause an error. 

Open in new window

0
Ray PaseurCommented:
You can do this with control logic - I will post an example in a moment.

You MUST NOT update a data base or otherwise change the state of a machine on the basis of information in the GET string of the URL.  It violates a lot of rules about how the www works, plus there is the practical matter that a search engine could pre-fetch a web page with a GET argument and... Boom!
0
Donnie WalkerAuthor Commented:
Ray,
 This is on an intranet behind security login and I am only using $_POST values to update the database.
 $_GET just lets me know what to do (delete, add, edit, etc).
 Even if someone where to use the querystring they would also have to send some $_POST data and have the cookie set for the security login.

I'm new to PHP but I think that would be enough.
0
Ray PaseurCommented:
Here is the if-else control structure.  HTH, ~Ray
<?php // RAY_not_redirect.php
 
// PAGE HEADER
echo "<html>\n";
 
// IF THERE IS DATA IN THE FORM PROCESS IT HERE
if (!empty($_POST)) {
	echo "The data field contains {$_POST["data"]} \n";
 
// IF THERE IS NO DATA IN THE FORM YET
} else {
	echo "The data field is EMPTY \n";
}
 
// FINISHED PROCESSING - SWITCH TO HTML AND PUT UP THE FORM
?>
 
<form method="post">
Enter something here:
<input name="data" value="<?=$_POST["data"]?>" />
<input type="submit" />
</form>
</html>

Open in new window

0
Ray PaseurCommented:
Even behind an intranet, there is some risk if you change the data model based on a query string.  A human typographical error could potentially trigger some kind of update.  You can't prevent all human errors, but here is the sort of thing I would say is safe.

A link that says "update" might look like this:
<a href=formpage.php?action=update&key=123>Update 123</a>

Then the formpage script would verify permission to update and present a form for client input, based on the data model for key=123.

Best, ~Ray
0
Tyler LaczkoCommented:
You do not want to use a refresh or it will attempt to insert the data over and over.

you need to know the exact page you want to go back to including your variables to get there.

EG
index.php //says hi

index.php
$_POST['page'] = "displayInfo"
//displays your data

index.php
$_POST['page'] = "add", $_POST['id'] = 1, etc
//adds data


after you are on "add data" you need to excecute your code then unset your variables using unset($_POST['page'])

then set your variables for the "display data page"



$_POST['page'] = "displayInfo";
header("Location: index.php");

this will then take you to the index page displaying your info.
0
Tyler LaczkoCommented:
header can be used you just need to make sure that you have your php code before your html.
0
Tyler LaczkoCommented:
<?php

//check if adding
if()
{
  //do something
}
//check if deleting
if()
{
  //do something
}
//check if whatever
if()
{
  //do something
}

?>

//HTML STARTS
0
Ray PaseurCommented:
You can prevent multiple submissions with a hash token.  Start a session on every page and use this code.
/* ************************************************************************* */
// PREVENT MULTIPLE UPDATES DUE TO UNEXPECTED RESUBMISSIONS
// EXAMPLE: if ( multi_submit() ) { /* error */ } else { /* normal processing */ }
function multi_submit($type = "post") {
	$string = "";
	$input_array = ($type == "get") ? $_GET : $_POST;
	foreach ($input_array as $val) { $string .= $val; }
	$string = md5($string);
 
	if ($_SESSION['_multi_submit'] === $string) {
return true;
	} else {
		$_SESSION['_multi_submit'] = $string;
return false;
	}
}
/* ************************************************************************* */

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
NoiSCommented:
This is what I often use to execute database instructions from a form




 
########### Initial code here ##############
// I use $_SESSION to store some data
session_start();
########### /Initial code here ##############
 
if($_SERVER['REQUEST_METHOD']=='POST'){
   // ALL your SQL isntructions
   /**
   * If you need to send some message to browser, save on $_SESSION['to_save'] variable
   *  Example, to tell the code that your submission was a sucess
   $_SESSION['to_save']['sucess']=true;
   */
   header("Location: " . $_SERVER['PHP_SELF']); // redirecting to itself (without POST)
   exit;
}
if(isset($_SESSION['to_save'])){
   extract($_SESSION['to_save']); // restoring all variables
   unset($_SESSION['to_save']); // clear all saved variables
}
 
// After a POST and if your isntructions was sucessfully executed we will have
// a variavle $sucess with TRUE value 
if(isset($sucess) && $sucess==TRUE){
 
   // Sucess message here
}

Open in new window

0
Donnie WalkerAuthor Commented:
thanks. both suggestions helped!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.