Home>Article>Backend Development> PHP file upload (implemented using global array $_FILES)
This article mainly talks about using the global array $_FILES in PHP to implement file upload. It has certain reference value. Interested friends can learn about it.
The PHP global array $_FILES is used here to implement file upload:
HTML code:
PHP code:
if (!empty($_FILES)) { // 限制文件大小 $file_size = $_FILES["file"]["size"]; // 限制2M大小 if ($file_size > 1024 * 1024 * 2) { echo '文件大小超过限制'; exit; } // 限制文件上传类型 $file_type = $_FILES["file"]["type"]; $file_type_arr = ['image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif']; if (!in_array($file_type, $file_type_arr)) { echo '上传文件类型错误'; exit; } // 文件上传到服务器临时文件夹之后的文件名 $tem_name = $_FILES['file']['tmp_name']; // 取得文件后缀名 $file_fix = explode('.', $_FILES['file']['name'])[1] ? explode('.', $_FILES['file']['name'])[1] : 'png'; // 文件重命名,这里自动生成一个不重复的名字,方便使用 $name = md5(uniqid(md5(microtime(true)), true)) . '.' . $file_fix; // 要存放文件的目录定义,这里按日期分开存储 $file_dir = dirname(__FILE__) . '/upload/' . date('Ymd') . '/'; // 检测要存放文件的目录是否存在,不存在则创建 if (!is_dir($file_dir)) { mkdir($file_dir, 0755, true); } // 移动文件到指定目录下 @ move_uploaded_file($tem_name, $file_dir . $name); echo '上传成功'; exit; } else { echo '文件上传失败'; exit; }
Related tutorials:PHP video tutorial
The above is the detailed content of PHP file upload (implemented using global array $_FILES). For more information, please follow other related articles on the PHP Chinese website!