目录结构图:
【本例把upload文件夹当做远程服务器下的文件夹】
运行127.0.0.1/test.php
test.php
$file_url = './img/5.jpg';
$url = 'http://127.0.0.1/upload/upload.php?dirname=news';
$pathinfo = pathinfo($file_url);
$filename = $pathinfo['basename'];
$path = $file_url;
$type = $pathinfo['extension'];
$data = upload_file($url, $filename, $path, $type);
var_dump($data) ;
/**
* @param string $url
* @param string $filename
* @param string $path
* @param string $type
* @return string
*/
function upload_file($url,$filename,$path,$type){
//php 5.5以上的用法
if (class_exists('\CURLFile')) {
$data = array('file' => new \CURLFile(realpath($path),$type,$filename));
} else {
$data = array(
'file'=>'@'.realpath($path).";type=".$type.";filename=".$filename
);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return_data = curl_exec($ch);
curl_close($ch);
return $return_data;
}
?>
upload.php
if($_FILES){
$filename = $_FILES['file']['name'];
$tmpname = $_FILES['file']['tmp_name'];
$dirname = $_GET['dirname'];
if(!is_dir($dirname)){
mkdir($dirname);
chmod($dirname,0777);
}
$dateDir = date("ymd"); //日期目录:20170705
$filePath = $dirname.'/'.$dateDir;
if(!is_dir($filePath)){
mkdir($filePath);
chmod($filePath,0777);
}
$newloc = dirname(__FILE__).'/'.$filePath.'/'.$filename;
if(move_uploaded_file($tmpname,$newloc)){
echo true;
}else{
echo false;
}
}
?>