1 回答

TA貢獻1818條經驗 獲得超11個贊
<?php
/*
* CREATE TABLE `uploads` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`timestamp` int(11) DEFAULT NULL,
`file` varchar(400) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
$mysqli = new mysqli('localhost', 'devel', 'devel', 'upload_db');
$timestamp = time();
$success_images = [];
$total = count($_FILES[ 'upload' ][ 'name' ]);
if ($total == 0) {
echo "Please upload at least one file";
$uploadOk = 0;
} else {
$uploadOk = 1;
for ($i = 0; $i < $total; $i++) {
$tmpFilePath = $_FILES[ "upload" ][ "tmp_name" ][ $i ];
if ($tmpFilePath != '') {
$newFilePath = "./uploadFiles/" . $_FILES[ 'upload' ][ 'name' ][ $i ];
$Name = basename($_FILES[ "upload" ][ "name" ][ $i ]);
$parts = pathinfo($Name);
$extension = strtolower($parts[ 'extension' ]);
if ($extension == 'jpg' || $extension == 'png') {
// there may be $newFilePath I think
if (move_uploaded_file($_FILES[ "upload" ][ "tmp_name" ][ $i ], $newFilePath)) {
$mysqli->query("INSERT INTO uploads (timestamp, file) VALUES ('$timestamp', '$Name')");
$id = $mysqli->insert_id;
$success_images[ $id ] = $newFilePath;
$uploadOk = 1;
} else {
echo "Error";
$uploadOk = 0;
break; // break loop !!!
}
} else {
echo "Just JPG and PNG files are allowed";
$uploadOk = 0;
break;
}
}
}
if ($uploadOk === 0) {
foreach ($success_images as $id => $filename) {
// `id` - primary key of table uploads?
$mysqli->query(sprintf('DELETE FROM uploads WHERE `id`=%d', $id));
if (file_exists($filename)) {
unlink($filename);
}
}
} else {
foreach ($success_images as $id => $filename) {
echo "<h2>The file <i>$filename</i> has been uploaded.</h2>";
}
}
}
?>
<form method="POST" enctype="multipart/form-data">
<input type="file" multiple name="upload[]"/>
<input type="submit" value="do_upload"/>
</form>
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報