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.
Related
I'm uploading a csv file to my php server with this form:
<form action="importCSV.php" method="post" enctype="multipart/form-data">
<br>Select file: <input type="file" name="file">
<br><input type="submit" name="import" value="Import file">
</form>
And what I want to do with that file is to add its content to a table in my mysql server.
$url=$_FILES['file']['tmp_name'];
$con = new mysqli(HOST, US, PW, BBDD);
$sql="load data local infile '" . $url. " into table users fields terminated by ':'";
$con->query($sql);
$con->close();
The problem is that in the "tmp" folder of the php server doesn't appear the csv file, but in this line $url=$_FILES['file']['tmp_name'] $url has a real url with a tmp_name. I don't understand what's happening there: I have the url with the tmp_name of the file but it actually doesn't exists?
I have checked the php.ini file and this are the values for the file uploads:
file_uploads=On
upload_tmp_dir="C:\xampp\tmp"
upload_max_filesize=2M
max_file_uploads=20
I'm not worried about the "upload_max_filesize", the file I'm trying to upload has a size of only 56 bytes.
Please, any ideas?
I can't believe this...
It seems that the mysql server doesn't understand this character \. It's only a problem of compatibility between operative systems.
The solution is only to replace the character: $url= str_replace("\\", "/", $url).
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.
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!
if(isset($_POST['submit'])){
if(!empty($_FILES['files']['name'])){
$Zip = new ZipArchive();
$Zip->open('uploads.zip', ZIPARCHIVE::CREATE);
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
$Zip->close();
}
else {
echo "no files selected";
}
}
What is wrong here ? I have just watched a tutorial of creating archives and adding files in it but it is not working ...I am using php 5.4 . It is not even giving me any error. Can any one please guide me what i am doing wrong here.
Below is the form
<form action="" method="POST" enctype="multipart/form-data">
<label>Select files to upload</label>
<input type="file" name="files">
<input type="submit" name="submit" value="Add to archieve">
</form>
These lines don't make any sense
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
At that point in the code you posted, no uploaded files have been moved to a uploads/ directory, and looping though the $_FILES["files"] element - which is an associative array of various values, only one of which is the actual file name - and adding each value to the ZIP as a file, is nonsensical. - You should read the PHP docs relating to file uploading. It's clear you don't really know how PHP handles file uploads yet, which you should learn before attempting things like this.
One solution would be to move the uploaded file to the uploads/ directory using move_uploaded_file, but seeing as you are only really using the file there to add it to the archive, that step is pretty redundant; you can just add it directly from the temp location. First you need to verify it, though, which you can do with the is_uploaded_file function.
// Make sure the file is valid. (Security!)
if (is_uploaded_file($_FILES["files"]["tmp_name"])) {
// Add the file to the archive directly from it's
// temporary location. Pass the real name of the file
// as the second param, or the temporary name will be
// the one used inside the archive.
$Zip->addFile($_FILES["files"]["tmp_name"], $_FILES["files"]["name"]);
$Zip->close();
// Remove the temporary file. Always a good move when
// uploaded files are not moved to a new location.
// Make sure this happens AFTER the archive is closed.
unlink($_FILES["files"]["tmp_name"]);
}
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.