move_uploaded_file() Unable to move file from tmp to dir - php

I've been searching for the solution but I can't find the answer.
I created a image upload form. It runs with ajaxform plugin. But still it doesn't upload to the directory.
The error_log says
move_uploaded_file() Unable to move file from [tmp] to [dir].
Then on the front end it says Upload Complete. But when the file is called, it doesn't exist.
HTML CODE:
<div class="imgupload hidden">
<form id="profpicform" action="" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="profpic">
<input type="submit" value="Submit File">
</form>
<div class="imguploadStatus">
<div class="imguploadProgress">
<div class="imguploadProgressBar"></div>
<div class="imguploadProgressPercent">0%</div>
</div>
<div class="imguploadMsg"></div>
</div>
<div class="imgpreview"></div>
</div>
JS:
var options = {
beforeSend: function()
{
$(".imguploadProgress").show();
$(".imguploadProgressBar").width('0%');
$(".imguploadMsg").html("");
$(".imguploadProgressPercent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$(".imguploadProgressBar").width(percentComplete+'%');
$(".imguploadProgressPercent").html(percentComplete+'%');
},
success: function()
{
$(".imguploadProgressBar").width('100%');
$(".imguploadProgressPercent").html('100%');
},
complete: function(response)
{
alert('Complecion');
},
error: function()
{
$(".imguploadMsg").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#profpicform").ajaxForm(options);
SEVER SIDE:
$output_dir = home_url()."/path/to/dir/";
if(isset($_FILES["profpic"])){
if ($_FILES["profpic"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}else{
move_uploaded_file($_FILES["profpic"]["tmp_name"],$output_dir. $_FILES["profpic"]["name"]);
if(get_user_meta($_SESSION['userid'], 'user_profile_picture')==""){
add_user_meta($_SESSION['userid'], 'user_profile_picture', $_FILES['profpic']);
}else{
update_user_meta($_SESSION['userid'], 'user_profile_picture', $_FILES['profpic']);
}
echo "Uploaded File :".$_FILES["profpic"]["name"];
}
}
They are only found in one PHP file. Folder permission for the directory is 777.

Try this:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["profpic"]["name"]);
#move_uploaded_file($_FILES['profpic']['tmp_name'], $target_path)

Look into the below case:
$file_tmp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_destination = 'upload/' . $file_name;
move_uploaded_file($file_tmp, $file_destination);
In the above code snippet, I have used $_FILES array with the name of the input field that is “file” to get the name and temporary name of the uploaded file.
Check the scenario that cause the error:
Make sure you have created folder where you want to move your file.
Check for the folder permission, is it writable or not. Use chmod() to modify permission.
See if your target path URL is properly created or not. You can use dirname(__FILE__) to get the absolute path. To get current working directory, use getcwd().

$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . 'images/'. basename( $_FILES["profpic"]["name"]);
move_uploaded_file($_FILES['profpic']['tmp_name'], $target_path);
getcwd() : getting current working directory path from the root.
'images/' : is the directory where you want to save your file.

Related

How to upload files to specific subdirectory

I am working on a simple thing that uploads files using PHP.
My form:
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="file" name="file_upload">
<input type="submit" name="submit" value="Upload">
</form>
And PHP:
$id = '3';
if (isset($_POST['submit'])) {
$tmp_file = $_FILES['file_upload']['tmp_name'];
$file = basename($_FILES['file_upload']['name']);
$upload_dir = "uploads";
if (file_exists($upload_dir."/".$file)) {
die("File {$file} already exists in {$upload_dir} folder.");
}
if(move_uploaded_file($tmp_file, $upload_dir."/".$file)) {
$message = "File " . $file . " uploaded to " . $upload_dir;
echo $message;
} else {
# Code with message about error.
}
}
Files successfully uploads only in uploads folder. In that uploads folder, I have few other folders: 1, 2, 3 and so on.
My question: How to move files in a specific subfolder after upload? (Subfolder name — from variable id.) Thanks!
Efficient way to do this:
This method move file when it get uploaded.
if (!empty($post_array['IconURI'])) {
$IconURI_current_path = "./" . $post_array['IconURI'];
if (file_exists($IconURI_current_path)) {
// Desired folder structure
$structure = './uploads/' . $primary_key . "/";
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (is_dir($structure) || mkdir($structure, 0777, true)) {
$dir = './uploads/' . $primary_key . "/" . $post_array['IconURI'];
chmod("$IconURI_current_path", 0777);
if (copy("$IconURI_current_path", "$dir")) {
#unlink("$IconURI_current_path");
//rename IconURI from [ 9723d-632ac-e325b-db1b8-icon.jpg ]
$IconURI = "uploads/" . $primary_key . "/" . $post_array['IconURI'];
}
} else {
die('Failed to create folders...');
}
} else {
echo "Banner file does not exist";
}
}
the script also handle file permissions. some time due to directory or files permission file couldn't moved.
Can be used as callback function like in Grocery CRUD or other third party Plugins. i.e these plugins uploads files to their default directory and you some time need to move file to other specific directory.

Uploading files to the same directory as the script using php

Using move_uploaded_file("temp_location","new_location"), is there a way to upload files to the same directory as the file uploading script when specifying the "new_location" or does it always have to be uploaded in another specified folder within the script's directory?
It's possible, as long as you have the permission to write in that specific directory:
/* new_file can be any path ... */
$new_file = __DIR__ . '/' . $_FILES['file']['name'];
if ( is_writable(dirname($new_file)) ) {
move_upload_file( $_FILES['file']['tmp_name'], $new_file );
} else {
throw new Exception( 'File upload failed: Directory is not writable.' );
}
You can upload file in script directory as following code .
HTML code :-
<input type="file" name="file" id="file">
PHP code:-
move_uploaded_file($_FILES["file"]["tmp_name"], "". $_FILES["file"]["name"]);
But a problem in the case of permission.
You could use dirname and __FILE__ for that:
move_uploaded_file($tmpName, dirname(__FILE__) . '/' . $newName);

How to upload file into different directory based on url token value

This is my code for html
<form enctype="multipart/form-data" action="L.CoursePage.php?id=<?php echo $id;?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" /><br>
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" name="upasg">
</form>
This is my php code:
if(isset($_POST['upasg'])) {
//folder to save in
$targetPath = $id."/download/assignment";
if (!is_dir($targetPath)){
mkdir($targetPath);
}
$targetPath = $targetPath . basename($_FILES['uploadedfile']['name']);
$_FILES['uploadedfile']['tmp_name'];
if ($_FILES['uploadedfile']['size'] < 2000) {
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$targetPath)){
echo "The file ". basename($_FILES['uploadedfile']['name'])." has been uploaded.";
} else {
echo "There was an error uploading the file, please try again.";
}
} else {
echo "The file is too big";
}
}
?>
What I'm trying to do is to upload file into different directory when the pageid is different.
For example:
in /L.CoursePage.php?id=1, the file I trying to upload in this page should be save in the 1/download/assignment path.
And I get this error:
Warning: mkdir(): No such file or directory in D:\xampp\htdocs\xampp\foundation\L.CoursePage.php on line 148
Warning: move_uploaded_file(TTT1234/download/assignment1.txt): failed to open stream: No such file or directory in D:\xampp\htdocs\xampp\foundation\L.CoursePage.php on line 153
Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\phpBF13.tmp' to 'TTT1234/download/assignment1.txt' in D:\xampp\htdocs\xampp\foundation\L.CoursePage.php on line 153
There was an error uploading the file, please try again.
The error says that PHP does not recognize targetPath, because you forget the $ sign in mkdir(targetPath);
For the uploadedfile index, in your first code you say name="uploaded file" with a space.
These PHP errors are quite explicit :D
Looks like the problem is with construction of $targetPath. You set $targetPath to $id."/download/assignment";. And then you concatenate it with the name of the file:
$targetPath = $targetPath . basename($_FILES['uploadedfile']['name']);
But $targetPath doesn't have a trailing directory separator, so the concatenated string will look like /download/assignmentfilename. Use a directory separator:
$targetPath = $targetPath . '/' . basename($_FILES['uploadedfile']['name']);

Uploadify is not working

I am using uploadify to upload multiple files on my website, but it is not working properly. I have fix various things in it but it is not working properly. issue is that when i upload the file it will show me the loading bar and when it completes it disappear but when i check the destination the file is not present in it. Please help me. My code is given below:
index.php
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>'
},
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php'
});
});
</script>
uploadify.php
<?php
// Define a destination
$targetFolder = 'uploads/'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
?>
As said by some comments, when uploading using PHP, you need to give writing permissions to the upload directory. If you use filezilla, simply rightclick on the folder on the server, click fileattributes, and set it to, for example 775.
Had a similar problem just yesterday. My problem was that my upload_max_filesize, located in the php.ini, was set to 2M. I boosted it up to 4M and TADA, problem solved. If you do seem to be having the same issue, don't forget to restart your server. ;)

Possible Reasons Why a PHP File Upload Wouldn't Work

Here is the HTML:
<h1>Upload Custom Logo</h1>
<form action="settings.php" enctype="multipart/form-data" method="post">
<input type="file" name="Logo" />
<input type="submit" value="Upload" name="logoUpload" />
</form>
Here is the PHP:
<?php /* Handle Logo Upload */
if($_POST['logoUpload']) {
$target_path = "uploads/";
$Logo = $_FILES['Logo']['name'];
$target_path = $target_path . basename( $_FILES['Logo']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo '<div class="statusUpdate">The file '. basename( $_FILES['Logo']['name']).
' has been uploaded</div>';
}
} else{
echo '<div class="statusUpdate">There was an error uploading the file to: '.$target_path.', please try again! Error Code was: '.$_FILES['Logo']['error'].'</div>';
}
}
?>
It always goes to the "else" statement on that code, I have an uploads folder in the same directory as this php file set to 777 file permissions. The image I am test uploading is under 10KB in size. But the move_uploaded_file() always fails and it doesn't return any error message except for the custom error message made with the else statement.
You're referring to the file in the $_FILES array by two different names -
$Logo = $_FILES['Logo']['name'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
Which one is it? Logo or uploadedfile ?
You're probably referencing an array index which doesn't exist.
Possible reasons:
The uploading of the file failed in some way.
You don't have permission to move the file to the target path.
As PHP.NET says:
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
Reference: http://php.net/manual/en/function.move-uploaded-file.php

Categories