My purpose is uploading a remote file create from my PC to specific folder, but I don't know whats wrong with my code below. It uploads the file with the name and the .jpg extension, but it is not moving the file to the specified folder.
if(isset($_POST["image"])){
define("SITE_NAME","project_name/"); //constant for project name
define("SITE_PATH",$_SERVER['DOCUMENT_ROOT']."/".SITE_NAME); //constant for project base directory
define("IMAGES_URL",SITE_URL."images/"); //constant for image directory
$upload_base_dir=IMAGES_URL;
$upload_time_dir=date('Y')."/".date('m')."/".date('d')."/"; // setup directory name
$upload_dir = $upload_base_dir.$upload_time_dir;
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true); //create directory if not exist
}
$input = $_POST["image"];
$file = fopen(time()."image.jpg", 'wb');
fwrite($file, $input);
//$image_name=basename($_FILES['image']['name']);
$image=time().'_'.$image_name;
move_uploaded_file($file,$upload_dir.$image);
fclose($file);
}
Any suggestions? Thank you in advance.
move_uploaded_file($file,$upload_dir.$image) will only work for items within temp, that are accessable via $_FILES superglobal. If you are sending your file as a strieam within post, that wont work.
1) If file is a form upload make sure form is a multipart and access your file via $_FILES superglobal
move_uploaded_file($_FILES['userfile']['tmp_name'], $yourDirectory.$yourFilename);
2) If you post the file as a stream via post (keep in mind this will only work for small files as large ones will exceed request limit). Save the file directly to it's destiantion using fopen or to move it after you created it use rename() - http://php.net/manual/en/function.rename.php
rename($currentFilePath, $newFilePath)
P.S. sending files as post streams is a very very bad idea.
Related
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. :)
hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).
I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}
I have a form with a file to uplaod. All works find. But I don't want to move the file directly into a folder.
After submit I show a confirm page and there I show the uploaded file with
header('Content-Type: image/x-png');
$file = file_get_contents(\Illuminate\Support\Facades\Input::file('restImg'));
$imgType = \Illuminate\Support\Facades\Input::file('restImg')->guessClientExtension();
echo sprintf('<img src="data:image/png;base64,%s" style="max-height: 200px"/>', base64_encode($file));
This works fine. After the confirmation I like to move the file to a folder. How can I move the file after the confirmation? The Input::get('file') is not available anymore.
You will have to store the file in the initial upload somewhere temporarily other than the default tmp directory.
The documentation for PHP file uploads says:
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed
This means that moving onto the next request, the file will no longer be available.
Instead, move it to your own custom temp directory or rename it to something special, then keep the filename in the $_SESSION to persist it to the next request.
For Laravel, this should mean putting it in the /storage directory with something like this:
// Get the uploaded file
$file = app('request')->file('myfile');
// Build the new destination
$destination = storage_path() . DIRECTORY_SEPARATOR . 'myfolder';
// Make a semi-random file name to try to avoid conflicts (you can tweak this)
$extension = $file->getClientOriginalExtension();
$newFilename = md5($file->getClientOriginalName() . microtime()).'.'.$extension;
// Move the tmp file to new destination
app('request')->file('myfile')->move($destination, $newFilename);
// Remember the last uploaded file path at new destination
app('session')->put('uploaded_file', $destination.DIRECTORY_SEPARATOR.$newFilename);
Just remember to unlink() the file after the second request or do something else with it, or that folder will fill up fast.
Additional Reference:
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html
I'm trying to push a file to a Amazon s3 filebucket.
I'm posting the file through an html form.
I try to generate a path to the file like this($file is a part of a foreach, because i need to support multiple files in a form-submit.)
$file['tmp_name'].'/'.$file['name'];
this outputs a filepath like this
/Applications/MAMP/tmp/php/phpZDcVQv/pdf.pdf
/Applications/MAMP/tmp/php/ exists, but nothing is inside it. I have set access read and write for everyone to that folder.
I use a library to post the images to Amazon: https://github.com/tpyo/amazon-s3-php-class It also complains that the filepath i have provided doesn't exist. It's running a check like:
if (!file_exists($file) || !is_file($file) || !is_readable($file))
How come the files aren't added?
Am I referencing the wrong folder? The file with the code is in /web/projectname/
Someone on the internet said something unclear about php removing the temp-file directly. Is this after the response has been run? Do I need to address this in some way?
The most simple code that generates the problem:
foreach ($_FILES as $file) {
$filepath = $file['tmp_name'].'/'.$file['name'];
if(file_exists($filepath)){
echo 'true <br />';
}else{
echo 'false <br />';
}
}
This echo:es false even if files have been uploaded.
$filepath contains the path i described above.
as the manual states:
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
and
$_FILES['userfile']['name']
The original name of the file on the client machine.
this means that file_exists($file['tmp_name']) should be true.
The path $file['tmp_name'].'/'.$file['name'] is bogus, since $file['name'] is there only for informing you of the original name, but this name is not used while saving the uploaded file on the server.
So in your example /Applications/MAMP/tmp/php/phpZDcVQv is actually the uploaded file.