dqsp60748
2014-11-07 14:27
浏览 287
已采纳

无法使用fopen(php)打开文件

I am trying to open a file for reading in php script but having trouble.

This is my code

$fileHandle = fopen("1234_main.csv", "r")or die("Unable to open");
if (!file_exists($fileHandle))
{
    echo "Cannot find file.";
}

The script is in the same directory as the file I am trying to read and there are no other read/write permission errors as I can create/read other files in the same directory.

When I run the script I just get the "Cannot find file" error message. Why is this error message being shown? Surely if fopen() can't open the file the "or die statement" should end the script?

Also, why can't I open the file when it definitely exists and is in the same location as the script (I have also tried using the full path of the filename instead of just the filename).

I am fairly new to php (but have exp in c++) so if its a stupid question I apologize.

Many thanks

图片转代码服务由CSDN问答提供 功能建议

我正在尝试打开一个文件,以便在php脚本中阅读但是遇到了麻烦。

这是我的代码

  $ fileHandle = fopen(“1234_main.csv”,“r”)或死亡(“无法打开”); 
if(!  file_exists($ fileHandle))
 {
 echo“无法找到文件。”; 
} 
   
 
 

脚本与文件I位于同一目录中 我正在尝试阅读并且没有其他读/写权限错误,因为我可以创建/读取同一目录中的其他文件。

当我运行脚本时,我只是得到“找不到 文件“错误消息。 为什么会显示此错误消息? 当然,如果fopen()无法打开文件,“或者死亡语句”应该结束脚本吗?

另外,为什么我不能打开文件,当它肯定存在并且在 与脚本相同的位置(我也尝试使用文件名的完整路径而不仅仅是文件名)。

我对php很新(但是在c ++中有exp)所以 如果这是一个愚蠢的问题我道歉。

非常感谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • duanjiao4763 2014-11-07 14:35
    已采纳

    file_exists() take the file-name as input, but the logic of your code has problem. You first try to open a file then you check its existence?

    You first should check its existence by file_exists("1234_main.csv") and if it exists try to open it.

    点赞 评论
  • dro60731 2014-11-07 14:30

    In PHP, file_exists() expects a file name rather than a handle. Try this:

    $fileName = "1234_main.csv";
    if (!file_exists($fileName))
    {
        echo "Cannot find file.";
    } else {
        $fileHandle = fopen($fileName, "r")or die("Unable to open");
    }
    

    Also keep in mind that filenames have to be specified relative to the originally requested php-script when executing scripts on a web server.

    点赞 评论
  • douzhang3822 2014-11-07 14:31

    file_exists takes a string, not a file handle. See http://php.net/manual/en/function.file-exists.php

    点赞 评论
  • dongzhong8691 2014-11-07 14:45

    You can use file_get_content() for this operation. On failure, file_get_contents() will return FALSE.For example

    $file = file_get_contents('1234_main.csv');
    
    if( $file === false ){
        echo "Cannot find file.";   
    }
    
    点赞 评论

相关推荐 更多相似问题