New Line Character in PHP script on Remote Server not working - php

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.

Related

Tired of guessing - cannot get line break to work

VERY simple routine that pulls the name of each PDF file in a folder and creates a list of each file found with a link to it. But I cannot get a line break between the items
Nothing seems to give me each file name and link on a new line. I have no idea why.
Neither of the \n has any affect at all.
<?php
$directory = "./images/";
$phpfiles = glob($directory . "*.pdf");
foreach($phpfiles as $phpfile)
{
echo "\n","<a href=$phpfile>".basename($phpfile)."</a>";
echo "\n";
}
?>
All I get for output is this....all on one line.
CAD_REPEQUEST.pdf JP_CADS.pdf JP_Reports.pdf
What I want is this....
CAD_REPEQUEST.pdf
JP_CADS.pdf
JP_Reports.pdf
If you're outputting to a Web page you'll need to replace \n with <br>.
If you're outputting to a text or other type of file, you may wish to replace \n with the constant PHP_EOL.
If you're outputting this to an email that's getting sent in text format, you'll have trouble with some clients, like Outlook, that will automatically attempt to remove unnecessary line breaks. Sometimes using a double line break helps, or you could convert your email to HTML and use the <br> approach.

PHP code from a file does not execute

I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:
function parsecode($codetype) {
$source = file_get_contents("file.php");
$language = $codetype;
$geshi = new GeSHi($source, $language);
echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>";
echo $geshi->parse_code();
}
This works perfectly fine!
Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:
$find = array(
"/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
'<?php parsecode("$1"); ?>'
);
Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.
What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.
Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.
My question: Why does the function not execute & parse the code like it should?
Thanks ahead!
There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().
http://www.php.net/manual/en/function.eval.php
This let's you dynamically make code and execute it
Please remember this quote though:
"If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"
eval() is known for security vulnerabilities and being exploited. Highly not recommended.
However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.
You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...

PHP echo adds a new line

Could somebody explain me why the PHP tags are giving me a linebreak?
And also, how can you delete this or stop this from happening, as it messes up my site.
An example I'm using on my site:
<?php include('assets/common/theme_header.php'); ?>
EDIT:
This doesn't seem to happen when I'm using:
<?php ?>
It does however seem to happen only when I'm using echo, which I also use on my include.
Example:
<?php echo "hello"; ?>
This still gives me a "linebreak", and it shows like this in Chrome development kit:
I had a similar situation where a php file on the server always echoed a space, then newline and then the actual echo. Like " \n[someVariable]". I got rid of it by making sure the php file had no empty lines at the beginning or end of the file.
So no empty line before the <?php or after the end ?>
Perhaps your problem is related.

Storing line break in a php Variable

I am developing a Facebook App in which I get some text from the Database and Display it on the Page.
The Problem is that I want to insert a line Break in the variable e-g
If I copy a Text from database and store it in a Variable..
Let say
$text="I love to walk";
I want to insert a line break after "to" how can i do that?
I had tried to store the text like this in html
"I love to <html> <br> </html> but that didn't worked..
Just suppose this is the Text ..may be next time the text is entirely Differnet having no "to" word.
Depends on if you want to create new line in code output, or in HTML
$nl = "\r\n";
$nl_html = "<br />";
That exmple you provided modify like this:
$lyrics = "I love to <br> but that didn't worked.."
To automatically add line break after some text, use preg_replace
$lyrics = preg_replace('/to /',"to<br />",$lyrics);
see http://php.net/manual/en/function.preg-replace.php
$new_str = str_replace('to', 'to <br />', $str, 1);
If you want to output the text in a html page, you need to make it
$text="I love to <br /> walk";
If you want to output it to a file you need to make it
$text="I love to\r\nwalk";
or
$text="I love to\rwalk"; depending on the OS on which you will be reading the file
Hi I was having issues with this just as you do earlier today (I am new to PHP).
The way I fixed this was as follows:
$format_text = nl2br($formatthis);
You would then refer to $format_text.
What it does is it keeps the line breaks.
However I am not quite sure what you mean with your OP, after re-reading it. I went by the topic and I answered it as best I could.
If you are having trouble let's say echoing html code then most definitely you are having trouble with escaping characters.
For instance:
echo "a href="something" /a this won't work.
echo "a href=\"something\" /a this will work, notice the .
you have two options either use preg_replace or use a variable to save the value
please see php documentation for further info

how to eval() a segment of a string

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.

Categories