Home  >  Article  >  Backend Development  >  PHP introductory tutorial - upload file example sharing

PHP introductory tutorial - upload file example sharing

墨辰丷
墨辰丷Original
2018-06-01 11:44:241192browse

This article mainly introduces the method of uploading files in the PHP introductory tutorial. It analyzes the steps of uploading files in PHP and related implementation techniques in detail with examples. Friends in need can refer to

Demo1.php

上传文件:

Demo2.php

';
  //is_uploaded_file -- 判断文件是否是通过 HTTP POST 上传的
  //通过 HTTP POST 上传后,文件会存放在临时文件夹下
  $fileMimes = array('image/jpeg','image/pjpeg','image/gif','image/png','image/x-png');
  //判断类型是否是数组里的一种
  if(is_array($fileMimes)){
    if(!in_array($_FILES['userfile']['type'],$fileMimes)){
      echo "";
      exit;
    }
  }
  //创建一个常量
  define('URL',dirname(__FILE__).'\uploads');
  echo URL;
  //判断目录是否存在
  if(!is_dir(URL)){
    mkdir(URL,0777); //最大权限0777,意思是如果没有这个目录,那么就创建
  }
  define('MAX_SIZE',2000000);
  if($_FILES['userfile']['size'] > MAX_SIZE){
    echo "";
    exit;
  }
  //还有两个问题要验证
  //第二个问题,只允许 JPG 文件
// if($_FILES['userfile']['type'] != 'image/jpeg' && $_FILES['userfile']['type'] != 'image/pjpeg'){
//   echo "";
//   exit ;
// }
// switch ($_FILES['userfile']['type']){
//   case 'image/jpeg'://火狐
//     break;
//   case 'image/pjpeg':
//     break;
//   case 'image/gif':
//     break;
//   case 'image/png'://火狐
//     break;
//   case 'image/x-png'://IE
//     break;
//   default: echo "";
//   exit ;
// }
  //第一个问题,如果上传错误,怎么办
  if($_FILES['userfile']['error']>0){
    switch ($_FILES['userfile']['error']){
      case 1:echo "";
      break;
      case 2:echo "";
      break;
      case 3:echo "";
      break;
      case 4:echo "";
      break;
    }
    exit;
  }
  if(is_uploaded_file($_FILES['userfile']['tmp_name'])){
    //就在这里移动了
    //move_uploaded_file -- 将上传的文件移动到新位置
    //第一个参数,写上临时文件的地址,
    //第二个参数,第二个参数要写上你要存在的地址
    //先去判断这个目录是否存在
    //如果想屏蔽掉警告,直接加上 @
    if(!move_uploaded_file($_FILES['userfile']['tmp_name'],URL.'/'.$_FILES['userfile']['name'])){
      //如果移动失败,就失败
      echo '移动失败';
      exit;
    }
  }else{
    echo "";
    exit;
  }
  //全部通过就上传成功了
  //必须传一个值给Demo3.php
  //文件上传的地址
  echo "";
?>

Demo3.php

";
?>

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

phpMethods to solve DOM garbled code

php Detailed explanation of PDO exception handling method

php.ini date.timezone setting brief introduction

The above is the detailed content of PHP introductory tutorial - upload file example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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