Validate the excel sheet - php

I have used the PHP method <form action="upload_file.php" method="post" enctype="multipart/form-data"> for uploading the excel sheets. Now I want to validate the excel sheet.
Validation:
If the sheet contain image instead of text I need to give an error to the user. Is it possible to validate the sheet's content without opening the sheet manually?

If you intend to use the data from the Excel file, you would have to parse and read it. If you can parse it as an Excel file, then its probably Excel, then you can safely rely on a php library like PHPExcel.
On the other hand, if you don't plan on using the data from the excel file, I personnally think that it would be overkill to use an entire library to validate if a file is in the right format.

$filename = $_POST['your_field_file'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
or this
$filename = "/home/user1/whatever.xls"; //or $_POST['your_field_file'];
echo $finfo->file($filename);
It will return the MIME type, verify if it is excell file, then you can look the file size, and put some restrictions, but if you want to know what have inside the file, I think you need to open or parse the file. Try to use file_get_contents() and verify line by line if has an image there. (I'm not sure about that)
I hope this help.

Sounds like you should make use of the fileinfo PHP extension to check the mime types of the files users are uploading.

Related

using PHP to remove the extension from a file and then downloading it

I recently had a asked a question very similar to this one, however after evaluating that I did not explain it in the best way I have come back once again explaining it in a greater manner.
So, I am creating a system that will gather data from a MySQL database and use a unique id to download a file, however depending on the value of a column within that database called type, this file could be anything from a png file to an xml file. What I am currently doing is trying to download these files WITHOUT any extension.
As an example to maybe make this easier to understand, a file named image.png would be converted to just image and then downloaded.
With this you could rename the file to image.png again on the local machine and view the image.
This may seem very inefficient to most reading this but for my current situation it's all that will work.
How could I remove a files extension and then download it? (in php)
Thank you in advance.
Just use headers to specify response type.
$filepath = '/wherever/the/file/is.png';
$filename = 'new-cool-name';
header('Content-Type: whatever/content-type-is');
header("Content-disposition: attachment;filename=$filename");
readfile($filepath);
This basically sends a response with specified content-type as an attachment and the body of the attachment contains the file contents. If you never sure what's the content type is, then just use application/octet-stream
Usually when you set out to push a file for downloading from a serverside script, you do so by utilizing http headers like https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
The filename of the downloadable file is specified in that header
Okay so to remove an extention from a file you could do is
$withoutExtion = preg_replace('/\\.[^.\\s]{3,4}$/', '', $youfilename);
...followed by your file download code

Detect an edited csv file using PHPExcel

I am using PHPExcel to validate csv files before parsing them and storing in my database and server. I am trying to use the file properties to determine if the file has been modified or if it is the original file. I have used the following for .xls, .xlsx with great results (using the appropriate reader);
$file = $_FILES['file']['tmp_name'];
$reader = new PHPExcel_Reader_CSV();
if($reader->canRead($file)){
$object = $reader->load($file);
$created = $object->getProperties()->getCreated();
$modified = $object->getProperties()->getModified();
if(!$created===$modified){
//File has been edited and cannot be used
}else{
//File is good, continue processing
}
}
However, when using CSV files, NOTHING is working as expected. I renamed an MS-Word doc to .csv->passed, edited a csv->passed, even used a .jpg->passed. What on earth am I missing?? Any help would greatly appreciated! Edit->I should note that $created and $modifed are an exact match when var_dump($object) despite having edited the file and confirming the changes within the document properties.
The properties values accessible from PHPExcel are those stored within the file itself, not within the directory entries for that file.
CSV files don't have any inherent properties of their own; CSV is purely a raw data file format These property methods are for accessing the properties that do exist in other spreadsheet formats such as BIFF (xls) and OfficeOpenXML (xlsx) which do support them. Loading a CSV (or other format that doesn't support properties) into PHPExcel will provide default value for those properties (so that calls like you're making won't trigger fatal errors), but it cannot provide actual values for something that doesn't natively exist in the format being loaded.

Change excel file extension from xls to xlsx while uploading with php

Is it possible and if is how can i change excel file extension while uploading or before saving file on server? I am using php and mysql.
Thankyou
You can do something like this.
move_uploaded_file($_FILES['file']['tmp_name'], upload_PATH.'/'.$_FILES['file']['name'].'x');
But that will only change the file name with the xlsx extension. It will not actually convert the file to xlsx format.
As previously mentioned in a different reply, changing the extension won't actually change the format, and it's not a good idea to serve a .xls file as .xlsx, since this will only confuse anyone trying to read it.
What you could do (disregarding potential problems with converting and verification of the file) is read the uploaded file into a library like PHPExcel (http://phpexcel.codeplex.com) and then use the builtin functions to export it as an .xlsx file. Sample below:
// Create a reader to read .xls format
$reader = PHPExcel_IOFactory::createReader('Excel5');
// Read the .xls file from upload storage
$workbook = $reader->load($_FILES['file']['tmp_name']);
// Create a writer to output in .xlsx format
$writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
// Save file to destination .xlsx path
$writer->save($destination_path);
Keep in mind that although this might work perfectly well, the conversion might mess with the contents of the file. This might not be desirable, as the conversion can cause data loss, formatting changes and all sorts of weirdness.

using php to check if a file is a kml file

I am using move_file_upload on my server side in php so that client can allow users to upload their kml files to the server. I know that in order to check an image , in php I can use $check = getimagesize(file) but what would be the equivalent for a kml file check ?
I donot want to just check the extension of the file. I wish to know if infact the file is a valid kml file or not. If I only check the extension, someone can just post some other malicious file and change its extension to .kml
If you want to see if the file has the extension KML, you can use:
$filename = $_FILES["file"]["name"]; //or however you are getting the filename
$ext = end((explode(".",$filename)));
if($ext!="kml"){
//Extension is incorrect
}
Checking mime content can be helpful.
I am not quite sure what is the correct mime name of kml files but at least with checking in google it should be something as:
mime_content_type ($file) === 'application/vnd.google-earth.kml+xml'
How ever its possible that there are mimes set to 'application/xml' or 'text/xml' so extension validation is required as well ..

Limiting file upload type

Simple question. Is there a way to only allow txt files upon uploading? I've looked around and all I find is text/php, which allows PHP.
$uploaded_type=="text/php
When you upload a file with PHP its stored in the $_FILES array. Within this there is a key called "type" which has the mime type of the file EG $_FILES['file']['type']
So to check it is a txt file you do
if($_FILES['file']['type'] == 'text/plain'){
//Do stuff with it.
}
It's explained very well here. Also, don't rely on file extentions it's very unreliable.
Simply put: there's no way. Browsers don't consistently support type limiters on file upload fields (AFAIK that was planned or even is integrated into the HTML standard, but barely implemented at best). Both the file extension and mime-type information are user supplied and hence can't be trusted.
You can really only try to parse the file and see if it validates to whatever format you expect, that's the only reliable way. What you need to be careful with are buffer overflows and the like caused by maliciously malformed files. If all you want are text files, that's probably not such a big deal though.
You could check the mime type of the uploading file. In codeIgniter, this code is used in the upload library:
$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
The variable $this->file_type then used to check the upload configuration, to see if the uploaded file is in allowed type or not. You can see the complete code in the CodeIgniter upload library file.
You need to check the file extension of the uploaded file.
There is Pear HttpUpload, it supports this.

Categories