Cannot open file using fopen (php)

我的未来我决定 提交于 2021-02-05 06:47:06

问题


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


回答1:


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.




回答2:


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.




回答3:


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.";   
}



回答4:


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



来源:https://stackoverflow.com/questions/26803436/cannot-open-file-using-fopen-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!