一个非常简单的PHP处理文件上传程序。主要是供前端测试使用。主要使用了php自带的两个函数:
is_uploaded_file
和move_uploaded_file
。
<?php
/**
* Created by PhpStorm.
* User: Jamling
* Date: 2017/11/20
* Time: 16:36
*/
define('ROOT', $_SERVER['PHP_SELF']);
$method = $_SERVER['REQUEST_METHOD'];
if ('POST' === $method) {
return doUpload();
}
else {
return doGet();
}
function doUpload()
{
if (empty($_FILES) || !isset($_FILES['file'])) {
echo json_encode([
'code' => -1,
'message' => 'No files in request, you need declared a named "file" file field!'
]);
return;
}
$uf = $_FILES['file'];
$tmp = $uf['tmp_name'];
$type = $uf['type'];
$name = $uf['name'];
$size = $uf['size'];
//var_dump($uf);
$up_dir = './';
if (is_uploaded_file($tmp)) {
$dst = $up_dir . basename($name);
if (move_uploaded_file($tmp, $dst)) {
echo json_encode([
'code' => 0,
'message' => 'success',
'data' => [
'name' => $name,
'size' => $size,
'type' => $type,
'file_path' => 'http://' . $_SERVER['SERVER_ADDR'] . ':' . $_SERVER['SERVER_PORT'] . '/test/' . $name,
],
]);
return;
}
}
echo json_encode([
'code' => -1,
'message' => 'Upload failed'
]);
}
function doGet()
{
echo
'<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form action="upload.php" enctype="multipart/form-data" method="post">
上传文件<br>
<input type="file" name="file"/><br>
<input type="submit" value="上传"/>
</form>
</body>
</html>';
}