'The filename 062014.xlsx is not recognised as an OLE file' - php

I am working on a complex program that deals with Excel, so I am using PHPExcel to search and edit the Excel file from a browser. My problem comes in the editing portion of the program, so I wrote a basic program to edit the existing Excel page. It seems that PHPExcel does not recognize the file created in Excel as an Excel file. This is done on my own server with an Excel page I created with Excel. The filename is 062014.xlsx. On the HTML side I named the text boxes C3, D3, and E3, so their names will easily correspond with Excel cells ( where the php $cell variable comes from). What I want to do is take the text in the html text boxes and rewrite corresponding cells in Excel with the data from the html textboxes. Posted is my whole code from html and php, if someone can tell me where my program is going wrong, I would greatly appreciate it.
<html>
<head>
<form method="POST" action="lilrevisetest.php" id="excelform">
<input type="text" value="foo" name="C3" />
<input type="text" value="foo" name="D3" />
<input type="text" value="foo" name="E3" />
<button type="submit">Submit</button>
</form>
</body>
</html>
<body>
<html>
<?php
include 'PHPExcel/IOFactory.php';
$n=1;
$x="C";
$y=1;
$file = "062014.xlsx";
$inputFileType = PHPExcel_IOFactory::identify($file);
$inputFileType = 'Excel5';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load($file);
$objWorksheet = $objPHPExcel->getActiveSheet();
$fileObj = fopen("$file", "rt" );
$y = 3;
$x= "C";
for($n=1; $n<4; $n++){
$cell = $x . $y;
echo $cell;
if (isset($_POST[$cell])){
$string = ($_POST[$cell]);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $inputFileType);
$objWorksheet ->setCellValue("$cell","$string");
$objWriter->save($file);
}
echo "<td> <input type ='text' value= '$string' name = '$cell'/></td>";
$x= ++$x;
}
?>
</html>
</body>

You are trying to load an xlsx file (OfficeOpenXML-format) using the Excel5 (BIFF-format) Reader.
$inputFileType = 'Excel5';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
You should be using the correct Reader for the file type you're trying to load, otherwise you will get errors.
You've already used
$inputFileType = PHPExcel_IOFactory::identify($file);
to identify the filetype and the correct Reader to use, so why are you ignoring this and setting it manually (and incorrectly) yourself?
Additionally
Another problem is likely to be the fact that the file is already open when you try to save it.
You're loading $file (062014.xlsx) using the PHPExcel loader, no problem.
For some unknown reason, you then execute
$fileObj = fopen("$file", "rt" );
though you don't do anything with $fileObj at all, but doing this leaves it open
When you try to save using $objWriter->save($file);, the file is still held open, so the save will fail (nothing to do with the filename, simply the fact that the file is open).
The solution is as simple as deleting the line
$fileObj = fopen("$file", "rt" );

Related

whysiyg save in php file

I am currently developing somthing like a CMS, but without using any database. A really big problem for me is how can you change (and later format content via tinymce (or similar) ) and then save it into a php file?
My configuration file for each page looks like this:
<?php
$title = 'Title of the page';
$contenttitle = <<<HTML
Something like a short summary, displayed at the top
HTML;
$content = <<<HTML
main content
HTML;
$foldername = basename(__FILE__, '.php');
include '../template/standard/layout/index.php'; ?>
Now, I want to be able to open a script in the browser where I can select the file I want to edit and see text boxes with content of $title, $contenttitle and $content.
So, in fact we open a file, look for these 3 variables, display their content and change them (overwrite the file).
How can this be solved?
This is just an example approach that may help you:
Write a php/html file which will print out a form for you:
<form method="post">
<input type="text" name="title" value=""/>
<input type="text" name="contenttitle" value=""/>
<textarea name="content">">
<input type="submit" value="save"/>
</form>
Handle your form in the php file:
if (!empty($_POST)) {
$result = array(
'title' => htmlspecialchars($_POST['title']),
'contenttitle' => htmlspecialchars($_POST['contenttitle']),
'content' => htmlspecialchars($_POST['content'])
);
// save it to a file by serialiing
$filename = uniqid().'.text'; // you may play around with file names, rewrite this line so it will suit your convention - you may use counter of the files
file_put_content($filename, serialize($result));
}
To retrieve file and print it use something like this:
$file = $_GET['name'];
$file = str_replace(array('/', '.', '\'), '', $file); // for security reasons
$content = file_get_contents($file.'.text'); // note this is an example extension
$data = unserialize($content);
echo '<h1>'.$data['title'].'</h1>';
echo '<h2>'.$data['contenttitle'].'</h2>';
echo '<p>'.$data['content'].'</p>';

HTML codes always showing up when I export query result to Excel CSV

I am exporting the results of a query from SQL Server. I half successful in doing it coz I have 1 problem. The HTML codes or interface of the page gets included in the exported .csv file. How do I remove it from the exported file? I have the codes below to give you an idea :)
Also, if you have other tips on how can I improve this thing, like I
want it to be in Excel Format (xlsx), please guide me :)
<html>
<head>
<title>Generate Report</title>
<script>
function MessageBox()
{
alert('Clicked!');
}
</script>
</head>
<body>
<form method='post'>
<input type='date' name='dateStart'> <input type='date' name='dateEnd'>
<input type='submit' name='btnSubmit' onclick='MessageBox()'> <br>
</form>
</body>
</html>";
<?php
include "db.php";
$con = SetConn();
if(isset($_POST['btnSubmit']))
{
header("Content-type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename=Export.csv');
$start = $_POST['dateStart'];
$end = $_POST['dateEnd'];
$user_query = sqlsrv_query($con, "SELECT TOP 100 * FROM [db_nps].[dbo].[survey_report] WHERE (time_stamp >= '$start' and time_stamp <= '$end')");
//While loop to fetch the records
$contents = "it_id, it_site, it_oraclenumber, it_lastname, it_firstname, ttsd_number\n";
while($row = sqlsrv_fetch_array($user_query, SQLSRV_FETCH_ASSOC))
{
$contents.=$row['it_id'].",";
$contents.=$row['it_site'].",";
$contents.=$row['it_oraclenumber'].",";
$contents.=$row['it_lastname'].",";
$contents.=$row['it_firstname'].",";
$contents.=$row['ttsd_number']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
}
?>
You are telling PHP to use everything echoed as the content for your CSV file. Yes, you are doing so after you echo your HTML, but it doesn't matter; it is all processed at the same time.
Let me Explain:
When you use the header() method, you are telling the browser that the content it is receiving is of a certain type. In your case, you are telling it that the content it is to receive is a CSV document that it should download.
It does not matter where header() is placed within the file, as long as it is before the print or readFile statements.
So essentially what your browser is doing is reading the entirety of the page, including the HTML as plain text for a CSV document. Remember that while PHP will process itself in order, the browser receives all of the information from the server at the same time, and since you are telling it to download the document as a CSV, it takes the whole page.
So what do you do?
My advice to you is to put the printing code in a separate external PHP document and link to it, rather than trying to do it on a page that echoes HTML.
I solved the problem.Try to use your code like this
$filename = 'trip_data.csv';
// file creation
$file = fopen($filename,"w");
// output the column headings
fputcsv($file, array('travel date', 'travel time', 'travel from', 'travel to','number of pessengers', 'car type', 'trip status', 'flight number', 'travel price( £ )'));
$query = "SELECT travel_date,travel_time,travel_from,travel_to,number_of_pessengers,car_type_id,trip_status ,flight_number,travel_price FROM trip";
$travelList = $conn->query($query);
while ($rowValue = $travelList->fetch_assoc()) {
fputcsv($file,$rowValue);
}
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/csv; ");
readfile($filename);
// deleting file
unlink($filename);
exit();

Updating HTML files using PHP from form input

Basically, I want to update static HTML files with code snippets input by users from a standard form. I understand how updating the files work, I'm just unsure as to how I go about including the code input from the form to my php file, which is shown below.
<?php
if($handle = opendir()) {
$search = '</body>';
replace = <<< EOF
<!-- I want to populate this with form field input.-->
EOF;
while(false !== ($entry = readdir($handle))) {
if(is_dir($entry)) continue;
$content = file_get_contents($entry);
$content = str_replace($search, $replace . '</body>', $content);
file_put_contents($entry, $content);
}
}
echo 'done';
?>
Any help greatly appreciated.
I would approach this a bit differently. I suggest having a template file aside from the one being modified. That way, you are always modifying a fresh copy instead of having to worry about what changed in the new version.
If your needs become more advanced beyond simply dropping in some markup, I might suggest using a DOM parser.
Finally, I'm sure you have a good reason for writing these static files... just remember the security implications of doing so. You're effectively letting someone do almost anything they want to your server.
Although I agreed it was in no way the best solution to the specific problem, for anyone that may find this useful in the future I used file_get and str_replace to achieve desired results. The code below will allow you to search a file for a specific term and replace with whatever you want based on form input.
<?php
//These are the variables the html file will post to the script.
$filename = $_POST['myFile'];;
$tofind = $_POST['myFind'];;
$toreplace = $_POST['myReplace'];;
$file = file_get_contents($filename);
$end = str_replace($tofind, $toreplace, $file);
$fp = fopen($filename, "w"); //Open the filename and set the mode to Write
if(fwrite($fp, $end)) ; //Write the New data to the opened file
fclose($fp); //Close the File
echo(" File name is $filename ... Finding $tofind .... Replacing with $toreplace ..... Done !");
?>
Though it's a horrible solution, mixed with your code this will do
$replace = array_key_exists('input',$_REQUEST) ? $_REQUEST['input'] : '';
//$replace = sanitize($replace); // there's so much bad with this string
//do the needfull
?>
<form method='GET' action='#'>
<input type='text' name='input' />
<input type='submit' />
</form>

Display thumbnailPhoto from Active Directory in PHP

I've set up a system to display everyone's name, email address and phone number from Active Directory however I can't get the 'thumbailPhoto' to work.
I have searched around on the internet but haven't been able to find if this is possible or at the very least what format is returned from Active Directory.
I am currently using the adldap class so if it is possible to use this that would be ideal.
Thanks in advance.
Edit:
I can retrieve the data in the thumbnailPhoto attribute and if I dump them straight to the browser I get something like this:
ÿØÿàJFIFððÿá
PExifII*bh~†(2Ži‡¢XCanonCanon EOS 5D Mark
IIIðð2013:05:19 17:35:31š‚à‚è"ˆ'ˆ 0230ð’
’ ’ (’0’8’ ’ ’#‘’11’’11 0100
ÿÿ¢H¢P¢¤¤¤¤ 2013:04:17
11:44:522013:04:17 11:44:52H¹o#B¬ †
è»dnäWµ˜:̦®(¶’
HHÿØÿàJFIFÿÛC $.'
",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀ–d"ÿÄ
ÿĵ}!1AQa"q2‘¡#B±ÁRÑð$3br‚
%&'()456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ
ÿĵw!1AQaq"2B‘¡±Á #3RðbrÑ $4á%ñ&'()
That isn't all of it but it is a very long string, I am presuming is some sort of binary string?
This seems to be a JPEG-File, so you should be able to send that data together with the appropriate mime-type to the browser. It should be possible to output that image with something like:
<img src="data:image/jpeg;base64,<?php echo base64_encode($imageString); ?>"/>
But it might also be possible to save files of any image format into that thumbnailPhoto attribute. Therefore, I would put the content into a temporary file that will then be served directly from the server. You will need to pass the file through finfo to get the correct mime-type.
So you might do something like this:
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $imageString);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
echo '<img src="data:' . $mime[0] . ';base64,' . base64_encode($imageString) . '"/>';
Try the code below. It is an adaptation of the answer above.
<?php
$result = ldap_search($ad , $dn , $filter, $attributes);
$aduser = ldap_get_attributes($ad, ldap_first_entry($ad,$result));
?>
<img src="data:image/jpeg;base64,<?php echo base64_encode($aduser['thumbnailPhoto'][0]); ?>" />
when you store the photo data into ldap i.e. "jpegphoto" attribute it should be done by using encode base64.
Reading the attribute is already decoded on fly. Hence I would use something less modified code
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $imageString);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
header("Content-Type: $mime");
echo $imageString;
This is direct php image write example
you can directly use it under tag img i.e.
<img src="example.php" />

Output issues with PHPExcel

I have a web page where a user selects the amount of rows to be displayed followed by a button within a form that exports the data to excel.
<form method="post" action="">
<input type="Submit" name="excel" value="Export" class="button">
</form>
I am able to get the data and put it into the excel file with the follwoing
if($_POST['excel']){
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
)
);
//Get the active sheet and assign to a variable
$foo = $phpExcel->getActiveSheet();
//add column headers, set the title and make the text bold
$foo->setCellValue("A1", "Nombre")
->setCellValue("B1", "Paterno")
->setCellValue("C1", "Pkey")
->setCellValue("D1", "Telefono")
->setCellValue("E1", "Ciudad")
->setCellValue("F1", "Used")
->setTitle("Contactos Encuestas")
->getStyle("A1:F1")->applyFromArray($styleArray);
$xlsRow = 1;
foreach ($rows as $column) {
$foo->setCellValue("A".$xlsRow++, $column[2])
->setCellValue("B".$xlsRow++, $column[3])
->setCellValue("C".$xlsRow++, $column[0])
->setCellValue("D".$xlsRow++, $column[1])
->setCellValue("E".$xlsRow++, $column[5])
->setCellValue("F".$xlsRow++, $column[4]);
}
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"ENcuestas_Contactos.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
$phpExcel->disconnectWorksheets();
unset($phpExcel);
}
This kinda works, the issue is that weird text allong with the webpage elements such as buttons and images get put onto the excel file.
What could be the issue?
is there a setting i'm missing?
Found out why I was getting HTML elements in the excel file.
I had the PHP code within the HTML.
Put the PHP Code outside the <html> code and voilà my excel file displayed without any issues.

Categories