0

I'm customizing a module in Drupal and in that module I'd like to refresh the current page right after an if statement, how can I refresh the current page in PHP

Gus
  • 107
  • 1
  • 1
  • 6
  • This has been answered [here](https://stackoverflow.com/a/8131377/1292092). Ensure that you protect yourself against an infinite redirect loop. – curtis1000 Sep 06 '15 at 04:53

4 Answers4

6

You can't in PHP if you've already outputted something (since all headers must be sent before output begins).

If you haven't outputted:

header('Location:: current_page_url');
or
header("Refresh:0");

Better way is to do it through Javascript with the window object

$window.location.reload();
q.Then
  • 2,743
  • 1
  • 21
  • 31
  • How can I add that js in my php code? should I make a js file and add my js to it? – Gus Sep 06 '15 at 04:54
  • You would need to it via ` – q.Then Sep 06 '15 at 05:26
3

Php offers the following function to invoke a page refresh

header("Refresh:0");

If you require a page redirect you can use the following.

header("Refresh:0; url=redirect_page.php");
WeeniehuahuaXD
  • 852
  • 3
  • 10
  • 30
  • 1
    Refresh is not a valid HTTP header even though it is implemented in most browsers. There is a standard way also which should be used, which is the Location header. – Sami Kuhmonen Sep 06 '15 at 05:05
2

just header("Refresh:0");

Drop Shadow
  • 845
  • 3
  • 12
  • 28
0

I'm surprised nobody mentioned the "Drupal Way":

drupal_goto(current_path()); 

This exact scenario is tested in modules/simpletest/tests/common_test.module function common_test_init():

/**
 * Implements hook_init().
 */
function common_test_init() {
  if (variable_get('common_test_redirect_current_path', FALSE)) {
    drupal_goto(current_path());
  }
  if (variable_get('common_test_link_to_current_path', FALSE)) {
    drupal_set_message(l('link which should point to the current path', current_path()));
  }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
jeff-h
  • 2,184
  • 1
  • 22
  • 33
  • this would fail with query parameters. `example.com/q?a=b` will redirect to `example.com/q` – Semra Dec 16 '22 at 22:13