Jump to content

Redirecting In Oop


Pain

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;
  }
}

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.