AMSOL e-Tutor

AMSOL e-Tutor helps you learn web programming better with examples. It also gives sample codes to implement.

PHP File Function


PHP developers often need to perform file handling. like reading from file, writing content to file etc. PHP has several functions for creating, reading, uploading, and editing files.

PHP readfile() Function

The readfile() function reads a file and writes it to the output buffer.


echo readfile("test.txt");

PHP File Open/Read/Close

For reading long files, PHP offers a better choice for file handling


$myfile = fopen("test.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("test.txt"));
fclose($myfile);

Modes - Description

r Open a file for read only. w Open a file for write only. a Same as w option, The existing data in file is preserved. x Creates a new file for write only. r+ Open a file for read/write. w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. a+ Open a file for read/write. Appends data. Creates a new file if the file doesn't exist x+ Creates a new file for read/write.

PHP file_exists

Checks if file exisits on the file system

 
	if (file_exists('thumb.jpg')) {
		echo "file already exisits";
	}

PHP Read File Line by line

Often you need to get file contents and process its output line by line, then this will help you.


	$file = fopen("test.txt", "r");
	//Output lines until EOF is reached
	while(! feof($file)) {
	  $line = fgets($file);
	  echo $line. "
";
	}

fclose($file);

PHP Read file using file_get_contents

file_get_contents reads or gets file contents at once



print file_get_contents("abc.txt");

PHP File change time

To check the file modified time use filemtime function


echo filemtime("abc.txt");

PHP Get file information using pathinfo

 


//************************************
$file_info = pathinfo('images/about-bg.jpg');
$file_info = pathinfo('/www/htdocs/index.html');
echo $file_info['dirname'], "
"; //shows dir name if dir name is supplied in file path
echo $file_info['basename'], "
"; //actual name of file
echo $file_info['extension'], "
"; // file extension
echo $file_info['filename'], "
"; // file name without extension. filename is only available since PHP 5.2

Creating directory

 


mkdir("test");

Creating directory if not exists and apply persmissions

if (!file_exists('newdir')) { mkdir('newdir', 0777, true); }

Get files changed in last 10 days

If you want to get filenames which are changed/modified in last 10 days,


$dir = opendir("."); //current dir
clearstatcache(); //clears the file status cache
$MTIME = strtotime("-10 days");
while(false != ($file = readdir($dir)))
{
	if (filemtime($file) >= $MTIME)
	{
		if ($file != "." && $file != "..") 
		{
		echo $file.'
';
		}
	}
}

PHP Upload File Using FTP

PHP offers FTP functions which can be used to upload files to any FTP location, Mostly developers use this function to automate upload tasks using cron jobs


$FTP_Server = "www.mydomain.com";
$FTP_UserName = "myftpuser";
$FTP_UserPass = "1234567";
	
	$File_To_Upload = "date.php";
	$Uploaded_File_Name = "public_html/cdn/123date.php";
	PHP_FTP_Upload($FTP_Server, $FTP_UserName, $FTP_UserPass, $File_To_Upload, $Uploaded_File_Name);
	
	
function PHP_FTP_Upload($FTP_Server, $FTP_UserName, $FTP_UserPass, $File_To_Upload, $Uploaded_File_Name){
    $FTP_Connection = ftp_connect($FTP_Server);  // Connects to FTP Server

    // FTP Login
    if (@ftp_login($FTP_Connection, $FTP_UserName, $FTP_UserPass)){
		ftp_pasv($FTP_Connection, true);
        // FTP connected
    }else{
        return false;
		// Ooooopsss !!! FTP Not connected
    }

    ftp_put($FTP_Connection, $Uploaded_File_Name, $File_To_Upload, FTP_BINARY);
    ftp_close($FTP_Connection);
    return true;
}	

PHP Upload multiple files modified in last 10 days

Some times developers need to automate backup of files from one server to another, these may be user uploaded files like profile images, program generated reports or logs.

first of all, It creates an array of file names which are modified in last few days.

In next step, for each loop iterates and upload files one by one.


$FTP_Server = "www.mydomain.com";
$FTP_UserName = "myftpuser";
$FTP_UserPass = "1234567";


$FILES_MOD = array(); //declare array to store modified file names
$dir = opendir("."); //current dir
clearstatcache(); //clears the file status cache
$MTIME = strtotime("-10 days"); //days you can change to hours as well

while(false != ($file = readdir($dir))){
	if (filemtime($file) >= $MTIME){
		if ($file != "." && $file != "..") {
		array_push($FILES_MOD,$file);
		}
	}
}

foreach ($FILES_MOD as $FILE_NAME) {
	$File_To_Upload = $FILE_NAME;
	$Uploaded_File_Name = "public_html/cdn/".$FILE_NAME;	
	PHP_FTP_Upload($FTP_Server, $FTP_UserName, $FTP_UserPass, $File_To_Upload, $Uploaded_File_Name);
}



//******************** UPLOAD FILES MODIFIED IN LAST 10 DAYS *********	
function PHP_FTP_Upload($FTP_Server, $FTP_UserName, $FTP_UserPass, $File_To_Upload, $Uploaded_File_Name){
    // connect to server
    $connection = ftp_connect($FTP_Server);

    // login
    if (@ftp_login($connection, $FTP_UserName, $FTP_UserPass)){
		ftp_pasv($connection, true);
        // successfully connected
    }else{
        return false;
    }

    ftp_put($connection, $Uploaded_File_Name, $File_To_Upload, FTP_BINARY);
    ftp_close($connection);
    return true;
}