unknownSPY
unknownSPY

Reputation: 738

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

Upvotes: 2

Views: 8817

Answers (4)

Brotheryura
Brotheryura

Reputation: 1188

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

Upvotes: 1

andy
andy

Reputation: 2002

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.

Upvotes: 3

Ahmad
Ahmad

Reputation: 9658

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.

Upvotes: 0

Ruan Mendes
Ruan Mendes

Reputation: 92274

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

Upvotes: 0

Related Questions