nackolysis nackolysis - 2 months ago 15
PHP Question

Uploading the same image to two different directories

I want to upload the same image to two different directory but it only uploads to the first directory called

upload/
. I have also tried copy command but cannot get the file to be uploaded to the second directory called
photo/
. How can I accomplish that?

<?php

$uname=strip_tags($_POST['uname']);

//$uname='user1';
$session_uid='user1';

$path='upload/';
$path1='photo/';


include_once 'background.php';

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST" && isset($session_uid))
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];


if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{

$actual_image_name = time().$session_uid.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
$bgSave='<div id="uX'.$session_uid.'" class="bgSave wallbutton blackButton">Image Saved</div>';
if(move_uploaded_file($tmp, $path.$actual_image_name)){

echo $bgSave.'<img src="http://localhost/testing/'.$path.$actual_image_name.'" id="timelineBGload" class="headerimage ui-corner-all" style="top:0px"/>';

}

// try upload to the second directyory
if(!copy ($path, $path1.$actual_image_name)){
throw new Exception('Could not move 2nd file');
exit();
}


else
{
echo "Fail upload folder with read access.";
}
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format.";
}

else
echo "Please select image..!";

exit;
}
?>

Answer

Just like you did in move_uploaded_file(), you need to give the full source path to the file. $tmp = $_FILES['photoimg']['tmp_name'] is the full path to the source temp file. So after the move you need to give the full source path using $path and $actual_image_name:

if(!copy($path.$actual_image_name, $path1.$actual_image_name)){
    throw new Exception('Could not move 2nd file');
    exit();
}