Line feed is showing up unexpectedly in PHP - php

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.

Related

Where is the data coming from?

It seems I met this problem before, in a different disguise. When a file was being "included" in my main php file before starting a session in that same main php file, I'd get the "headers already sent" error because my included php had a blank line at the start, which was being somehow sent before anything should be sent. Delete blank line, "problem solved"...
Now I have this ajax thingy where I scan a certain string returned by a php. The string I hardcoded in this php to be returned to the ajax callback was the string "alert", which was never seen. I scan what is being received by the callback, and guess what? It has a character 10 starting my 5 character "alert" string.
Sounds familiar? yes, I had an include before the "echo("alert");", and that include'd file DID start with a blank line (too! why I keep doing this???). Delete line, and now I don't get the character 10 (ascii "new line" eh?) starting my "alert" string anymore.
The question: why is the php echo'ing a "new line" character that was never formally "echoed" along with my carefully crafted string? Is this a bug of mine or php? Thanks in advance.
Everything not inside your <?php ... ?> tags is treated as text and sent to the client. So make sure not to have empty lines in your source files...
Edit: The purpose of this is to have a simple way to have a HTML file mixed with portions of PHP code without the need to echo all the HTML stuff explicitly...

Php include to skip the first 12 lines read

I am reading data from a htm page into a Wordpress post with <?php include("liveresults/140403F001.htm"); ?> it works perfectly. I however need to skip the first 12 lines of the html file and only start reading from line 13. Any ideas?
If the file only contains HTML and you don't want to execute it as PHP, then you should not be using include anyway. readfile() is much better suited for that.
However, since you want to ignore the first 12 lines, you should use an SplFileObject which allows you to seek by line:
$file = new SplFileObject("liveresults/140403F001.htm");
$file->seek(12);
$file->fpassthru();
Note that if your file comes from some sort of external input, you should escape it for HTML, to guard against XSS.

PHPExcel outputs garbled text

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..

How does the PHP code execute even without closing the ?> PHP tag?

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.

PHP assign variable definition from a string

Let's say I have a file "English.txt" containing these lines :
$_LANG["accountinfo"] = "Account Information";
$_LANG["accountstats"] = "Account Statistics";
Note : the file extension is .txt and there is nothing I can do to change that. There is no opening PHP tag (<?php) or anything, just those lines, period.
I need to extract and actually get the $_LANG array declared from these lines. How do I do that? Simply includeing the file echoes every line, so I do
ob_start();
include '/path/to/English.txt';
$str = ob_get_clean();
Now, if I call eval on that string, I get an syntax error, unexpected $end. Any ideas?
Thanks.
eval(file_get_contents('English.txt'));
however, be sure NOBODY can change English.txt, it could be dangerous!
First of all, note that you should use file_get_contents instead of include with output buffering. Since it contains no <?php tag, there is no need to run it through the script processor.
The following works perfectly in my tests:
<?php
$contents = file_get_contents("English.txt");
eval($contents);
var_dump($_LANG);
As one of the comments said, if you do the above and still get an error, then your file does NOT contain exactly/only those lines. Make sure the file is actually syntax compliant.
As has been mentioned, you should really use eval only as a last resort, and only if the file is as safe to execute as any code you write. In other words, it must not be editable by the outside world.

Categories