简体   繁体   中英

Change php header using switch case

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 form 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.

Eg:

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM