0

PHP Version: 5.4.16

I'm running an Apache Server on a Centos Linux machine and my PHP code to change directory doesn't work. My ultimate goal was to try and read a file that was in a different directory but it wouldn't read the file. My first attempt was

$filename=("/home/tom/notes/test_notes.txt");
$file = fopen( $filename, "r" );

This didn't work, so I fixed it up with the answer from this question: Reading a file in a different directory php

$filename=(__DIR__."/home/tom/notes/test_notes.txt");
$file = fopen( $filename, "r" );

But that wouldn't read the file either, I then checked to see if it could read a text file in the same directory and that worked so I decided that changing the directory to where the text file was located could work.

I went around doing that with this code, but it doesn't change directory:

echo getcwd();
chdir("/home/tom/notes");
echo getcwd();

It returns:

/var/www/html
/var/www/html

(Without the newline..)

The directory is valid as cd /home/tom/notes in the shell, works

Any idea what is not allowing it to change directory? Or are there any other better ways to read a file that is located in another directory?

(I used this code to see whether or not opening the file worked or not)

if( $file == false )
{
echo "ERROR: Unable to open file";
}
Community
  • 1
  • 1
Tom
  • 71
  • 1
  • 2
  • 11
  • Do you have any error or warning ? – TIGER Dec 21 '16 at 06:30
  • No, everything works fine.. although I'm not sure if I have showing errors enabled – Tom Dec 21 '16 at 06:33
  • when chdir() getting failed it must return warning. Do `var_dump` for your chdir code. – TIGER Dec 21 '16 at 06:34
  • Oh wow, I just enabled error reporting and I get the "Warning: chdir(): Permission denied (errno 13) in /var/www/html/note_interaction.php on line 39" warning – Tom Dec 21 '16 at 06:36
  • 1
    @Tom than i hope it is clear, your apache user must have access to the folder. But more likely, all required files should be in a folder accesible by apache. Anyway, if you are not able to fix the permissions yourself, please update your post to fit the new question. (P.S. read this post http://serverfault.com/questions/357108/what-permissions-should-my-website-files-folders-have-on-a-linux-webserver) – Doktor OSwaldo Dec 21 '16 at 06:41

1 Answers1

1

I am not sure what is wrong with your chdir() code there must be some warning if its getting fail see the documetation here try to debug your code for the same as below and enable error reporting.

echo getcwd();
$response = chdir("/home/tom/notes");
var_dump($response);
echo getcwd();

To read the file see the example below. More Details

<?php
$myfile = fopen("/path/of/your/file", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Community
  • 1
  • 1
TIGER
  • 2,864
  • 5
  • 35
  • 45