Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a user to another url without a header redirect?

Tags:

redirect

php

I'm learning PHP and been looking for this for a while. What I want to achieve is something like so:

if (true/false) {
    go to this url;
}

Every time I search terms like php redirects or php links etc., 99% of the time I get something "headers". I read that header redirects can achieve this but no code can go before it, that it must be first on the page else it wont work.

If that's so, then how can I achieve this?

like image 470
somdow Avatar asked Oct 12 '11 20:10

somdow


1 Answers

i read that header redirects can achieve this but no code can go before it. that it must be first on the page else it wont work.

That's wrong. There must be no output before this. Thus you have to ensure, that you don't echo, print, ?>something<?php (or whatever) anything before.

if (true)  {
  header('Location: ' . $url, false, 302);
  exit; // Ensures, that there is no code _after_ the redirect executed
}

You can ready everything about it in the official manual. Especially:

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. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

like image 199
KingCrunch Avatar answered Nov 14 '22 21:11

KingCrunch