- How to upload excel file to php server from
- 4 Answers 4
- Detect excel .xlsx file mimetype via PHP
- 3 Answers 3
- Overview
- Analyzing files
- Solution
- Code
- Upload xls or xlsx files with codeigniter, mime-type error
- 4 Answers 4
- Обзор PHP расширений для чтения файлов Excel
- PHPExcel
- Пример чтения файла в массив:
- SimpleXLSX
- PHP-ExcelReader
- PHP-Excel-Reader
- Nuovo Spreadsheet-Reader
- PHP-Spreadsheetreader
How to upload excel file to php server from
I want to upload excel file using to php and wanted to perform some file operation in that excel file. I am not able to upload the file , If any one have some Idea please help , in the server side how to get the path from where the file has been uploaded? $target_dir = ‘uploads/’; is not working for me. and My file is in D: Please help. PHP CODE:
load($target_file); $i=2; $val=array(); $count=0; for($i=2;$i<34;$i++) < $val[$count++]=$objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue(); > //echo'';print_r($val); > ?>
4 Answers 4
You first need to upload the file before the read line:
$target_dir = 'uploads/'; $target_file = $target_dir . basename($_FILES["filepath"]["name"]); $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); move_uploaded_file($_FILES["filepath"]["tmp_name"], $target_file); // rest of your code.
now you should be able to continue working on the file. before this, the file never have been in your uploads folder.
move_uploaded_file should receive 2 parameters, look again at my example. you missed the tmp_name of the source
if(isset($_POST['SubmitButton']))< try < //attached file formate $statement = $db->prepare("SHOW TABLE STATUS LIKE 'table_name'"); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) $new_id = $row[10]; //10 fixed $up_filename=$_FILES["filepath"]["name"]; $file_basename = substr($up_filename, 0, strripos($up_filename, '.')); // strip extention $file_ext = substr($up_filename, strripos($up_filename, '.')); // strip name $f2 = $new_id . $file_ext; move_uploaded_file($_FILES["filepath"]["tmp_name"],"uploads/" . $f2); // Client's info Insert MySQl $statement = $db->prepare("INSERT INTO table_name (files) VALUES (?)"); $statement->execute(array($f2)); $success_message = "Excel file upload successfully!"; > catch(Exception $e) < $error_message = $e->getMessage(); > >
Detect excel .xlsx file mimetype via PHP
You'd have to unpack the file. PHP won't peek inside the file for you. if it's an arcbomb, you'll just have to deal with it.
Okay, thanks. I hoped ms use additional information. And file information in nautilus said that it's "Microsoft Excel Worksheet (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)", but it use extention list..
3 Answers 3
Overview
PHP uses libmagic. When Magic detects the MIME type as "application/zip" instead of "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", this is because the files added to the ZIP archive need to be in a certain order.
This causes a problem when uploading files to services that enforce matching file extension and MIME type. For example, Mediawiki-based wikis (written using PHP) are blocking certain XLSX files from being uploaded because they are detected as ZIP files.
What you need to do is fix your XLSX by reordering the files written to the ZIP archive so that Magic can detect the MIME type properly.
Analyzing files
For this example, we will analyze an XLSX file created using Openpyxl and Excel.
The file list can be viewed using unzip:
$ unzip -l Openpyxl.xlsx Archive: Openpyxl.xlsx Length Date Time Name --------- ---------- ----- ---- 177 2019-12-21 04:34 docProps/app.xml 452 2019-12-21 04:34 docProps/core.xml 10140 2019-12-21 04:34 xl/theme/theme1.xml 22445 2019-12-21 04:34 xl/worksheets/sheet1.xml 586 2019-12-21 04:34 xl/tables/table1.xml 238 2019-12-21 04:34 xl/worksheets/_rels/sheet1.xml.rels 951 2019-12-21 04:34 xl/styles.xml 534 2019-12-21 04:34 _rels/.rels 552 2019-12-21 04:34 xl/workbook.xml 507 2019-12-21 04:34 xl/_rels/workbook.xml.rels 1112 2019-12-21 04:34 [Content_Types].xml --------- ------- 37694 11 files $ unzip -l Excel.xlsx Archive: Excel.xlsx Length Date Time Name --------- ---------- ----- ---- 1476 1980-01-01 00:00 [Content_Types].xml 732 1980-01-01 00:00 _rels/.rels 831 1980-01-01 00:00 xl/_rels/workbook.xml.rels 1159 1980-01-01 00:00 xl/workbook.xml 239 1980-01-01 00:00 xl/sharedStrings.xml 293 1980-01-01 00:00 xl/worksheets/_rels/sheet1.xml.rels 6796 1980-01-01 00:00 xl/theme/theme1.xml 1540 1980-01-01 00:00 xl/styles.xml 1119 1980-01-01 00:00 xl/worksheets/sheet1.xml 39574 1980-01-01 00:00 docProps/thumbnail.wmf 785 1980-01-01 00:00 docProps/app.xml 169 1980-01-01 00:00 xl/calcChain.xml 513 1980-01-01 00:00 xl/tables/table1.xml 601 1980-01-01 00:00 docProps/core.xml --------- ------- 55827 14 files
Notice that the file order is different.
The MIME types can be viewed using PHP:
\n"; echo mime_content_type('Excel.xlsx');
pip install python-magic-bin==0.4.14
import magic mime = magic.Magic(mime=True) print(mime.from_file("Openpyxl.xlsx")) print(mime.from_file("Excel.xlsx"))
application/zip application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Solution
@adrilo has investigated this problem and has developed a solution.
Hey @garak,
After pulling my hair out for a few hours, I finally figured out why the mime type is wrong. It turns out the order in which the XML files gets added to the final ZIP file (an XLSX file being a ZIP file with the xlsx extension) matters for the heuristics used to detect types.
Currently, files are added in this order:
[Content_Types].xml _rels/.rels docProps/app.xml docProps/core.xml xl/_rels/workbook.xml.rels xl/sharedStrings.xml xl/styles.xml xl/workbook.xml xl/worksheets/sheet1.xml
The problem comes from inserting the "docProps" related files. It seems like the heuristic is to look at the first few bytes and check if it finds Content_Types and xl . By having the "docProps" files inserted in between, the first xl occurrence must happen outside of the first bytes the algorithm looks at and therefore concludes it's a simple zip file.
I'll try to fix this nicely
Fixes #149
Heuristics to detect proper mime type for XLSX files expect to see certain files at the beginning of the XLSX archive. The order in which the XML files are added therefore matters. Specifically, "[Content_Types].xml" should be added first, followed by the files located in the "xl" folder (at least 1 file).
According to Spout's FileSystemHelper.php :
In order to have the file's mime type detected properly, files need to be added to the zip file in a particular order. "[Content_Types].xml" then at least 2 files located in "xl" folder should be zipped first.
The solution is to add the files "[Content_Types].xml", "xl/workbook.xml", and "xl/styles.xml" in that order and then the remaining files.
Code
This Python script will rewrite an XLSX file that has the archive files in the proper order.
#!/usr/bin/env python from io import BytesIO from zipfile import ZipFile, ZIP_DEFLATED XL_FOLDER_NAME = "xl" CONTENT_TYPES_XML_FILE_NAME = "[Content_Types].xml" WORKBOOK_XML_FILE_NAME = "workbook.xml" STYLES_XML_FILE_NAME = "styles.xml" FIRST_NAMES = [ CONTENT_TYPES_XML_FILE_NAME, f"/", f"/" ] def fix_workbook_mime_type(file_path): buffer = BytesIO() with ZipFile(file_path) as zip_file: names = zip_file.namelist() print(names) remaining_names = [name for name in names if name not in FIRST_NAMES] ordered_names = FIRST_NAMES + remaining_names print(ordered_names) with ZipFile(buffer, "w", ZIP_DEFLATED, allowZip64=True) as buffer_zip_file: for name in ordered_names: try: file = zip_file.open(name) buffer_zip_file.writestr(file.name, file.read()) except KeyError: pass with open(file_path, "wb") as file: file.write(buffer.getvalue()) def main(*args): fix_workbook_mime_type("File.xlsx") if __name__ == "__main__": main()
Upload xls or xlsx files with codeigniter, mime-type error
Well, i believe this is not a Codeigniter problem per se as it is more of a mime-type. I'm trying to upload a file, a xls (or xlsx) file and the mime-type the browser and the php report is application/octet-stream instead of application/excel, application/vnd.ms-excel or application/msexcel for a xls file. Of course codeigniter upload plugin will report an error (invalid file type) as it tries to match the file extension with the mime-type. The weird(est) thing might be that the same code worked for months and now stopped working with the latest Chrome (16.0.912.77), Firefox (10.0) and IE9. Has anyone had the same (or similar) problem and care to share the solution? Thank you very much. PS: I won't provide code as it's not really a code matter, but if necessary i'll upload some snippets. EDIT It might be relevant: the error doesn't happen with same browsers on a similar configuration, but with MS Office instead of Libre Office (on my pc). It doesn't happen on a GNU/Linux based + Libre Office system either. SO, could it be Windows playin' hard on the open source suite, or the Libre Office changing the mime-types just for the heck of it?
4 Answers 4
I'm getting this error also.
CI is reporting a file type of 'application/zip' which makes sense as the xlsx format is a compressed format (rename it to zip and you can open the contents).
I have added/replaced the following line to the mime types file (application/config/mimes.php):
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/zip'),
and that works (for this browser at least!)
Обзор PHP расширений для чтения файлов Excel
В статье представлены различные PHP-расширения для чтения файлов XLS, XLSX, описаны их плюсы и минусы, а также примеры чтения.
PHPExcel
Огромная библиотека читает и формирует фалы xls, xlsx, csv.
Пример чтения файла в массив:
require_once __DIR__ . '/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php'; // Файл xlsx $xls = PHPExcel_IOFactory::load(__DIR__ . '/test.xlsx'); // Первый лист $xls->setActiveSheetIndex(0); $sheet = $xls->getActiveSheet(); foreach ($sheet->toArray() as $row)
SimpleXLSX
- Менее прожорлив к памяти.
- Не всегда может прочитать файл, например файл сформированный PHPExcel.
require_once __DIR__ . '/simple-xlsx/simplexlsx.class.php'; // Файл xlsx $xlsx = new SimpleXLSX(__DIR__ . '/test.xlsx'); // Первый лист $sheet = $xlsx->rows(1); foreach ($sheet as $row)
PHP-ExcelReader
require_once __DIR__ . '/phpExcelReader/Excel/reader.php'; $data = new Spreadsheet_Excel_Reader(); $data->setOutputEncoding('UTF-8'); // Файл xls $data->read(__DIR__ . '/test.xls'); // Первый лист $sheet = $data->sheets[0]['cells']; foreach ($sheet as $row)
PHP-Excel-Reader
Форк библиотеки «PHP Excel Reader» с SourceForge предназначенный для вывода таблицы в HTML.
Например файл example.xls выведет следующим образом:
table.excel < border: 1px solid #CCCCCC; border-collapse:collapse; font-family:sans-serif; font-size:12px; margin: 0 auto; >table.excel thead th, table.excel tbody th < border: 1px solid #CCCCCC; text-align: center; vertical-align:bottom; >table.excel tbody th < text-align:center; width:20px; >table.excel tbody td < vertical-align:bottom; >table.excel tbody td dump(true, true); ?>
Также у библиотеки есть методы для получения формата и содержания каждой ячейки по отдельности.
Nuovo Spreadsheet-Reader
Читает файлы XLSX, XLS, CSV и OpenOffice ods. Для чтения XLS используется предыдущая библиотека php-excel-reader.
require_once __DIR__ . '/spreadsheet-reader/php-excel-reader/excel_reader2.php'; require_once __DIR__ . '/spreadsheet-reader/SpreadsheetReader.php'; // Файл xlsx, xls, csv, ods. $Reader = new SpreadsheetReader(__DIR__ . '/test.xlsx'); // Номер листа. $Reader -> ChangeSheet(0); foreach ($Reader as $Row)
PHP-Spreadsheetreader
Откроет только файлы в формате XML Excel 2004.
$file = __DIR__ . '/test.xml'; require_once __DIR__ . '/SpreadsheetReader/SpreadsheetReader.php'; $reader = new SpreadsheetReader; // Файл xml $sheets = $reader->read(__DIR__ . '/test.xml'); // Выводим Первый лист foreach ($sheets[0] as $row)