Printing contents of array on separate lines - php

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

Related

Not getting a new line when using use "\n" in PHP

I am trying to use \n in PHP to get a new line on my website, but it's not working.
Here is my code:
if(isset($_POST['selected'])){
$selected_val = $_POST['selected'];
// Storing Selected Value In Variable
echo "\n";
echo $selected_val; // Displaying Selected Value
}
On echo, use <br />.
The \n won't work in the HTML page, only in the source code, executing the PHP from the command line or writing into a text file.
This essentially boils down to saving the below text to a HTML file and expecting it to have visual line breaks:
one line
another line
To have a visual line break in HTML you're gonna need the br element:
one line<br />
another line
So replace your echo "\n"; with echo '<br />';.
If you have a string containing newlines, you could use the php built in nl2br to do the work for you:
<?php
$string = 'one line' . "\n" . 'another line';
echo nl2br($string);
When writing PHP code, you need to distinguish between two distinct concepts :
go to the new line in the code you produce, which you do using "\n"
go to the new line in the HTML webpage you produce, which you do using <br />
So, Option 1 makes you go to the new line in the code you produce, but you will not go to a new line in the HTML webpage you produce. The same way, option 2 makes you go to the new line in the HTML webpage you produce, but you will not go to a new line in the code you produce.
If you want go to the next line in both your code and the HTML output, you can just combine "\n" and <br /> :
echo "<br />\n";
On a web page, out of a <pre> block, all occurrences of tabs and newlines characters are assimilated as a single space.
For example:
echo "<pre>\n" . $selected_val . "</pre>";
But if your code is for debugging purposes, you'd better use print_r to inspect your variable values. Such as:
echo "<pre>" . htmlspecialchars(print_r($select_val), true) . "</pre>";
The htmlspecialchars function preserving you from ill-formed HTML due to the variable content.

PHP is variable not working as expected

I have a php variable $username and following script:
<?php
echo ''.$username.'';
?>
If $username contains something <b it bolds text. How can I prevent that?
Use htmlspecialchars
echo ''.htmlspecialchars($username).'';
See documentation: http://php.net/manual/en/function.htmlspecialchars.php
echo ''.htmlentities($username).'';
like that:
<?php
echo ''.htmlspecialchars($username).'';
?>
http://php.net/manual/fr/function.htmlspecialchars.php
the echo in PHP returns the HTML of whatever you tell it should. So if you use e.g.
echo "This is my text which should be displayed as it is <b>";
the browser will translate it into the according HTML Text (every browser has built in mechanics to "repair" malformed HTML), which will be
<b>This is my text which should be displayed as it is</b>
This is not only wrong, but also a security risk. Imagine someone uses an extremely long name which would translate into javascript once the browser renders it. Your server would turn into a spambot machine.
To prevent this from happening, you have to use the according php function, which is htmlspecialchars() (or htmlentities();
So your code will be:
echo ''.htmlspecialchars($username).''
and it will display the name as intended.
You need to strip (remove) HTML tags from the string.
echo '' . strip_tags($username) . '';
http://php.net/manual/en/function.strip-tags.php

Getting a variable from a link PHP

I have two files, one called test3.php, and another called test4.php. I'm trying to echo the variable in the link of the file test4.php, but it's echoing unexpected results. Please take a look.
In the file called test3.php:
<?php
$text = "Good morning.";
header('Location:test4.php?text=$text');
?>
In the file called test4.php:
<?php
$text = $_GET['text'];
echo "$text";
?>
Expected echo result:
"Good morning."
Actual echo result:
$text
I don't understand why it's echoing out $text, instead of "Good morning." One thing that came to mind is that you can't actually set variables when you're using a header, so if that's the case please let me know. Thank you.
Variables do not get parsed in single quotes
header('Location:test4.php?text=$text');
therefore, you need to use double quotes
header("Location:test4.php?text=$text");
References:
https://php.net/language.types.string
https://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
What is the difference between single-quoted and double-quoted strings in PHP?
Plus, it's best to add exit; after header, in order to stop further execution, should you have more code below that (or decide to in the future).
http://php.net/manual/en/function.header.php
and using a full http:// call, as per the manual
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
Footnotes, about header, and as per the manual:
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. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
However you wrote, and I'm using this literally:
Expected echo result:
"Good morning."
If you want to echo just that "Good morning." having the text in double quotes, then you will need to change the following in your test4.php file:
echo "$text";
to, and escaping the " using \
echo "\"$text\"";
use
header("Location:test4.php?text=".$text);
In test4.php:
<?php
$text = $_GET['text'];
echo "$text";
?>
When you quote "$text", you are echoing af string.
What you will want to do, is echo the variable: $text.
So:
<?php
$text = $_GET['text'];
echo $text;
?>
...Without the quotes.. :)
And also, the: header('Location:test4.php?text=$text'); is a bitch, if you use it below a lot of code...
Safe yourself some trouble, and use:
echo "<script type='text/javascript'>window.location.href = 'test4.php?text=".$text."';</script>";
instead ;)

php - how to hide the HTML part when no session_start();

thank you in advance , i wanted to stop not logged_in visiters from reaching some pages
i know i can just do that by cheking values in SESSION_ and and showing the HTML part with
<?php echo '<html>...</html>'; ?>
but i have a very long html content with both '' & "" text delimiters because it's not only HTML there is some JavaScripts, so i'm looking for another methode rather than printing the code with ECHO , and in this case i can't mixt PHP and HTML code . i there any solution or another idea to secure page from non member to see it,
and can i use this code to take them back to hope page (? :
<?php header("Refresh: 0;url=http://index.php/"); ?>
is it secure ?
so i'm looking for another methode rather than printing the code with
ECHO ,
use [heredocs] style or print all HTML outside php tag:
1- [heredocs]
echo <<<HEREDOCS
any string here ' or "
HEREDOCS;
note: notations should be at beginning of each line and ends with line break without any space or indent.
2- separation logic
<?php
//here is php
//close php
?>
<html>
<head>
</head>
<body>
<p>This will also be ignored by PHP and displayed by the browser.</p>
....
</body>
<?php
//php again
?>
When you echo out code that uses both ' and ", you escape the characters that match your opening and closing tags, like so:
echo '<p class="someclass">This can\'t be the end.</p>';
or
echo "<p class=\"someclass\">This can't be the end.</p>";
If you're worried about the " & ' text parameter,you should just use text editor such as sublime to to replace all " to '
and for " in textarea you can replace with "
then do
echo " <a href='#' value='{$var1}'>double quote mean "</a>some other massive code ";
thus you can just use a <?php and ?> from the beginning of page till the end of the page
What you can probably do is perform the check for the session variable at the start of the file and if the user is not logged in, use a header('Location: index.php'); followed by an exit();. If you do need to send headers based on logic that appears after the echo statements and changing the order of the statements is not doable, use output buffering.
Also, instead of including the HTML and Javascript within your code file, consider using a template engine, using include, or a combination of file_get_contents and echo (and possibly a string replace if you are using content placeholders). Heredocs and Nowdocs will make it easier to include single-quotes and double-quotes within strings.
Edit: If all you want to show unauthenticated users is an error message, you can redirect them to an error page, or use the PHP die(''); statement (which is like a combination of an echo and an exit).

New Line Character in PHP script on Remote Server not working

I am having trouble with "\n" character not working. I realized that it wasn't work while testing output of variables using a simple echo statement. I have tried approaching the new line character a few different ways to see if it was just me, but nothing I have tried is working. Here is an example of some attempts I have made:
<?php
// Establish Connection to Taskaro DB
require "../_connections/connection_taskDB.php";
// Start Session
session_start();
// Create Session Variables
$_SESSION['userID'];
$_SESSION['companyID'];
$_SESSION['usernameDB'];
// Convert Session Variables to page variables
$userID = $_SESSION['userID'];
$currentUser = $_SESSION['usernameDB'];
$editType = $_REQUEST['editType'];
$projectID = $_REQUEST['projectID'];
// Testing if new line character is working
echo "hello, Mr. New Line!\n\r";
echo "This line should be below 'hello, Mr. New Line!'";
// Testing variable and session connection
echo "SESSION VARIABLES:"."\\n\n"."userID = {$userID}";
echo "userID = {$userID}"."/n";
echo "currentUser = {$currentUser}"."\r";
echo "companyID = {$companyID}\n\r";
echo "\nPOST VARIABLES:\n";
echo "editType = {$editType}\n";
echo "projectID = {$projectID}\n";
?>
I read up on some other overflow questions that had similar problems and none of them fixed my problem. The project is on a remote server (GoDaddy) in which php has been installed. The document has the correct file extension (.php). I am coding in dreamweaver and uploading my script for testing. From the code you can see I've tried "\n","\n\r","\r". I've also tested in both Firefox and Google Chrome.
I also tried to concatenate the "\n" character, and took a shot in the dark and even tried using the forward slash rather than the backslash (I knew it wouldn't work, but I'm getting pretty frustrated at this point). I bet it's something simple but I don't see what else is could be. Thanks in advanced.
If you view the source of the page, you will see all of those values output on separate lines.
If you are viewing the file in the browser, you need to use line breaks (<br />) if you want your text to show up on different lines. HTML ignores newlines in regards to presentation.
echo "hello, Mr. New Line!\n";
echo "This line should be below 'hello, Mr. New Line!'";
When viewing source, the above two text strings will be on separate lines. When viewed in the browser they will appear to be on the same line.
echo "hello, Mr. New Line!\n<br />";
echo "This line should be below 'hello, Mr. New Line!'";
When viewing source, the above two text strings will be on separate lines because of the \n. When viewed in the browser they will also be on separate lines because of the HTML break <br />.
Use the PHP_EOL constant instead of \n and call it a day.
Also, it's \r\n, not the other way around.
If you are expecting the browser to render new line characters as new lines in HTML, that won't happen. You need to use the <br> tag.

Categories