Jump to content

Recommended Posts

Hello. I wrote this small class which should redirect user to another page.

 

<?php


class Redirect {

public function redirect($parameter) {

header("Location: " . $parameter . ")";

}

}

?>

 

Doesn't really work because of the incorrect syntax in this line:

header("Location: " . $parameter . ")";

What would be the correct syntax in this case?

Link to comment
https://forums.phpfreaks.com/topic/270838-redirecting-in-oop/
Share on other sites

I see no discernible reason for why this should be in a class of its own, it gives you no benefit what so ever. A function I'd understand, but the class syntax is quite thoroughly wasted in this instance. Also, for a function I'd add some error checking, as well as constructing the constant part of the URI. So that I only had to send the variable bit, such as page name, GET parameters etc.

Classes and functions are meant to enable you to group sections of code, so that you can do more with less code, as well as avoid having to repeat blocks of code. If you end up in a situation where you have to write more to do the same as without the class/function, then you've missed the point entirely.

 

When it comes to the syntax: There is no problem, the syntax is perfectly fine. Do you get any error messages? If so, the please post them and note which line (exactly) they point to.

 

PS: Always use die () after a header ('Location: ') redirect. Otherwise the script will continue to parse, potentially creating security breaches and/or other problems.

 

 

Link to comment
https://forums.phpfreaks.com/topic/270838-redirecting-in-oop/#findComment-1393259
Share on other sites

I see you already solved it, though I should point out that you need to put an exit after the header. I would also expand a bit to make use of the extra parameters header provides.

 

class Response {
  public function redirect($to, $code = 302) {
    header('Location: ' . $to, true, $code);
    exit; // or
    //$this->setHeader('Location', $to);
    //$this->setStatus($code);
    //$this->sendHeaders();
    //exit;
  }
}

Edited by ignace
Link to comment
https://forums.phpfreaks.com/topic/270838-redirecting-in-oop/#findComment-1393260
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.