无法打开流:没有这样的文件或目录

时间:2016-09-17 08:41:12

标签: php image copy filestream

我想将选定的图像文件一个文件夹复制到另一个文件夹中。图像选择过程是动态的。我使用下面的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,则上述代码运行完美。但如果所选图像计数高于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,则第一张图像将成功复制,下一张(第二张图像)将产生错误。发生了什么事?

1 个答案:

答案 0 :(得分:1)

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

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

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

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

尝试在其中添加一些随机常量,例如

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