Trung Bún
Trung Bún

Reputation: 1147

Reading a text file in localhost (WAMP server) using PHP

My problem is very simple, I think I have misused the slashes somewhere in the path.

I want to read a local file, the path to the file is stored in database which is managed by phpMyAdmin. The code that I use to read the file is below:

<?php
    $f = fopen($row['Article'], "r");
    while(!feof($f)){
       echo fgets($f) . "<br/>";
    }
    fclose($f);
?>    

Originally the path I stored in the database is: C:\wamp\www\project\database\article\article1.txt

And it works just fine. Problem here is that, I'm using WAMP server, this means that I don't have to store an absolute path to the file, so I would store the path into my DB like this:

\project\database\article\article1.txt

But it doesn't work at all! The error it displays is "fopen failed to open stream".

This error means that the php code can't read the path I store in DB. So I tried several ways, such as:

\localhost\project\database\article\article1.txt
/project/database/article/article1.txt
/localhost/project/database/article/article1.txt

But none of them work. Same error displayed!

Can someone give me some tips to make it work? Thank you!!

Upvotes: 0

Views: 2535

Answers (3)

georoot
georoot

Reputation: 3617

the file open streams opens file relative to Current Working Directory so store the file location relative to the PHP file that is being executed. In any other case you can always change it by prending the path to you / file. For example if i have my file in /var and my script runs on /var/www/index.php i can simply in that case prepend "../" to read file from /var

Upvotes: 0

doubleui
doubleui

Reputation: 556

Where your php file is? You can append

echo dir(__FILE__)

into your php block. I think the problem in wrong initial path (cwd).

Upvotes: 1

Ayush Ghosh
Ayush Ghosh

Reputation: 487

The way to solve this problem is to look in logs where it is trying to read from

"fopen failed to open stream" file-name

read the file-name and change your code to get to the file you want to.

Hope it helps!

Happy Coding !!!

Upvotes: 0

Related Questions