无法使用PHP CLI读取文件

$file=file('DATA.txt');

I keep getting "failed to open stream. No such file or directory in ...". This works when I run it on a server and browser. But the error occurs when I run the script using command line.

First of all take a deep breath and a tea ;)

The news is: DATA.txt is only a file-name.

A file normally is placed in a directory. As stupid as this sounds, well, as stupid this is: What is the directory?

The answer: the current working directory. This differs between servers and CLI.

So better add your directory as well:

$name = 'DATA.txt';
$dir = 'C:/';
$path = $dir.$name;
$file = file($path);

Hope this is helpful.

The question definitely lacks some clarifications, but two guesses:

  1. Since you haven't provided a path, the file is expected to be located in the current dir, but server most likely runs as a different user (web, for example), and expects this file to be located in this user home dir (or current dir, to be precise).
  2. Permissions, as usual.

I found that this works: $fname=str_replace(basename(__FILE__),'',__FILE__).'DATA3.txt'; I couldn't simply use "dirname" because I wanted this to work in both Windows and Linux (\ or /).