Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2008-11-17
17
Medium Priority
?
444 Views
Last Modified: 2013-12-13
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?
0
Comment
Question by:Donnie Walker
  • 4
  • 4
  • 3
  • +3
17 Comments
 

Expert Comment

by:tben2008
ID: 22975727
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
 

Author Comment

by:Donnie Walker
ID: 22975790
I already mentioned header('Location in my original question. I can't use it.

Is there another way in PHP to do this?
0
 
LVL 3

Expert Comment

by:abn38
ID: 22975791

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:tben2008
ID: 22975849
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
 

Author Comment

by:Donnie Walker
ID: 22975885
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
 

Expert Comment

by:tben2008
ID: 22975919
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
 
LVL 3

Expert Comment

by:abn38
ID: 22975958
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 22976333
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
 

Author Comment

by:Donnie Walker
ID: 22976386
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 22976548
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 22976614
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
 
LVL 10

Expert Comment

by:Tyler Laczko
ID: 22977224
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
 
LVL 10

Expert Comment

by:Tyler Laczko
ID: 22977239
header can be used you just need to make sure that you have your php code before your html.
0
 
LVL 10

Expert Comment

by:Tyler Laczko
ID: 22977259
<?php

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

?>

//HTML STARTS
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1000 total points
ID: 22977291
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
 
LVL 11

Assisted Solution

by:NoiS
NoiS earned 1000 total points
ID: 22979031
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
 

Author Closing Comment

by:Donnie Walker
ID: 31517432
thanks. both suggestions helped!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question