无法打开流:没有那个文件或目录

Failed to open stream: No such file or directory

我想将选定的图像文件从一个文件夹复制到另一个文件夹。图像选择过程是动态的。我正在使用下面的 php 代码进行复制过程。

//$cnt is count of selected images

for($i=0;$i<$cnt;$i++)
    {
    $img = $sel['album_images']; //name of file to be copied
                //read the file
                $fp = fopen('uploads/members/album/'.$_SESSION['ses_userid'].'/'.$img, 'r') or die("Could not contact $img");
                $page_contents = "";
                while ($new_text = fread($fp, 100)) 
                {               
                $page_contents .= $new_text;
                }
                chdir("uploads/products/design/"); //This moves you from the current directory user to the images directory in the new user's directory
                $newfile = "product-".strtotime('now').".png"; //name of your new file
                //create new file and write what you read from old file into it
                $fd = fopen($newfile, 'w');
                fwrite($fd, $page_contents);
                fclose ($fd);
}

上面的代码是 运行 完美的,因为如果选择的图像数量是 1.but 如果选择的图像数量超过 1,它会产生错误。

Error is : 

Warning: fopen(uploads/members/album/72/full_e5829jellyfish.jpg) [function.fopen]: failed to open stream: No such file or directory in D:\wamp\www\myprint\photoprint_step2.php on line 51
    Could not contact full_e5829jellyfish.jpg

注意:如果选择的图像数量为2,则第一张图像将复制成功,接下来(第二张图像)将产生错误。发生什么事了?

我假设您的 for-cycle 导致了错误,因为您只更改了一次目录(而不是将其更改回来),而在第二次和以后的迭代中,您没有。

我不会使用 chdir 功能,为了代码的整洁和可读性,最好使用完整路径。

$newfile = "uploads/products/design/product-".strtotime('now').".png";

请注意使用 strtotime('now') 作为图像文件的唯一标识符,因为一秒钟内可以保存很多图像,这可能就是您的情况。这就是为什么您的图像在第二次迭代中具有相同名称的原因,它保存了第二张图像的内容,但替换了前一张图像。

尝试在其中放入一些随机常数,像这样

$newfile = "uploads/products/design/product-".strtotime('now')."-".rand(1000,9999).".png";