Pain Posted November 17, 2012 Share Posted November 17, 2012 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? Quote Link to comment https://forums.phpfreaks.com/topic/270838-redirecting-in-oop/ Share on other sites More sharing options...
Christian F. Posted November 17, 2012 Share Posted November 17, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/270838-redirecting-in-oop/#findComment-1393259 Share on other sites More sharing options...
ignace Posted November 17, 2012 Share Posted November 17, 2012 (edited) 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 November 17, 2012 by ignace Quote Link to comment https://forums.phpfreaks.com/topic/270838-redirecting-in-oop/#findComment-1393260 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.