简体   繁体   中英

PHP, Changing directory not working

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

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);
?>

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