Home > Backend Development > PHP Tutorial > php上传文件,创建递归目录的实例代码_PHP

php上传文件,创建递归目录的实例代码_PHP

WBOY
Release: 2016-06-01 11:59:22
Original
824 people have browsed it

复制代码 代码如下:

$uid=$_REQUEST['uid'];

$avatar = 'D:/avic/discuz/uc_server/data/avatar/'.get_avatar($uid, $size, $type);
$dir=dirname($avatar);

//创建目录成功后移动临时文件
if(mkdirs($dir)){
  if($_FILES["pic"]["error"] >= 0){
    if(move_uploaded_file($_FILES['pic']['tmp_name'],$avatar)){
      $errorcode=1;
    }else{
      $errorcode=0;
      $errormsg="文件移动失败";
    }
  }else{
    $errorcode=0;
    $errormsg=$_FILES['pic']['error'];
  }
}
$back=array("errorcode"=>$errorcode,'errormsg'=>$errormsg);
echo json_encode($back);

//返回图片要存储的路径
function get_avatar($uid, $size = 'middle', $type = '') {
  $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
  $uid = abs(intval($uid));
  $uid = sprintf("%09d", $uid);
  $dir1 = substr($uid, 0, 3);
  $dir2 = substr($uid, 3, 2);
  $dir3 = substr($uid, 5, 2);
  $typeadd = $type == 'real' ? '_real' : '';
  return $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).$typeadd."_avatar_$size.jpg";
}
//递归创建目录,若传的$dir不是绝对路径,则会和运行此方法的目录同级
function mkdirs($dir){
  if(!is_dir($dir)){
    if(!mkdirs(dirname($dir))){
      return false;
    }
   if(!mkdir($dir,0777)){
      return false;
    }
   }
return true;
}
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template