Ben10
Ben10

Reputation: 3259

How to copy the only particular extension file in php?

Hello I am using following code for copy the files from one directory to another directory its worked like a charms This is my code:

<?php
function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}  if(isset($_POST["source"]) && isset($_POST["destination"])){

$src = $_POST["source"];

$dst = $_POST["destination" ];
recurse_copy($src,$dst);
}
?>

now I want to copy only the image files from the source folder.How can i do that?

Upvotes: 2

Views: 1095

Answers (2)

Andras Toth
Andras Toth

Reputation: 628

I see 2 ways:

  • You make an array of the possible file extensions, and check end of $file var for every file.
  • Or you use exif_imagetype() function along with the Imagetype contants to determine the file type from the signature. Documentation is here. However, there is a dependency for this, for details see the first user contributed note.

Upvotes: 3

Narek
Narek

Reputation: 3823

Getimagesize can help you. It return false on error. File not image is error.

<?php
function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                /////
                if(!getimagesize($src . '/' . $file,$dst . '/' . $file)) continue;
                /////
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}  if(isset($_POST["source"]) && isset($_POST["destination"])){

$src = $_POST["source"];

$dst = $_POST["destination" ];
recurse_copy($src,$dst);
}
?>

OR

You just can check file extension:

$ext = end(explode('.',$file));

But it can lie.

Upvotes: 4

Related Questions