将图像从一个文件夹复制到另一个文件夹


Copy images from one folder to another

我的Web应用程序存储在XAMPP/htdocs/projectname/目录下。我有图片(来源)&Img(目标)文件夹在上面的目录。我正在编写以下代码行,以获得从一个文件夹复制图像到另一个。但我得到以下警告:(警告:复制(资源id #3/image1.jpg):打开流失败:C:'xampp'htdocs中没有这样的文件或目录)和图像未复制到目标。

<?php
        $src = opendir('../images/');
    $dest = opendir('../img/');
    while($readFile = readdir($src)){
            if($readFile != '.' && $readFile != '..'){
                 if(!file_exists($readFile)){
                if(copy($src.$readFile, $dest.$readFile)){
                echo "Copy file";
            }else{
                    echo "Canot Copy file";
                }
                   }
            }
        }
?>

只是猜测(对不起),但我不相信你可以这样使用$src = opendir(...)$src.$readFile。试试这样做:

$srcPath = '../images/';
$destPath = '../img/';  
$srcDir = opendir($srcPath);
while($readFile = readdir($srcDir))
{
    if($readFile != '.' && $readFile != '..')
    {
        /* this check doesn't really make sense to me,
           you might want !file_exists($destPath . $readFile) */
        if (!file_exists($readFile)) 
        {
            if(copy($srcPath . $readFile, $destPath . $readFile))
            {
                echo "Copy file";
            }
            else
            {
                echo "Canot Copy file";
            }
        }
    }
}
closedir($srcDir); // good idea to always close your handles

在你的代码中替换这一行,这肯定会起作用。

if(copy("../images/".$readFile, "../img/".$readFile))

你给出了错误的路径,如果你的文件路径说script.php是"XAMPP/htdocs/projectname/script.php"和图像和img都在"projectname"文件夹比你应该使用以下值$srcPath和$destPath,改变他们的值

$srcPath = 'images/';
$destPath = 'img/';
public function getImage()
  {
    $Path='image/'; //complete image directory path
    $destPath = '/edit_image/';
    // makes new folder, if not exists.
    if(!file_exists($destPath) || file_exists($destPath)) 
    {
        rmdir($destPath);
        mkdir($destPath, 0777);
    }
    $imageName='abc.jpg';
    $Path=$Path.$imageName;
    $dest=$destPath.$imageName;
    if(copy($Path, $dest));
  }