What factors that affect the single line comment? - php

I just started to learn the php and found interestingly new only to me that single line php can affect the code (break the code and may output the html):
From the docs:
// $file_contents = '<?php die(); ?>' . "\n";
Which results in ' . "\n"; (and whatever is in the lines following it) to be output to the HTML page.
But using comment on this wouldn't affect the code:
$file_contents = '<' . '?php die(); ?' . '>' . "\n";
Ah, its only because of < and > or something else?
So, I'm curious to know what exactly the factors that affect from using single line comment?

This is an excerpt from the php.net website mentioned in my comment:
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the tag doesn't break out of PHP mode in a one-line comment.
In your example, it would be the ?> that is breaking out of the comment as new lines and end PHP tags will override comments to end the script, which is why when you split the ? and the > into two strings and concatenated them, it didn't end the comment.

Related

The proper use of PHP_EOL and how to get rid of character count when reading a file

I am trying to write a function in which a string of text is written with timestamps to the file "text2.txt", I want each entry to be on a new line, but PHP_EOL does not seem to work for me.The strings simply write on the same line and does not write to a new line for each string.
Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated?
Some sort of example would be highly appreciated.
Thank you in advance.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['sendmsg']))
{
writemsg();
}
function writemsg()
{
$txt = $_POST['tbox'];
$file = 'text2.txt';
$str = date("Y/m/d H:i:s",time()) . ":" . $txt;
file_put_contents($file, $str . PHP_EOL , FILE_APPEND );
header("Refresh:0");
}
?>
Also, I want to get rid of the character count on the end of the string when using the below code :
<?php
echo readfile("text2.txt");
?>
Is there any way for the character count to be disabled or another way to read the text file so it does not show the character count?
Could anyone give me some pointers or ideas as to how to force the script to write to a new line every time the function is activated? Some sort of example would be highly appreciated.
Given the code you posted I'm pretty sure newlines are properly appended to the text lines you are writing to the file.
Try opening the file text2.txt on a text editor to have a definitive confirmation.
Note that if you insert text2.txt as part of a HTML document newlines won't cause a line break in the rendered HTML by the browser.
You have to turn them into line break tags <br/>.
In order to do that simply
<?php
echo nl2br( file_get_contents( "text2.txt" ) );
?>
Using file_get_contents will also solve your issue with the characters count display.
A note about readfile you (mis)used in the code in your answer.
Accordind to the documentation
Reads a file and writes it to the output buffer.
[...]
Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as #readfile(), an error message is printed.
As readfile reads a file and sends the contents to the output buffer you would have:
$bytes_read = readfile( "text2.txt" );
Without the echo.
But in your case you need to operate on the contents of the file (replacing line breaks with their equivalent html tags) so using file_get_contents is more suitable.
To put new line in text simply put "\r\n" (must be in double quotes).
Please note that if you try to read this file and output to HTML, all new line (no matter what combination) will be replaced to simple space, because new line in HTML is <br/>. Use nl2br($text) to convert new lines to <br/>'s.
For reading file use file_get_contents($file);

Adding ?> to a PHP comment

I am fairly new to PHP and trying to create a piece of community learning code for my co-learners to help them and I want to put a coding tip in the comments. I tried writing the following:
# Tip -- when PHP is the only code in a file, don't put ?> at the end as this can cause bugs if white-space or additional PHP code is written to the end of the file after the file is initially created, after the ?>
However, typing ?> in the comment ends the file and the comment. How do I escape this? I tried using \ but that doesn't seem to work, and would also confuse the sense of the comment.
How is this done?
PHP doesn't work well with single lined comments using the closing and starting tags. Although you can use a muti-lined comment:
/* Tip -- when PHP is the only code in a file, don't put ?> at the end as this can cause bugs if white-space or additional PHP code is written to the end of the file after the file is initially created, after the ?> */
Note this is mentioned in the Comment Documentation for PHP:
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that.

writing to text file - layout messed up - PHP

ive got the following fwrite code, with , separating the data and it ending in ))
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);
but this is how it saves in the text file...
,,,,))Triangle,180,120,80,Red))
why have the first set of
,,,,,))
appeared in front of what it should look like?
You need to add a new line character to the end of each line. Otherwise your lines will all run into each other.
Use PHP_EOL for this as it will automatically use the Operating System appropriate new line character sequence.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform.
Available since PHP 4.3.10 and PHP 5.0.2
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))'.PHP_EOL;
FYI, this might be a little cleaner to do using sprintf():
$shapeType = sprintf("%s,%s,%s,%s,%s))%s",
$_POST['shapeType'],
$_POST['triangleSide1'],
$_POST['triangleSide2'],
$_POST['triangleSide3'],
$_POST['triangleColour'],
PHP_EOL
);
Without seeing more of the code I would guess that you post to the same file and you do not check if a POST request was made before you write your file. So probably you write to your file on a GET request as well, causing empty entries to appear.
You would need something like:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// ...
$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);
// ...
}
Edit: By the way, you should probably use fputcsv as that takes care of escaping quotes, should you change something in the future that adds for example a description field.

Printing contents of array on separate lines

Experimenting with arrays and wondering why the following DOESN'T seem to print the values on SEPARATE lines when I run it?
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
echo $my_array[0] . "\n";
echo $my_array[1] . "\n";
echo $my_array[2] . "\n";
?>
This makes the trick.
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
foreach ( $my_array as $item ) {
echo $item . "<br/>";
}
?>
If your viewing the output in a web browser, newlines aren't represented visually. Instead you can use HTML breaks:
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
echo implode('<br>', $my_array);
?>
From my PHP textbook:
One mistake often made by new php programmers (especially those from a
C background) is to try to break lines of text in their browsers by
putting end-of-line characters (“\n”) in the strings they print. To
understand why this doesn’t work, you have to distinguish the output
of php (which is usually HTML code, ready to be sent over the
Internet to a browser program) from the way that output is rendered
by the user’s browser. Most browser programs will make their own
choices about how to split up lines in HTML text, unless you force a
line break with the <BR> tag. End-of-line characters in strings will
put line breaks in the HTML source that php sends to your user’s
browser (which can still be useful for creating readable HTML
source), but they will usually have no effect on the way that text
looks in a Web page.
The <br> tag is interpreted correctly by all browsers, whereas the \n will generally only affect the source code and make it more readable.
You need to print with <br/> instead of \n because the default PHP mime type is HTML, and you use <br/> to accomplish line breaks in HTML.
For example,
<?php
$my_array = array("stuff1", "stuff2", "stuff3");
echo $my_array[0] . "<br/>";
echo $my_array[1] . "<br/>";
echo $my_array[2] . "<br/>";
?>
That's because in HTML a line break is <br />, not "\n".

Echo statements aren't being flushed properly?

I've been trying to debug this code for hours now, but haven't been making any headway. My print statements are simply not working. Another question suggested I flush(), but it's not working.
echo 'this never prints';
flush();
flush();
flush();
Any help would be appreciated.
I think you have the display_errors directive off. Check your php.ini file to see if this is the case.
Your code has a syntax error; you are missing a semi-colon after the echo statement. Any syntax error can only be seen in the browser if display_errors is on.
php.net on display_errors:
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
If you are inside an outbut buffer, which you can check with ob_get_level()>0, you can flush contents with ob_flush(). If you want to break out of all outbut buffers, this is a quick oneliner to end them all:
while(ob_get_level()>0) ob_end_flush();
Possibly use ob_end_clean() instead of ob_end_flush() if you want to discard the buffer(s).
<?php
echo "Hello Web!";
?>
In this simple script you can see some of the most used components of a PHP script. First off, PHP tags are used to separate the actual PHP content from the rest of the file. You can inform the interpreter that you want it to execute your commands by adding a pair of these: standard tags ""; short tags ""; ASP tags "<% %>"; script tags " ". The standard and the script tags are guaranteed to work under any configuration, the other two need to be enabled in your "php.ini"

Categories