![]() |
|
With my 3+ years for PHP Programming, I have found out that there are some functions which are used often but are not found bundled with PHP. I have grouped them into a single file. Please feel free to comment on errors or to add any new additions.
Remove Directory
We have function named rmdir which removes a file. But it does not work for folders. The function below deletes a folder by recursively deleting the files inside it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); } } reset($objects); rmdir($dir); } } |
Copy Directory
We have copy function which copies a single file. But it does not work for folders. The function below copies a folder by recursively copying the files inside it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function ccdir($from,$to){ mkdir($to); if(is_dir($from)){ $objects = scandir($from); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($from."/".$object) == "dir"){ ccdir($from."/".$object,$to."/".$object); } else copy($from."/".$object,$to."/".$object); } } } } |
Zip a folder using PHP
Its very easy to use the UNIX ‘ZIP’ command for Zipping files, but sometimes they won’t work in servers which does not support such functionality. This function is purely based on PHP and works everywhere.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function zipFolder($folder_path,$zipfilename){ ini_set("max_execution_time", 300); $zip = new ZipArchive(); if ($zip->open($zipfilename.'.zip', ZIPARCHIVE::CREATE) !== TRUE) { die ("Could not open archive"); } $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder_path."/")); foreach ($iterator as $key=>$value) { $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key"); } $zip->close(); echo "Archive created successfully."; } |
Sending HTML Emails
Sending emails are easy using PHP mail function. But the mail goes to spam folder(esp gmail), if they are not having proper headers. This one becomes handy in such occasions.
|
1 2 3 4 5 6 7 8 |
function sentEmail($to,$subject,$content,$from='admin@yourdomain.com'){ $headers = "From: " . $from . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $content = "<html><body>".$content."</body></html>"; mail($to,'sConnection Message',$content,$headers); } |

