php file upload

form.php

<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">

<label for="file">上传:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="上传" />
</form>

</body>
</html>

 upload.php

<?php
//Set the upload file size limit (unit b)
$max_size=500000;
//Set the file format limit for uploaded files
$format=array("image/jpeg","image/gif","image/png");
//File upload directory
$dir=dirname(__FILE__) ."/upload/";


//name of the uploaded file
$name=$_FILES["file"]["name"];
//Type of uploaded file
$type=$_FILES["file"]["type"];
//The size of the uploaded file, in bytes
$size=$_FILES["file"]["size"];
//name of temporary copy of file stored on server
$tmp_name=$_FILES["file"]["tmp_name"];
//Error code caused by file upload
$error=$_FILES["file"]["error"];

//determine file size
if($size>$max_size){
    exit("The file size exceeds the maximum value");
}
// Determine the file format
if(!in_array($type,$format)){
    exit("Invalid file format");
}

/ / Determine the upload directory, create it if it does not exist
if(!is_dir($dir)){
    mkdir ($ dir, true);
}

//generate filename
date_default_timezone_set("PRC");
$file_name=time().mt_rand(1111, 999999);
//get file format
$ext=substr($type, strpos($type, "/")+1);

if($error>0){
    exit($error);
}else{
    if(move_uploaded_file($tmp_name, $dir.$file_name.".".$ext)){
       exit("Upload successful");
    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326952541&siteId=291194637