PHP Upload File AND Write TXT File - php

This SHD work ... no idea why.
When user submits form, uploads the file to ../images/ and writes that file name to a text file. It does not upload the file and it blanks out the txt file which I assume means the upload fails.
$img_name = $_FILES['avatar']['name'];
$upload_file = move_uploaded_file($_FILES['avatar']['tmp_name'], "../images/" . $img_name);
$log_avatar = fopen('../archive/avatar.txt', 'w+');
fwrite($log_avatar, $img_name);
fclose($log_avatar);
header("location:user.php");

to write the name of the uploaded file to text file use "a+" instead of "w+"
the difference between them is
"w+" opens the file for reading and writing and place the file pointer at the beginning of the file
"a+" opens the file for reading and writing and place the file pointer at the end of the file
$log_avatar = fopen('../archive/avatar.txt', 'a+');
also you can add line break using PHP_EOL
fwrite($log_avatar, $img_name.PHP_EOL);
that is what makes the text file get empty
about upload files there is nothing wrong in your code.
but i think you are have error in your html form because filename is blank
make sure you set the form enctype Attribute to "multipart/form-data"
<form method="POST" enctype="multipart/form-data" action="up.php">
and using the correct input name in your upload script

Related

how to clear .txt file contents without delete file in php

I want to clear .txt file contents; the file name is stored in the variable $data['soft_files'] which is taken by a button and sent to the controller from javascript.
$data['soft_files'] = $this->input->post('soft_files');
$file = FCPATH . "/software_files/$this->input->post('soft_files')";
file_put_contents ($file, "");

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.

Get file from temp after confirm with PHP/Laravel

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

Getting error when renaming file in PHP

I am uploading a file using PHP to a folder in my directory and am unable to rename it using the following code
$da = date("dmY");
$ja = $uid.$da;
$mukesh = $app.$ja;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['userfile'][$mukesh], $uploadpath));
Here's PHP's official document about how to handle uploads: http://www.php.net/manual/en/features.file-upload.post-method.php
The method move_uploaded_file() requires two parameters, a filename of the temp file, and a new location.
$tmp = $_FILES['userfile']['tmp_name']; // temp path
move_uploaded_file($tmp, $uploadpath . '/' . $mukesh);
You will need to name your input element userfile.
<input type="file" name="userfile" />
Based on code snippet provided, you can do following
move_uploaded_file ($_FILES["userfile"]["tmp_name"], $uploadpath);
When you upload a file, files will be store in upload location specified in php.ini using a temporary name. This file location with name can be accessed by $_FILES["userfile"]["tmp_name"]
Lets say you upload an image.if no error then
$uploads_dir = 'as per you defined';
$tmp_name = $_FILES["userfile"]["tmp_name"];
$name = 'custom_file_name.png';//$_FILES["userfile"]["name"];
move_uploaded_file($tmp_name, $uploads_dir."/".$name);
You are renaming the temp name of file ...
When you want to rename the change the name with which you want to store the file
$filename = time().$_FILES['userfile']['name'];
$upload_path = 'path_to_ur_upload_folder'.$filename;
move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path );
first param in move_upload_file is temporary name that will be used by stream while copying an d uploading .. the second parameter is path where your file will be saved (along with file name).. it is the second parameter which will help you in renaming of file which is being uploaded

Saving a PDF file using PHP

I have a problem with saving PDF files to folders on my server. The code worked at one time and now it doesn't. What I want it to do is to check if someone is trying to upload a PDF when a form is submitted, and if there is a PDF in the file field it uploads it and then saves the path to the mysql database. Code is below:
if (!empty($_FILES['pdf'])){
$idir = "../files/PDF/"; //my directory file is supposed to be saved in
$randomd=rand(0000000,9999999); //creates a random number as filename
$domain = "http://".$_SERVER['HTTP_HOST'];
$file_ext = strrchr($_FILES['pdf']['name'], '.'); grabs file extension. my code checked if the file was a pdf a different way and neither seems to work.
$destination=$randomd.$file_ext; //new filename
if ($file_ext=='pdf') {
move_uploaded_file($_FILES['pdf']['tmp_name'], "$idir" . $destination);
$pdf= $domain."/files/PDF/".$destination; } else { echo("File type not supported.");
mysql_query("UPDATE tbl_listings SET pdf='$pdf' WHERE listing_id='$lid'");
}
The if not empty does not work and it always tries to upload a file, but when I check the folder nothing is in there and it doesnt update the mysql.
$_FILES['pdf'] will never be empty(when the form has been submitted), no matter if a file has been selected or not, it will always return an array.
Check $_FILES['pdf']['error'] , it will be 4 when no file has been uploaded.

Categories