Tuesday, 10 February 2015

Add any content at start & end of files in directories.


Hi folks,

I have written a reusable PHP function for adding text/content at the Start and end of numbers of files in a directory/folder.

I was working with Japanese project where I got the  requirement to put some html tags at Start and End of files and numbers of files were huge.

So I wrote this PHP function which will require some parameter like Folder name, Start Content and End Content.
And you are done.

This PHP function will prepended and append the required text at Start and End of files all files of mentioned folder.

Please refer this function

/*Function to add any texts/content at Start and end of the all the file in a directory.
Function name :addTextStartEnd()
Date 10/1/2015
Params: Directory name,file extension, Start Content to add, End Content to add.
Autore : Peeyush Guhe
*/


$directory_name="two";
$file_extn = ".html"; //provide the extension of the files.
//$file_extn = ".*"; //uncomment this line and comment the above list if you have files with different extension.
$startContent = "<b><i>This is start content</i></b> ";
$endContent="<u>This is end content</u>";
 
addTextStartEnd($directory_name,$file_extn,$startContent,$endContent);
 
echo "Content added";



function addTextStartEnd($directory_name,$file_extn,$startContent,$endContent){
//glob("2006/*.html")
    foreach (glob($directory_name."/*".$file_extn) as $file) {
        $new_content_start = $startContent; // this gets  
prepended
        $new_content_end = $endContent;   
        $handle = fopen($file, "r+");
        $len = strlen($new_content_start);
        $final_len = filesize($file) + $len;       
        $cache_old = fread($handle, $len);       
        rewind($handle);
        $i = 1;
        while (ftell($handle) < $final_len)
        {
          fwrite($handle, $new_content_start);
          $new_content_start = $cache_old;     
          $cache_old = fread($handle, $len);         
          fseek($handle, $i * $len);
          $i++;
        }
file_put_contents($file, $new_content_end, FILE_APPEND | LOCK_EX);
    }
    return true;       
}


Please do post/comment if you need any modifications in this function .



1 comment: