Get file from temp after confirm with PHP/Laravel - php

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

Related

hello I wanna use php_move_upload_file in order to move image from my temp folder to a permanent folder

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).

upload a file to a specific folder php

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.

php move_uploaded_file not creating file

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.');
}

file put contents how to set a path

I am using file put contents and set a file name but file saved on the directory where the script was written. How to do to set the full path to save to disc or desktop. Something like browse window and save path.
$fileName = 'etykieta_' . $package_no . '.' . $xml->label->format;
file_put_contents($fileName, base64_decode($xml->label->base64));
And i want to set a file path in a window.

$_FILES["file"]["tmp_name"]

I used a file upload form to upload files to my server. Then I echo $_FILES["file"]["tmp_name"] but it returns to me a location that does not seem to exist. eg /tmp/phpBparj4 is the output but there is no such file/folder in my /tmp folder. I have also checked for the appropriate permissions for the folder
My actual concern is move_uploaded_file($_FILES["file"]["tmp_name"],$target); which is not moving the uploaded file to the target location. I have also tried move_uploaded_file($_FILES["file"]["tmp_name"].$file_name,$target);
I am not sure if I understand right but why can't you specify the file folder location? i.e."
//set the right path from the server perspective
$article_file_path = $_SERVER['DOCUMENT_ROOT'];
// you should check for the file if it is/ or not already there (something like this)
if (!file_exists($article_file_path ."/your_folder/file_subfolder/". $_FILES["my_file"]["name"]))
{ do something.....
// then make your script upload the file exactly where you want it
move_uploaded_file($_FILES["my_file"]["tmp_name"],
$article_file_path ."/your_folder/file_subfolder/".$_FILES["my_file"]["name"]);
// and the download link to the uploaded file would be something like this:
echo "http://". $_SERVER["HTTP_HOST"] . "/files-article/".$_FILES["my_file"]["name"]";

Categories