<?php
// Set the max file size and upload path
$maxFileSize = (100 * 1024);
$uploadDir = 'upload/';
// Do not edit these values
$showForm = false;
$formError = false;
$uploadFilePath = '';
if (isset($_POST['submit'])) {
// Check for upload errors
if ($_FILES['file']['error'] > 0) {
$formError = 'Error: ' . $_FILES['file']['error'];
} else {
$fileName = $_FILES['file']['name'] ; // the name of the uploaded file
$fileType = $_FILES['file']['type'] ; // the type of the uploaded file
$fileSize = $_FILES['file']['size'] ; // the size in bytes of the uploaded file
$tempLocation = $_FILES['file']['tmp_name']; // the temp file location
// Check the file type
if ( ! in_array($fileType, array('image/jpeg', 'image/png'))) {
$formError = 'Invalid file type. Must be jpeg or png.';
}
// Check the file size
elseif ($fileSize > $maxFileSize || $fileSize < 0) {
$formError = 'Invalid file size. Must be between 1 and ' . $maxFileSize . ' kb.';
}
// Make sure the file does not exist
elseif (file_exists($uploadDir . $fileName)) {
$formError = 'The file "' . $fileName . '" already exists.';
}
// The file is valid so continue with the upload
else {
// Move the file from the tmp dir to the desired location
move_uploaded_file($tempLocation, $uploadDir . $fileName);
// Remember the complete upload file path
$uploadFilePath = $uploadDir . $fileName;
// Store the upload information in the database
$c = mysql_connect('localhost','root','') or die (mysql_error());
$d = mysql_select_db('datebase_name') or die(mysql_error());
mysql_query("insert into table_name values('','$fileName','$fileType','$fileSize')") or die(mysql_error());
}
}
} else {
$showForm = true;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<?php
if ($showForm) {
if ($formError !== false) {
echo '<p>' . $formError . '</p>';
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit"><br>
</form>
<?php
} else {
echo '<p>File stored at: ' . $uploadFilePath . '</p>';
}
?>
</body>
</html>
此处文件将存储在名为“upload”的文件夹中,上传的文件大小和类型保存在数据库中。
在上面的示例中,数据库表有 4 列(按此顺序):id、文件名、文件类型和文件大小。
注意:这是一个基本示例。不要忘记改进文件验证以增强安全性。最好不要向用户显示上传位置。在大多数情况下,像“文件上传成功”这样的上传确认就足够了。