开发者

Change php header using switch case

开发者 https://www.devze.com 2023-04-05 17:20 出处:网络
I want to redirect to other page based on the selected string in combo box. I have added following code:

I want to redirect to other page based on the selected string in combo box.

I have added following code:

switch ($downloadType){
    case "text1":
        header("Location:pdf/text1.pdf");
        break;
    case "text2":
        header("Location:pdf/text2.pdf");
    case "text3":
        header("Location:pdf/text3.pdf");
    default:
        header("Location:index.html");
}

But this simple script is not working. I am new to php. Do you have any idea why I am not able to change header. Is it like we cannot change header using switch-case statements.

If this is not the way then what could be the possible way to redirect to another page on for开发者_如何学Pythonm submission.


You need to add a break; to the end of each case.

case "text3": 
    header("Location:pdf/text3.pdf"); 
    break;


You need to add break:

switch ($downloadType){
case "text1":
    header("Location:pdf/text1.pdf");
    break;
case "text2":
    header("Location:pdf/text2.pdf");
    break;
case "text3":
    header("Location:pdf/text3.pdf");
    break;
default:
    header("Location:index.html");
}


You must see switch statements as a sort of jump to construct. Depending on the value of the evaluated expression, code execution jumps to the first appropriate case or default statement and continues from there. That's why you'll want to insert a break statement most of the times. Currently, you only do it for the "text1" case.

Apart from that, I suggest you use full URLs when composing Location HTTP headers, even though relative URLs normally work as expected. The HTTP specification doesn't really allow relative URLs.

header('Location: http://example.com/foo/pdf/text2.pdf');

And don't forget that sending an HTTP header does not stop the script execution. Add an exit; statement when you're done.


Apart from completing your case statements with break, also remember that you must call header() before any actual output is sent.

E.g:

<html>
<?php
header("Location:pdf/text2.pdf");?>
</html>

Will not work, since the "<html>" line will already have been sent to the client, precluding the use of header(). Basically, make sure no output is going on in the file before you try to call header().

Edit: Ref: http://php.net/manual/en/function.header.php

0

精彩评论

暂无评论...
验证码 换一张
取 消