I'm getting an error when i upload a file into mysql: "Error! A file was not sent!".
Here is my PHP code please look into it and let me know where the error is in my code.
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
<a href="list_files.php">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
$dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file'] ['tmp_name']));
$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
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
} else
{
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click <a href="index.html">here</a> to go back</p>';
?>
You need at least one non-file form field to have the form submit properly. The $_FILES array does not get set without data in the $_POST array. Adding a hidden form field above your file input field will fix it.
<input type="hidden" name="form_field">
<input type="file" name="uploaded_file"><br>
Or add a name attribute to the submit button input tag like this:
<input type="submit" name="submit" value="Upload file">
In the non working demo you'll see that, even though the file is uploaded the $_FILES array is empty.
If you get HTTP Upload Disabled
when doing
if(ini_get('file_uploads') == 1){
echo 'HTTP Upload Enabled';
}
else {
echo 'HTTP Upload Disabled';
}
file_uploads
on your server is turned off by default
If you have access to / and can modify your php.ini
file -
file_uploads = 1
In your .htaccess
file -
php_value file_uploads 1
Or at the top your php page
<?php
ini_set('file_uploads',1);
?>
see http://www.php.net/manual/en/ini.core.php#ini.file-uploads