switch case被调用两次

时间:2012-03-11 11:33:04

标签: php switch-statement fread

我的php脚本应该只是取一个文件名,并在特定目录下输出文件名的内容。问题是它确实这样做但是它显然再一次调用导致抛出错误的情况,我试图用if / else替换switch但仍然回忆起自己(与case相关的代码:“1”)。这是错误:

    Warning: fopen(C:/xampp/htdocs/phptut/practice/) [function.fopen]: failed to open stream: No such file or directory in C:\xampp\htdocs\phptut\practice\fileuploadread.php on line 8

    Warning: fread() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\phptut\practice\fileuploadread.php on line 9

    Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\phptut\practice\fileuploadread.php on line 10

这是代码:         

    switch($_GET['id']){
        case"1":

            {   //here $file gets the pathtothefile + filename
                $file="C:/xampp/htdocs/phptut/practice/" . $_POST["element"];
                $fh=fopen($file,"r");
                $contents=fread($fh,filesize($file));
                fclose($fh);
                   //It does output the $contents at this point
                echo $contents;

            }
            break;
        default:{

            echo"
                <html>
                        <head>
                            <style type='text/css'>
                                fieldset{
                                    background-color:lightblue;
                                    border-color:blue;
                                    width:50%;
                                    margin-left:auto;
                                    margin-right:auto;
                                    margin-top:200px;

                                }
                                legend{
                                    color:blue;

                                }
                            </style>
                        </head>
                        <body>
                            <fieldset>
                                <legend> Upload Your CV </legend>
                                <form method='POST' name='form' action='fileuploadread.php?id=1'>
                                    <input type='input' name='element' size='20' /><br/>
                                    <input type='submit' value='submit...'/>
                                </form>
                            </fieldset> 
                        </body>
                    </html>
                    ";
    }       }
    ?>

2 个答案:

答案 0 :(得分:2)

我不确定这里有什么真正的问题,但你应该在fread()和fclose()调用中使用它之前检查文件指针是否正常

$fh=fopen($file,"r");
if ($fh) {
   $contents=fread($fh,filesize($file));
   fclose($fh);
}

如果文件不存在,请先检查并处理。

if (file_exists($file)) {
   // do something with file
} else {
   // do something else
}

答案 1 :(得分:0)

有两件事突出:

  1. $file中您使用正斜杠对路径进行硬编码,但您的Windows系统使用反斜杠 - 您最好查询系统的本机文件路径;

  2. switch通常用于多个选项 - 您只有一个和默认选项?您可以在函数中尝试使用简单的if - else,然后查看是否仍然发生重复。

  3. ......正如亚当所说,添加一些错误检查。

相关问题