Move uploaded file function in php is not working - php

Following is my piece of code which moves file to particular directory.
foreach($files as $dir_file) //Getting Path of XML file
{
echo "\nDir Files: ".$dir_file."\n";
if($dir_file != "." && $dir_file != "..")
{
if(strpos($dir_file,'.xml'))
{
echo "\nXML file found\n";
$xmlPath=$path."/".$dir_file;
// return ReadXML($xmlPath);
}
if(strpos($dir_file,'.JPG'))
{
echo "\n FOund \n";
$ret=move_uploaded_file($dir_file, 'upload/'.$dir_file));
echo "\n retunr values: ".$ret;
}
}
I have checked all permission and it is 777. but move upload file function is not moving my file to particular directory. it is also not returning anything. What i am doing wrong?

If you are to move files from one directory to another, you should use copy() function.
This is the example code:
$source = "YOUR_SOURCE_DIRECTORY/";
$destination = "YOUR_DESTINATION_DIRECTORY/";
foreach ($files as $file) {
if (in_array($file, array(".","..")))
continue;
//If file is copied successfully then mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
//If you want to delete the copied files then include these lines
//Delete all successfully copied files
foreach($delete as $file) {
unlink($file);
}

move_uploaded_file
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
(Emphasis mine.) You can use move_uploaded_file only to move files which have been uploaded, where "uploaded" means "PHP has received the file in the current request and the file is currently in the $_FILES super global". Any other file is not movable by move_uploaded_file. This is exactly on purpose, move_uploaded_file is supposed to protect you from yourself and make sure you're only moving files uploaded by the user.
If you want to move any other file which has not just been uploaded via HTTP POST, use copy or rename.

Related

Remove "Attachments" folder after PHPMailer email is sent

I've got a web form which has a unique upload folder for each user (using their PHP session_id() as the folder name) which works well. When the form is submitted (after error checking) PHPMailer is used to send the email and the attachments. This is also working well. However, after the email is sent, I would like to remove the uploads from the folder and then the folder itself (sort of a self-cleanup!) The files are removed as expected but the folder remains (albeit empty). I wonder if the folder is somehow "still in use" so doesn't get deleted or something similar? This is the code:
// Empty the contents of the upload folder
if (is_dir($dir)) { // Target directory ($dir) is set above in photos POST section
// Check for any files inside the directory
$files = glob($dir.'/*'); // Get all file names
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
// Remove the upload folder
rmdir($dir); //NOT WORKING? NEEDS SOME TROUBLESHOOTING...
}
Any other ideas on why this folder is remaining?
Ben
I would guess that your folders might contain hidden files (starting with .) which the default glob pattern won't match, so try this:
$files = glob($dir . '/{,.}*'); // Get all file names including hidden ones
foreach($files as $file) { // Iterate through the files
if(is_file($file)) { // Check its a file
unlink($file); // Delete the file
}
}
Also check the return value on both unlink and rmdir so you can see exactly where it's failing.
Turns out after much testing that the problem was not actually with rmdir at all! My web form uses a Dropzone for photo uploads to a unique folder for each user using their php session_id() and this folder is supposed to be created when they add a photo to Dropzone (if it doesn’t already exist). Problem was I’d put the folder creation code outside of the actual upload script so the folder was in fact being deleted but them instantly created again when the form submitted and the page reloads! Sorry about that but thanks for all your help. :)

FTP Delete All Folders in Target Directory

What i am trying to do is to delete all files in my target servers folder, the folder all the files are in is: "/public_html/" this directory contains all the target files, i don't want to delete this folder as it must remain the intact, just everything inside.
function ftpDelete($conn, $directory) {
echo "<pre><b>FTP Files on Server:</b>\n";
$filelist = ftp_nlist($conn, $directory);
foreach($filelist as $file) {
// Do not show "." or ".."
if ($file != "." && $file != "..") {
ftp_delete($conn, $directory);
echo $file . "\n";
}
}
echo "</pre>";
}
// Run delete functions ...
ftpDelete($conn, "/public_html/");
// Files out that is still on the server ...
FTP Folders on Server:
/public_html/vendor
/public_html/stats
/public_html/icon
/public_html/images
This code so far will delete all files that is the "public_html" directory, but not any folders, i know from reading the folders need to be empty first, i'm not sure the best way to handle these folders, i didn't see a command that would delete the target folders and it's contents, any help would be appreciated.
You need to append the filename after the directory:
ftp_delete($conn, "$directory/$file");

Why is move_uploaded_file not working?

Whenever I try to move a file it does not work and shows "Image file not uploaded"... I just want to know where the error is...
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if( move_uploaded_file( $target, $destination ) ) {
echo "Image file is successfully loaded";
} else {
echo "Image file not uploaded.";
}
I have checked error log (tail -f /var/log/apache2/error.log) but found nothing.
target and destination both directories have 777 permissions.
Can someone tell me that how to find out the error. Any idea ?
If you are not using HTTP POST upload method then you can use rename()
rename($target, $destination);
Has the file been uploaded in the current request?
move_uploaded_file will refuse to move files that are not uploads. (i.e. $target must equal $_FILES[$field_name]['tmp_name']
If it has been uploaded previously, move_uploaded_file will refuse to work (if it is even still there - PHP will delete it if you don't handle the file on that upload if I remember correctly)
If it is in fact not a file that has been uploaded with this request you'll want to use rename
move_uploaded_file() only works on http post files. http://php.net/manual/en/function.move-uploaded-file.php
to move a file already on the server, you will have to copy the file and unlink the old file
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if (copy($target, $destination)) {
unlink($target);
} else {
echo "Unable to copy $target to $destination.";
}

PHP move_uploaded_file to directory and create file

I have a script that uploads a file and then moves it to a directory. However the script does not know the name of the file its creating because it hasn't created it yet and cannot find the file to update.
So either one requires a way to make the file first or there is another way of doing this. The code.
<?php
$filename = '/home/divethe1/public_html/update/z-images/admin/upload/test/';
if ($_FILES['thumbfile']['error'] === UPLOAD_ERR_OK) {
$info = getimagesize($_FILES['thumbfile']['tmp_name']);
if (($info[2] !== IMG_GIF) && ($info[2] !== IMG_JPEG)) {
die("not a gif/jpg");
}
if (filesize($_FILES['thumbfile']['tmp_name']) > 100000) {
die("larger than 100000");
}
move_uploaded_file($_FILES['thumbfile']['tmp_name'], $filename . $_FILES['thumbfile']['name']);
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Archiving"</script>Archiving';
}
else
{
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Invalid File Format"</script>Invalid File Format';
}
?>
Any ideas?
I think you're misunderstanding how move_uploaded_file() works. It doesn't create a file for you. It:
Takes the temporary filethat PHP created for you to hold the upload (the filename/path for which is in $_FILES['thumbfile']['tmp_name'])
does a few security checks to make sure no one's tampered with the file between the time the upload completed and the move_uploaded_file call was issued
then MOVES the file to the location you specify.
It doesn't handle the upload, or receive the file - by the time your upload-handling script gets fired up, the upload has already been completed and the file is waiting in that tmp_name location.
If the move can't be completed for any reason, move_uploaded_file() returns false. It won't warn you if you're overwriting a file in the destination, on the assumption that you know what you're doing.
My mistake. I left the directory test in place. That should have gone. Thanks anyway for all help.

Why is my upload-of-a-file code putting 2 sets of files into my directory? (PHP)

When I upload a file using this code, it puts a copy of the file in the "uploads" folder(which is what I want) but it also puts a copy in my root. I only want the files going to the uploads folder.
define ('GW_UPLOADPATH', 'uploads/');
$upfile= GW_UPLOADPATH . $_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
if(!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) //this is saying if the file isn't moved to $upfile.
{
echo 'Problem: could not move file to destination directory';
exit;
}
}
else
{
echo 'Problem: Possible file upload attack. Filename: '; //this could be an attack b/c it might be from localhost.
echo $_FILES['userfile']['name'];
exit;
}
echo 'File uploaded successfully<br><br>';
What would be your temporary dir? Is it possible that somehow the uploaded file lands in the root but PHP can not delete it? Figuring this out requires a lot more knowledge about your setup.

Categories