0

I have a login class, whereby a user logs into the database then I want the method to redirect the user to their own profile page. I was hoping to use header() redirect although I've been having a few issues implementing it.

Because I want to call the header() after the HTMl has been started it won't re-direct, is there any neat way to wrap it into a function and call it when I need it?

3 Answers 3

3

Two ways:

  1. Reorganize your script to perform logic first (including the header() redirect) and output HTML second.

    -or-

  2. Buffer your HTML output and send the buffer contents only after your logic determines that the redirect is not needed.

The first method is preferable. Logic should be separated from layout wherever possible. You may consider implementing the MVC (Model, View, Controller) pattern to improve the maintainability of your code.

Sign up to request clarification or add additional context in comments.

1 Comment

Both good suggestions. I'd go with re-organizing your code. It's not good for maintainability to have your main PHP logic and HTML mixed in together. Goes back to the paradigm of separating program logic and input/output functionality.
1

You should do all of your logic before you output any HTML. Don't check whether or not you need to redirect in the middle of your page.

Otherwise, you could enable output buffering, but I wouldn't rely on it.

Comments

0

if you want to include header() redirect method then the code must come before any html tag, however you can make a function to behave like header() for example

function redirect($link, $time) {
  return "<meta http-equiv='refresh' content='$time;url=$link'>";
}

then call the function like

echo redirect("http://google.com", "3");

which will redirect to google.com in 3 seconds.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.