简体   繁体   中英

php upload to two different directories

I am currently using the below script to upload to the main directory, however I need this to upload to a second directory which is one level below (../../gfx/). Any ideas how I can make this work for both uploads?

 <?php // If you want to ignore the uploaded files, // set $demo_mode to true; $demo_mode = false; $upload_dir = '../gfx/'; $allowed_ext = array('jpg','jpeg','png','gif'); if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){ exit_status('Error! Wrong HTTP method!'); } if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){ $pic = $_FILES['pic']; if(!in_array(get_extension($pic['name']),$allowed_ext)){ exit_status('Only '.implode(',',$allowed_ext).' files are allowed!'); } if($demo_mode){ // File uploads are ignored. We only log them. $line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name'])); file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND); exit_status('Uploads are ignored in demo mode.'); } // Move the uploaded file from the temporary // directory to the uploads folder: if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){ exit_status('File was uploaded successfuly!'); } } exit_status('Something went wrong with your upload!'); // Helper functions function exit_status($str){ echo json_encode(array('status'=>$str)); exit; } function get_extension($file_name){ $ext = explode('.', $file_name); $ext = array_pop($ext); return strtolower($ext); } ?> 

You're already moving it to one location:

if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
    exit_status('File was uploaded successfuly!');
}

Just copy to another afterward. How you want to report to the user in the event that only one succeeds is up to you. But, for example, if it's only "successful" if both files are created, then you can move/copy like this:

$success = move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
$success = copy($upload_dir.$pic['name'], $another_dir.$pic['name']);

if ($success === true) {
    exit_status('File was uploaded successfuly!');
}

(Where, of course, $another_dir is the directory to which you want to duplicate the file.)

You can check for errors in between the two operations, you can report success only after the first and simply internally log if the second fails, etc. That's up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM