简体   繁体   English

PHP上传到两个不同的目录

[英]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/). 我目前正在使用以下脚本将其上载到主目录,但是我需要使用此脚本将其上载到第二个目录(../../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.) (当然, $another_dir是您要将文件复制到的目录。)

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. 您可以检查这两个操作之间的错误,仅可以在第一个操作之后报告成功,并且如果第二个操作失败则可以在内部进行日志记录,等等。这取决于您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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