php | files

PHP file and directory commands.

Reference:

  w3schools   manual   manual_list


Reading a file completely:

$page = file_get_contents('template.txt');

Replace a string:

$page = str_replace('old_string','new_string',$page);

Print the results:

print $page;


Writing a file completely:

file_put_contents('newfile');


Turning lines of a file into an array:

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

Reading lines and using trim() to remove trailing newline:
foreach (file('file.txt') as $line){
  $line = trim($line);
  print $line;
}

Putting list of files in a directory into an array:

$list = scandir('directory')

Easy way to get rid of the hidden files/folders:
$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));
Listing non-hidden sub-directories:
foreach (scandir('directory') as $d){
  if ($d[0]!=='.' && is_dir($d)){echo $d;}
}
Listing non-hidden regular files:
(Note that is_file() returns false if the parent directory doesn't have +x set for you; this make sense, but other functions such as readdir() don't seem to have this limitation.)
foreach (scandir('.') as $f){
  if ($f[0]!=='.' && is_file($f)){echo $f;}
}

Array of all files in a directory:

$filelist = glob("/path/directory");

Array of .txt files in a directory:

$filelist = glob("/path/directory/*.txt");

Array of files and directories that begin with "te":

$filelist = glob("/path/directory/te*");

Array of image files:

$filelist = glob("/path/directory/*.{jpg,gif,png}");

$filelist = glob("/path/directory/{*.jpg,*.gif,*.png}");

$fileslist = glob("/path/directory/*.{jpg,gif,png}", GLOB_BRACE);


Get file name without path:

$file = basename("/path/sudoers.txt");

Get file name without path and remove .txt extension:

$file = basename("/path/sudoers.txt",".txt");

fetching only the filename (without extension and path)
$file = 'image.jpg';
$info = pathinfo($file);
$file_name =  basename($file,'.'.$info['extension']);
echo $file_name;

Using pathinfo() to get an array of file parts:
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'];
echo $path_parts['basename'];
echo $path_parts['extension'];
echo $path_parts['filename'];
Using pathinfo() to get a specific part:

echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html

echo pathinfo('/www/htdocs/index.html', PATHINFO_DIRNAME); // outputs /www/htdocs

echo pathinfo('/www/htdocs/index.html', PATHINFO_BASENAME); // index.html

echo pathinfo('/www/htdocs/index.html', PATHINFO_FILENAME); // outputs index


Returning a parent directory's path:

echo dirname("/etc/passwd"); \\ returns /etc

echo dirname("/etc/"); \\ returns /

echo dirname("."); \\ returns .

echo dirname("/usr/local/lib", 2); \\ returns /usr

The command dirname($path [,levels]) will return the parent directory's path that is levels up from the current directory.

To get the directory of current included file:

echo dirname(__FILE__);