Skip to content

Instantly share code, notes, and snippets.

@antoniojps
Created April 3, 2017 23:19
Show Gist options
  • Save antoniojps/b6164d1ff039128a46fca21e6149eb57 to your computer and use it in GitHub Desktop.
Save antoniojps/b6164d1ff039128a46fca21e6149eb57 to your computer and use it in GitHub Desktop.
PHP Files Functions
<?php
$path ='/dir0/dir1/myfile.php';
$file = 'file1.txt';
// Return filename
echo basename($path);
// Return filename without ext
echo basename($path, '.php');
// Return the dir name from path
echo dirname($path);
// Check if file exists
echo file_exists($file);
// Get abs path
echo realpath($file);
// Checks to see if file
echo file_exists('test');
// Check if writeable
echo is_writable($file);
// Check if readable
echo is_readable($file);
// Get file size
echo filesize($file);
// Create a directory
mkdir('testing');
// Remove dir if empty
rmdir('testing');
// Copy file
echo copy('file1.txt', 'file2.txt');
// Rename file
rename('file2.txt', 'myfile.txt');
// Delete File
unlink('myfile.txt');
// Write from file to string
echo file_get_contents($file);
// Write string to file
echo file_put_contents($file, 'Goodbye World');
$current = file_get_contents($file);
$current .= ' Goodbye World';
file_put_contents($file, $current);
// Open File For Reading
$handle = fopen($file, 'r');
$data = fread($handle, filesize($file));
echo $data;
fclose($handle);
// Open file for writing
$handle = fopen('file2.txt', 'w');
$txt = "John Doe\n";
fwrite($handle, $txt);
$txt = "Steve Smith\n";
fwrite($handle, $txt);
fclose($handle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment