php上传到两个不同的目录

时间:2016-02-01 16:54:03

标签: php upload

我目前正在使用以下脚本上传到主目录,但是我需要将其上传到下面一级的第二个目录(../../gfx/)。 任何想法如何使这两个上传工作?



<?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);
}
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您已将其移至某个位置:

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

之后只需copy to another。如果只有一个成功由您决定,您希望如何向用户报告。但是,例如,如果它只是&#34;成功&#34;如果两个文件都已创建,那么您可以像这样移动/复制:

$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!');
}

(当然,$another_dir是您要复制文件的目录。)

您可以检查两个操作之间的错误,您可以仅在第一个操作之后报告成功,并且只是在内部记录第二个操作是否失败等等。这取决于您。