Hailwood
Hailwood

Reputation: 92581

How to refresh the current page (aka. redirect to the same URL)?

I have a page which has to refresh itself after a POST request. Is there a way to get the exact url to the current page?

Like header('location: ???');?

Upvotes: 50

Views: 224956

Answers (7)

Syntax Error
Syntax Error

Reputation: 4527

My preferred method for reloading the same page is $_SERVER['PHP_SELF']

header('Location: '.$_SERVER['PHP_SELF']);
die;

Don't forget to die or exit after your header();


If the query string is also necessary, use

header('Location:'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
die;

When using htaccess url manipulation, the value of $_SERVER['PHP_SELF'] may take you to the wrong place. In that case the correct redirect target will be in $_SERVER['REQUEST_URI']

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

You can also explicitly assign a value to $_SERVER['PHP_SELF'] to make sure it's always correct. For example:

$_SERVER['PHP_SELF'] = http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI];

or if you have a specific path structure:

$_SERVER['PHP_SELF'] = 'https://sample.com/controller/etc';


Note about security - this answer is about reloading during php execution. Use htmlspecialchars() or another method to sanitize $_SERVER['PHP_SELF'] if you're going to output it's contents to the webpage to prevent XSS attacks.

See this article for how $_SERVER["PHP_SELF"] can be attacked.

Upvotes: 0

Steve Moretz
Steve Moretz

Reputation: 3128

How about a simple:

header("refresh: 0");

Upvotes: 1

Byron Whitlock
Byron Whitlock

Reputation: 53861

header('Location: '.$_SERVER['REQUEST_URI']);

Upvotes: 115

Fernando
Fernando

Reputation: 1124

PHP refresh current page

With PHP code:

<?php
$secondsWait = 1;
header("Refresh:$secondsWait");
echo date('Y-m-d H:i:s');
?>

Note: Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

if you send any output, you can use javascript:

<?php
echo date('Y-m-d H:i:s');
echo '<script type="text/javascript">location.reload(true);</script>';
?>

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

Or you can explicitly use "meta refresh" (with pure html):

<?php
$secondsWait = 1;
echo date('Y-m-d H:i:s');
echo '<meta http-equiv="refresh" content="'.$secondsWait.'">';
?>

Greetings and good code,

Upvotes: 23

Mahendra Jella
Mahendra Jella

Reputation: 5596

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

Upvotes: -1

Mahendra Jella
Mahendra Jella

Reputation: 5596

header('Location: '.$_SERVER['PHP_SELF']);  

will also work

Upvotes: 2

casablanca
casablanca

Reputation: 70701

$_SERVER['REQUEST_URI'] should work.

Upvotes: 7

Related Questions