Like many others out there i have had my fair share of issues trying to download an Excel file output by PHPExcel.
What happened in my case was whenever I wanted to download a file using
$obj->save('php://output')
i always used to get garbled text in my excel file with a warning saying my file was corrupt. Eventually i resolved the issue. The problem being i had a
require('dbcon.php')
at the top of my php script. I just replaced that with whatever was there inside dbcon.php and it worked fine again.
Though the problem is solved i would really like to know what caused the problem. It would be great if anyone out there could help me out with this one.
Thanks.
If you get that error - you should follow the advice we always give in that situation: you use a text editor to look in the generated file for leading or trailing whitespace, or plaintext error messages - and then in your own scripts for anything that might generate that such as echo statements, blank lines outside ?> <?php, etc.
Another way of testing for this is to save to the filesystem rather than php://output and see if you get the same problem: if that works, then the problem is always something that your own script is sending to php://output as well.
Clearly you had a problem along those lines in your dbcon.php file. This can be as simple as a trailing newline after a closing ?> in the file...
Tanmay.
In situations like your's, there can be couple of reasons for broken output:
in file dbcon.php can be a whitespace before opening or ending php
tag, so that produce some chars to output and can make file broken
(this is reason for using only opening tag in php 5.3+);
maybe file dbcon.php wasn't found by require, so you got error message in otput;
any other errors or notices or warnings in dbcon.php, because presence of global vars from current file..
Related
QUESTION:
Hello stackoverflow!
So this encoding stuff is getting on my last nerve. Not enough that it is difficult to figure out what the best combination of encodings needs to be when sending stuff forth and back using AJAX and PHP and SQL etc.. But it also causing problems with SESSION???!
So basically I already found a hot-fix solution no-thanks to google, partly the reason I'm writing this now. But I would also like to see if anyone of you actually have any more practical solution.
PROBLEM:
For example if I want my PHP file to have UTF-8 encoding, it then adds hidden characters in the file which then can only be viewed and deleted in a hex-editor. For those that don't know, YES any extra characters that aren't commented out will cause problems with SESSION and give you header error. So when I delete them, and re-upload the file, it falls back to ANSI encoding. Maybe there are different editors that can encode files more properly into UTF-8? I don't know, I'm using Notepad++ at the moment and am perfectly happy with it and it is hard to believe it should cause problems with encoding. I have also tried to change my default encoding in .htaccess file and no difference for the index file anyways.
It seems, although we get WARNING: session_start(): Cannot send session cache limiter - headers already sent ... the sessions are still set perfectly fine and all we could do at this point is simply turning off warning errors by placing this on top of our php file: error_reporting(~E_NOTICE & ~E_WARNING); although this doesn't really solve our problem and simply hiding it from public eye.
Page open Notepad2 or Sublime Text -> Save with Encoding -> UTF-8
index.php
<?php
session_start();
header('Content-type: text/html; charset=utf-8');
echo 'Hello ÇÖİŞÜĞüğışçö'; // bla bla
?>
SOLUTION:
I had to therefore make a fix by making 2 separate files for one and the same index, just with different encoding. Like my main file is ANSI encoded and called
index.php
that will have session_start(); line in it and beneath it we include our main scripts that were originally supposed to be there, but instead now included with this include('index_.php'); ................ Also I found out that this problem will NOT occur on all hosting servers, but only some. So the real solution may be found trough somewhere in the server settings.
I checked all answers in different pages and use it, but the error still appears. Please help me.
The error is:
Warning: Cannot modify header information - headers already sent by (output started at /home/iraustor/public_html/copytest/post.php:1) in /home/iraustor/public_html/copytest/post.php on line 57
The URL of form is here: http://iraust.org/copytest/contact.html
And the page that after complete the form is: http://www.iraust.org/copytest/thanks.html (or any other method to shod this message)
It has taken 2 days but answer. Please help me.
"header("Location:$Redirect_Page");"
If you issue headers, like you do for a redirect (setting Location) you MUST be sure that there's no other output before that statement, as PHP will already build the headers (however maybe not yet flushing them to the client) on the first output.
This might be the case for several reasons (unexpected error in some require, a whitespace at the beginning or end of some file, etc, but the error message you have is clear in mentioning where this output started: /home/iraustor/public_html/copytest/post.php:1.
You should double check that there's nothing before the opening and after the closing <?php ... ?> block. This applies to all included or required files in called script.
As pointed out by h7r, if you use the header function you cannot print anything before its call.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
From Header documentation on PHP.net
So, the first thing you should check is the line 57 in your post.php file: there starts the output that causes the error.
Be sure that no output is sent: also a white space or a blank lines is an output and this cause the error.
If you like, you can use the output control functions to buffer the output: in this way you can print what you want but all your outputs aren't sent immediately to browser, so you can use the header function without causing errors.
Put your code somewhere for us to look at...
Possibly PHP could be outputting an error, or a warning, etc... It might not be you for example.
no space before
I completely confused!
The form is working and the information will be send to e-mail
but the error makes feeling nervous for users
The problem solved by simple code editor (notpad++)
problem: hidden white space and non Unicode characters
I have a PHP script, which attempts to read a file and output it, but none of the ways I know are working. It's kind of a weird case, since I can WRITE to the file, but not read it.
Posting any code would probably be unnecessary, I simply tried reading the file, first with file_get_contents, and then with fopen. None of them rises an error, they simply return an empty string. Even filesize returns 0 as the length. The only thing, that works is filemtime.
Any ideas why writing would be possible, but not reading?
EDIT:
It seems like file_get_contents works, when I point to the file, directly, using FTP, although a new weird issue came up: before the while-loop in my original code, it does return the file's text, but IN the while loop, it doesn't. And it's printing anything else with no problem, so it's not an echo-related issue..
Following is the code I come to notice from a PHP file:
<?php
# Should log to the same directory as this file
$log = KLogger::instance(dirname(__FILE__), KLogger::DEBUG);
$args1 = array('a' => array('b' => 'c'), 'd');
$args2 = NULL;
$log->logInfo('Info Test');
$log->logNotice('Notice Test');
$log->logWarn('Warn Test');
$log->logError('Error Test');
$log->logFatal('Fatal Test');
$log->logAlert('Alert Test');
$log->logCrit('Crit test');
$log->logEmerg('Emerg Test');
$log->logInfo('Testing passing an array or object', $args1);
$log->logWarn('Testing passing a NULL value', $args2);
You can notice that the closing PHP tag(?>) is not present there but still all the statements within code are working perfect. I'm not getting how this could be possible to execute the code without completion of PHP tag(?>). I researched but didn't get any satisfatory explanation. Can anyone guide me in this regard? Thanks in advance.
The closing tag exists to tell the interpretter that it should stop executing the text and just output it verbatim. Unlike XML, which requires openning and closing tags to match to be valid, the PHP interpretter simply uses the tags to delimit where execution should start and stop.
Just like a PHP file could have no opening tag - meaining that the entire contents would be output, no closing tag is necessary as once the end-of-file is reached execution ends.
While I can't remember any other reason, sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:
While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.
By sending headers inadvertently, you might have introduced a security vulnerability: say, you are doing a redirection, but hence the headers are already sent, the redirection does not work and the rest of the page might be output, thus the visitor may see what she was not supposed to see. While this can be mitigated by using exit, you know the story, only if every one of us utilize good programming habits every time.
Even if letting the visitor stay in the wrong page does not have a security implication, by breaking a session behavior, or in some other ways I've encountered over years, the security and/or session cycle might have taken some sort of blow in the end.
If not security, you may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.
You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.
If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).
Bonus: a few gotchas (actually currently one) related to these 2 characters:
Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$ with empty text in all files that contain PHP code.
From the PHP Manual:
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
I have spent the last several hours pulling my hair out trying to figure out the solution to this problem. I am sending an AJAX request which, up until some minor changes, worked perfectly, returning a lovely usable character to the Javascript. Now, however, a \r\n is being returned, and I have spent far too long tracking it down. My final method for finding where it was being included was literally echo-ing "OMG" in various places around my scripts until it showed up on Line 2 of the HTML instead of Line 1. Here is the offending script:
// Import Global Game Variables
include('../engine/engine_core_functions.php');
// Convert our gamestate(gameID)
//$curGamestate = getCurrentGamestate($gameID);
// Make sure it's a valid turn
if(isMyTurn()) {
// Draw a card from the card drawing mechanism
$cardValue = drawCard();
$cardValue = str_replace("\r", 'R', $cardValue);
echo $cardValue;
}
else echo 'Error 3';
The line skip occurs immediately after the include file at the top. Before the include, no line break, after the include, line break. So I go to the include file. Placing my
echo 'OMG!';
at the VERY END of the included file does NOT produce a line break. Which led me to believe that including a file may (why!?) generate a line break (it's 5 AM...). However, there are multiple included files at the top of the offending included file. None of them generate breaks. The entire "engine_core_functions.php" generates no line breaks at all.
However, a break shows up when it is included in the above-shown script. Needless to say, I'm baffled and extremely annoyed. I could simply remove the offending characters (via PHP or Javascript) but it annoys me I can't seem to fix the root of the problem. Please help, thank you.
You could have some kind of invisible BOM mark at the beginning of your file or something else.
Always let <? or <?php be the first string of your PHP files and make it a practice NOT to end the entire PHP file with ?> if it's going to be included by another file.