Oto kody:
upload.php
<!DOCTYPE html>
<head>
<title
>MySQL
file upload example
</title
> <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="index.php?go=add_file" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
<a href="index.php?go=download">See all files</a>
</p>
</body>
</html>
add_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) { // Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
include 'connection.php';
// Gather all required data
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!'; }
else {
echo 'Error! Failed to insert the file' . "<pre>{mysql_error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. ' . 'Error code: '. intval($_FILES['uploaded_file']['error']); }
}
else {
echo 'Error! A file was not sent!'; }
// Echo a link back to the main page
echo '<p>Click <a href="index.php?go=upload.php">here</a> to go back</p>'; ?>
download.php
<?php
// Connect to the database
include 'connection.php';
// Query for a list of all existing files
$sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`';
// Check if it was successfull
if($result) {
// Make sure there are some files in there
echo '<p>There are no files in the database</p>'; }
else {
// Print the top of a table
echo '<table width="100%"> <tr>
<td><b>Name</b></td>
<td><b>Mime</b></td>
<td><b>Size (bytes)</b></td>
<td><b>Created</b></td>
<td><b> </b></td>
</tr>';
// Print each file
<tr>
<td>{$row['name']}</td>
<td>{$row['mime']}</td>
<td>{$row['size']}</td>
<td>{$row['created']}</td>
<td><a href='index.php?go=get_file&id={$row['id']}'>Download</a></td>
</tr>";
}
// Close table
}
}
else
{
echo 'Error! SQL query failed:'; echo "<pre>{mysql_error}</pre>"; }
?>
get_file.php
<?php
// Make sure an ID was passed
// Get the ID
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!'); }
else {
// Connect to the database
include 'connection.php';
// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `file`
WHERE `id` = {$id}";
if($result) {
// Make sure the result is valid
// Get the row
// Print headers
header("Content-Type: ". $row['mime']); header("Content-Length: ". $row['size']); header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
}
else {
echo 'Error! No image exists with that ID.'; }
}
else {
echo "Error! Query failed: <pre>{mysql_error}</pre>"; }
}
}
else {
echo 'Error! No ID was passed.'; }
?>