PHP Temporary File Does Not Exist - php

I'm working on a Wordpress plugin that has its own file upload form to import data. I have a really basic form upload script. I want to keep the files in the temporary directory, I won't be storing the uploaded files permanently.
Here is the upload script:
<?php
echo $_FILES['file']['tmp_name'];
I get a temporary location, but the file does not exist on my file system. I'm on Fedora 21.
The HTML form looks like this:
<form action=<?php echo plugins_url() . '/upload.php'; ?> method='post' enctype="multipart/form-data">
<h4>Data Import</h4>
<fieldset>
File: <input type='file' title='spreadsheet' name='file'><br>
<input type='submit' name='Import' value='Import'>
</fieldset>
</form>

Try this instead:
$uploaddir = './temporaryfolder/'; //give this dir write permissions
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
//now you can get the filename
$file = basename($uploadfile);
echo "File <b>$file</b> is valid, and was successfully uploaded.\n";
}

It is called temporary location, because files exist there only temporary. You have to relocate them somewhere else to be able to "fetch" them.
However you mentioned you don't want to keep those files - therefore I suggest you to write yourself an algorithm that will take care of files after you don't need them anymore. May be based on age of the file or something else, you decide.
How to relocate those files after upload is mentioned in Pedro Lobito's answer.

Related

PHP upload files to remote server

I am completely a novice in all this ...
I have created a Social Networking project in which there is a module which allows user to upload photos..
I have hosted this project in my college server
I access that server using bitvise client with my server credentials.
My problem is i don't know how to setup upload mechanism for remote server ... In my localhost i simply use
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
function but i don't know how to do this for remote server ...
I tried FTP by looking at some tutorials but that didn't worked for me.
In my project structure there is a directory
users/user_id (diff for all users)/photos
here i want to place the uploaded files....
A proper description with example and proper functioning might be very helpful for me.... Thank you
EDIT:
Below is my code.
Photos.php
<form class="input-group-btn" method="post" action="editPhotos.php"enctype="multipart/form-data" id="myForm">
<input type="file" name="file" id="imgInp">
<button type="submit" class="btn btn-primary" name="form-submit">Done</button>
</form>
editPhotos.php
if( isset($_POST['form-submit']) ){
$target_file = "users/".$email."/pictures/Photos/" . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$img =str_replace(" ", "",basename($_FILES["file"]["name"]));
rename($target_file, "users/".$email."/pictures/Photos/".$img);
header('Refresh: 1; url=Photos.php?user='.$email);
}
Small tutorial how to upload file.
For sure, you need correct encryption and file's type in your form (ommited other fields, to clear example):
form.html
< form action="upload.php" method="post" enctype="multipart/form-data">< /form>
< input name="test" type=file>
upload.php
In $_FILES you have all data of uploaded file. In given example, we have field named test.
Advice, to always first check error $_FILES['test']['error'] - the values you can find in here.
If this is correct, then prepare upload path. Some advices:
remember that if you use original filename ($_FILES['test']['name']), then is User upload second file, with same name, you will need overwrite file or ignore upload. Other way, is to save data to database and generate temporary name form him.
destination path(target_file) - regardless if upload folder is in the same catalog, you should always use global path, as good practice. You can use DIR for that.
don't use in path data, like email - is you have project, and want give opportunity to change email in configuration, what you will do with files? Better save user to Database and use his ID as key.
If you have path, then you simply need only use of move_uploaded_file, but remember to check result, as it not always will return true. You can have error, when you don't have permissions to destination folder (you'll need debug this).
I see that you, first upload file, then rename (then you should check, if rename was success). Don't extends this process, if it not necessary. Upload file for final path and name.
Example of code (I this rattle off)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$fileName = basename($_FILES["file"]["name"]);
$fileName = str_replace(" ", "", $fileName);
$target_file = sprintf(__DIR__ . "/users/%s/pictures/Photos/%s", $email, $fileName);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// File was uploaded
header('Refresh: 1; url=Photos.php?user=' . $email);
} else {
// File was not uploaded;
throw new \Exception('File was not uploaded. Check warnings.');
}
}
Used other method to check, if this is POST
use method sprintf, for better code quality
checked effect of move_uploaded_file
use global path for destination file
Below code is risky in live environment, please use cautiously
Use a relative path to the uploads folder. For example, if your uploads folder is placed outside your current folder. Then
$PATH = '/absolute/example/path/to/uploads';//from config file
$target_file = "$PATH/file_name";
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
The above code will work both in local and remote server.
Other checks are below:
Check for errors while uploading file in server
To enable error handling use below code in your upload logic:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Another important note is to make uploads folder writable otherwise file upload wont work.

Getting file name and file directory in PHP application by selecting file

I'm currently making a PHP application, where I want to insert data from a excel sheet in a MySQL database. I've done that so far, but the problem now is, that the excel file needs to be in the root directory. What I'm looking for is a button where I can browse the file, and from which i get the name and the directory. Any suggestions?
currently I just use $fileName="gefertigt.xlsx";
I tried it with JavaScript (from this tutorial), but since I'm a beginner it's to difficult for me.
The PHP filesystem has two functions, basename() and dirname(), which give the filename and directory, respectively. Thus your answer is:
function get_name_and_directory($file) {
return array(
'name' => basename($file),
'directory' => dirname($file)
);
}
So I found a good solution for my problem, which is quiet easier than I thought. Instead of getting the directory of the file, I uploaded the file to a folder called "uploads" in my root directory. Since i knew that the file(which will always be an .xlsx file) will always be the same, but always with new content, it replaces the current file in the folder uploads with the upladed file.
code in html:
<form action="dbconnection.php" method="post" enctype="multipart/form-data">
Datei auswaehlen
<input type="file" name="dateiHochladen" id="dateiHochladen">
<input type="submit" value="Hochladen" name="submit">
</form>
code in php:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["dateiHochladen"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["dateiHochladen"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["dateiHochladen"]["name"]). " wurde hochgeladen.";
} else {
echo "Fehler beim hochladen.";
}

How PHP uploading Documents Works with posting document on the same page of Website?

I have been playing with various php upload examples to get a feel of how it works.
Before my database is in place, I want to understand why when I click my "post comment" button on my form that it goes to another page showing my whole php code. (is this due to database not made yet?)
I also think that I am not understanding the line of code: "$upload_path ="
I put the directory path of the folder containing my text document. From what I have been reading it said it has to be a directory and usually only has examples of just "\files\" or "\uploads\" which doesn't make sense to me.
Also what does:
$filename . '" title="Your File">here</a>'; // It worked.
line of code mean or does?
I want my upload to post to my website. In other words, click upload button and the document displays below the form on the same page.
I have a html form inside a html document and then I have a separate php document.
HTML:
<form id="comments" action="upload.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment">
<br>
Text Document: <input type="file" name="documentfile" />
<br>
<input type="submit" name="submit" value="Post comment" class="button">
</form>
PHP:
<?php
$allowed_filetypes = array('.text'); // types of files to use
$max_size = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = '\\ps....\ps.....\w...\Data\Aly...\HTML\TechSite - Copy\TechSite - Copy\files';
$filename = $_FILES['documentfile']['name']; // Get the name of the file and extension.
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get file extension
// Check if the filetype is allowed, if not tell user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Check filesize, if too large tell user.
if(filesize($_FILES['documentfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to path, if not tell user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['documentfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file <a href="' . $upload_path .
$filename . '" title="Your File">here</a>'; // It worked.
else
echo 'There was an error during the file upload. Please try again.';
?>
Once again: I played with examples I found for the php file because I am learning as I go with it. Please let me know if there is something in the php file that doesn't make sense and explain if possible. I'm wanting to understand if my php will be ok once my database is in place. I'd appreciate it!

Why isn't uploaded file saving in directory

I'm having users upload .xls, .xlsx, and .csv files to my website. From there I want to save them to the folder /upload/ in the same directory as the handler. I also want the name to remain constant. I have developed a code from what I have seen across the internet. Upon submission, the page turns white and no file is uploaded to the folder.
Form:
<form name="file" enctype="multipart/form-data" action="update_handler.php" method="post" >
<b>Accepted File Extensions: .csv .xls </b><br>
Please save your excel table as one of the <br>accepted file extensions prior to uploading.
<br><br>
<u>Upload File:</u> <input type="file" name="file"><br>
<input type="submit" value="Submit">
</form>
Handler:
<?php
$uploadDir = '/upload/';
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
?>
You named your form file <form name="file"
Where it should be for your input <input type="file" name="file"> <= which am sure read something else, since it was edited. Both form and the input hold the same named attribute. Remove the one for the form or give it another name if it is required for something else.
Also, David pointed out another issue which I did think of earlier, but failed to mention after. Since I took your comment about the "face palm" had fixed everything. I would've commented, but did not.
I was going to suggest that actually, about your use of /upload/ instead of upload/ if running your script from the root, but failed to mention it earlier.
David seems to have deleted his answer.
Plus; you may need to use ../upload/ or something similar, depending on the script's execution location and make sure proper write permissions are set.

PHP error uploading file

Okay, so I set up an upload engine for a website so that an authenticated user can upload a audio file (a key) for a song in the library, but I come across this strange problem when I try to upload any file over 5MB.
I set my php.ini max filesize to 50MB by the way
Everything uploads properly, but there is no data associated with the file on the other end.
HTML CODE:
<form action="keyUpload.php?id=<?php echo $id;?>" method="post" enctype="multipart/form-data">
<p style="color:#fff;font-size:30px;font-family:Times">
Add a new Key:<br/><input name="uploaded" type="file" id="file"><br />
<input type="text" name="kname" id="kname" value placeholder="Key Name (Ex. Demo, A#, etc.)" style="width:300px;"><br/>
<button class="button">Upload File</button><br/>
<span style="font-size:12px;">*Max Filesize is 50 MB*</span>
</p>
</form>
PHP CODE:
<?php
$id=$_GET["id"];
$name=$_POST["kname"];
$name = str_replace(" ","%20",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
Both $filename and $ext are empty variables when I upload a file larger than 5 MB. In all other cases, this engine works perfectly.
When echoed, simply nothing happens, so obviously the engine will not save the file if it doesn't exist. What's going on?
var_dump:
array(0) { }
Thanks for all your help!
Check for upload errors:
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['uploaded']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
As well, do NOT use filenames to validate the uploads. It is beyond trivial for a malicious user to fake a filename and upload malicious files, eg.
ren nastyvirus.exe good_tune.mp3
And don't use string operations on filenames. There's a whole whack of PHP functions for filename manipulation, e.g. http://php.net/basename
Set max_post_size in php.ini as well.

Categories