I have an application which uploads data from a csv file and this is working fine. It would be useful, but not essential, if I could limit the dialog window to only show csv files, and if possible a file template say 'abc*.csv'.
The attached image shows an example of a dialog box which will only allow files that start with abc*.csv
Example of csv image dialog box
Thanks
Harry
It depends on how you're handling the uploads.
You can either use plain HTML to filter the .csv extension or handle it using PHP, or both.
Using HTML:
<input type="file" name="upload" accept=".csv">
Using PHP:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if( $ext !== 'csv' ) {
echo 'Invalid extension.';
}
Note that this only verifies the extension and not the actual filetype.
Also the accept attribute of the <input type="file"> does indeed provider a filter in the file select dialog.
Related
I want to use a text-box, insert my file address is in the Desktop, and then upload it in the server, what should I do?
Is it because you dont like file uploader object how it looks?
If yes I suggest you to make it hidden but in background use its fuctionality.
Show file selected information in a textbox but keep the file into hidden file uploder object.
Another method to post files like audio and jpeg to server is to use Base64 format . Its consider as string but not recommanded for large files.
Then you need a backend function to save data into file object or simply insert data into database.
Do it this way:
$file_url= $_POST['file']; //Path of file to be uploaded
if file_exists($file_url):
$fh= fopen("NewfileName", a+);
fwrite($fh, file_get_contents($file_url));
fclose($fh);
endif;
Am planning to develop a image upload API which need to upload a image to the server location as part of my project. (The usage will be to upload user pics and avatar using an android app)
The API which should be similar to Imgur API in which we can use a post request to upload a binary image to the server.
I searched through multiple questions, all am getting is using multi part request which requires html form submitting. Since my aim is to create a API, html form submitting will be impossible.
Anyway am submitting a sample code which uses html form to upload an image. Can someone show to how can I modify the script to meet my requirement?
<html>
<body>
<form action="photo.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP code
<?php
$allow = array("jpg", "jpeg", "gif", "png");
$todir = 'uploads/';
if (!!$_FILES['file']['tmp_name'] ) // is the file uploaded yet?
{
$info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file
if ( in_array( end($info), $allow) ) // is this file allowed
{
if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
{
// the file has been moved correctly
}
}
else
{
// error this file ext is not allowed
}
}
?>
Some remarks about your server-side code in no particular order:
As you can read at Handling file uploads, the correct way to verify an upload is comparing the ['error'] subkey with UPLOAD_ERR_OK (codes explained here). Don't use ['tmp_name'] for that.
Don't let the end user pick the actual file name on your server. You'd better generate a unique name yourself and keep the display name elsewhere (e.g. a database)
The recommended way to determine a file extension is pathinfo:
pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)
File extension provided by the user is not a reliable way to determine file type. For pictures, the getimagesize function is often used.
multi part request which requires html form submitting
That's wrong. It requires a properly formatted request (headers and body), period. In fact, the server has no way to know what piece of software was used to generate the request—or if you just typed the bytes yourself in a console ;-)
I'm trying to build a simple image uploader using PHP. I do know how to code it, however I have a few concerns..
My question I had is the following: Is saving files which users send safe to save as the original file? With this I mean: Will I not get any vulnerabilities when I'm saving a file send by an user?
Let's say my PHP script does this: It retrieves the POST data, which includes a file send by a person on my website. Is it save to just move the file over to a directory, with original name, content, etcetera? Is there any harm in doing this, or should I rename these files to a random string?
If this isn't a safe way to do this, then what is? How would I verify the send content isn't harmful?
There are always vulnerabilities in storing and providing content provided by a client.
This blog post gives a good description of the vulnerabilities you could face, how they're exploited and how to protect against them. I suggest you use this as a reference: http://blog.insicdesigns.com/2009/01/secure-file-upload-in-php-web-applications/
Make sure you only process files with the correct ending. Image files are never executed by a webserver, but .php files are for example. So make sure the users don't upload any file that can be executed.
I'm not aware of file names that are harmful. For the content this is difficult to answer. I remember an attack vector with modified TIFF images on windows and one in libjpeg on *nix Systems. However you probably won't be able to find these things without completely decoding the image.
Here's another approach: use this (https://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/) very short Image Uploader, by Paul Rouget, based on Imgur.com's API.
Instead of uploading directly to your database, let imgur do all the security and validation, then if you need to, link to or download the (safe) image via Imgur.
It's free for non-commercial and very cheap for commercial.
Basically, you can use imgur's API to safely upload images from your HTML page, with no server side code at all
Here's a live demo: (http://paulrouget.com/miniuploader/)
I would say 100% user upload file are NOT 100% SAFE
JPEG files can contain arbitrary data in them in addition to the actual image data; it's part of the spec. Thus, merely checking if an image is a valid JPEG does not mean that the file is necessarily completely harmless.
File upload without validation
HTML Form:
<form enctype="multipart/form-data" action="uploader.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" /> </form>
PHP Code:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file " . basename($_FILES['uploadedfile']['name']) . " has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>
Define a .htaccess file that will only allow access to files with
allowed extensions.
Do not place the .htaccess file in the same directory where the
uploaded files will be stored. It should be placed in the parent
directory.
A typical .htaccess which allows only gif, jpg, jpeg and png files
should include the following (adapt it for your own need). This will
also prevent double extension attacks.
deny from all
<Files ~ “^w+.(gif|jpe?g|png)$”>
order deny,allow
allow from all
</Files>
If possible, upload the files in a directory outside the server root.
Prevent overwriting of existing files (to prevent the .htaccess
overwrite attack).
Create a list of accepted mime-types (map extensions from these mime types).
Generate a random file name and add the previously generated extension.
Don’t rely on client-side validation only, since it is not enough. Ideally one should have both server-side and client-side validation implemented.
I have a scenario in which I need to count the number of words in file.
I have different file formats such as .doc, .xls, .pdf and .txt. I am using this method for counting:
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="docfile" />
<input type="submit" name="submit" />
</form>
<?php
if(isset($_POST['submit'])){
$file = $_FILES['docfile']['name'];
$file = str_replace(" ","_",$file);
//$file = file_get_contents($file);
$ext = pathinfo($file, PATHINFO_EXTENSION);
move_uploaded_file($_FILES['docfile']['tmp_name'],"uploads/".$file);
if($ext == "txt" || $ext == "pdf" || $ext == "doc" || $ext == "docx"){
$file = file_get_contents("uploads/".$file);
echo str_word_count($file);
}
}
?>
But it is not returning the correct word count for the file.
Apache Tika is a Java framework that is capable of recognizing a lot of document types and extracting meta information from them. It is is capable of ascertaining word counts for a lot of the document types it recognizes.
I mention this Java framework for your PHP question because there is a PHP wrapper for it called PhpTikaWrapper. I have never used the wrapper but Apache Tika can extract the meta information you are after so, investigating the wrapper may prove beneficial.
You've got a difficult task there. .doc .pdf and .xls are not simply readable. To test this try opening a pdf with a basic text editor like notepad or gedit. You will see what appears to be gibberish. This is the same thing PHP sees when you read a file's contents.
.xls and .doc can probably be parsed with PHPWord and PHPExcel from PHPOffice. You will need to look in to these libraries. I don't know anything for PDFs but there's probably something.
I would suggest writing a series of classes that all implement a similar interface so you can switch them out depending on the extension.
I've been working on a general purpose class that incorporates various methods found around the web and on Stack Overflow that provides word, line and page counts for doc, docx, pdf and txt files. I hope it's of use to people. If anyone can get RTF working with it I'd love a pull request! https://github.com/joeblurton/doccounter
I want to make a file upload form.
But my confusion is that when i put file element in html its allow all types of files to select.
I want that browse button will only allow the images to select from the file system.
Actually it should display only images of the file system.
Thanks in advance.
Attribute "accept" with list of MIME types, does not supported by any browser.
<input type="file" accept="image/gif, image/jpeg" />
You can sort out file extension with JS, or try http://swfupload.org/
Uploadify will work for you. It allows you to specify which file types are visible for the user to choose. It can also allow the user to upload multiple files at once if you need them to. All files that are uploaded are showed in a queue with progress bars and are removed from the queue when they are finished uploading. I highly recommend it.
Generally speaking, file uploads should be validated server-side as the 'accept' attribute is not fully supported by the major browsers. Example below:
$accept = array('jpg','png','gif','bmp');
$extension = substr($_FILES['file']['name'],strrpos($_FILES['file']['name'],'.')+1);
if(!in_array($extension,$accept)){
// If the extension is not allowed show an error, else, the file type is valid
echo 'Not a valid file extension';
}