简体   繁体   中英

Cannot open file using 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

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.

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

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

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.

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