Reputation: 35
I'm trying to upload a file from a html form so that the file goes to a specific folder and the path get uploaded to a database. The database part works fine but the file doesnt go to my destination folder. I have the folder permissions set to 777 and in my php.ini file, file_uploads = on.
<?php
require 'config.php';
$connection = new mysqli($servername, $username, $password, $db);
foreach ($_FILES['upload']['name'] as $key => $name) {
if( move_uploaded_file($_FILES['upload']['name'][$key], '/upload_test/' .
$name)){
echo "Uploaded";
} else {
echo "Debug ", print_r($_FILES);
};
$path = '/upload_test/' . $name;
mysqli_query($connection, "insert into docs (path) values ('$path')");
}
?>
<script src="addInput.js" type="text/javascript"></script>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<div id="dynamicInput">
<input type="file" name="upload[]" multiple><input type="button"
value="+" onClick="addInput('dynamicInput');">
</div>
<input type="submit" value="Upload">
</form>
When I try to upload it returns this:
Debug: Array(
[upload] => Array(
[name] => Array([0] => test.docx)
[type] => Array([0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document)
[tmp_name] => Array([0] => /tmp/phputnLek)
[error] => Array([0] => 0)
[size] => Array([0] => 12551)
)
)
Upvotes: 0
Views: 1488
Reputation: 91734
Based on your comment, it seems that you are trying to upload to the wrong directory:
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key], '/upload_test/' . $name)) {
Note that the path '/upload_test/' . $name
is on the root of your file-system as it starts with a slash /
.
If you want to move the file to a directory relative to the one you are currently running the script from, you would need:
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key], 'upload_test/' . $name)) {
^ relative to the current path
As relative paths tend to lead to confusion, you can also set a variable to define the root of your web-site relative to the root of the file-system or use the value provide by php, $_SERVER['DOCUMENT_ROOT']
.
For example:
define('WEBROOT', '/var/www/html');
...
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key],
WEBROOT . '/multiple_file_upload/upload_test/' . $name)) {
or:
if (move_uploaded_file($_FILES['upload']['tmp_name'][$key],
$_SERVER['DOCUMENT_ROOT'] . '/multiple_file_upload/upload_test/' . $name)) {
Upvotes: 2
Reputation: 543
You have to move the temp-file to the new destination! In your case you´re trying to move the original filename to the destination folder.
This should do it ...
move_uploaded_file($_FILES['upload']['tmp_name'][$key], '/upload_test/' . $name);
Upvotes: 1