PHP - Insert line break in email post - php

I've tried many tests to make this work but can't seem to figure this one out!
A PHP code is called before it sends an email, it checks if placeholders have values in them, then adds them in email. Results I get are all on same line with no line breaks.
Can someone please tell me how to insert a line break in the code?
I've tried the linebreak br with single quotes and double in many places in the code, nothing is working. I've tried the echo code, I get errors.
Each placeholder starts with the IF statement and must end with the value}'; for each one. Where and how can I insert the line break between the IF and value}'; for each?
Thanks a million!
Results come out like this scapbooking20dancing35
instead of:
scapbooking
20
dancing
35
if you guys had to put a line break in this code, how does it go? cheers if($_POST['form']['age'] != '') $modAdminEmailText .= '{age:caption}: {age:value}';
/* Retrieve the admin email text */
$modAdminEmailText = $form->AdminEmailText;
/*Checks if the field has a value and if so, add it to the Email Text*/
if($_POST['form']['hobby'] != '')
$modAdminEmailText .= '{hobby:caption}: {hobby:value}';
if($_POST['form']['age'] != '')
$modAdminEmailText .= '{age:caption}: {age:value}';
/*After the field placeholders are added we will need to replace them with the actual submitted values.*/
$adminEmail['text'] = $modAdminEmailText;
$adminEmail['text'] = str_replace($placeholders, $values, $adminEmail['text']);

been there, done that. Here's what I think is going on.
I've tried the linebreak br ... with single quotes and double.. in many many places in the code, nothing is working.. I've tried the echo code, I get errors, 2 days now no sleep :(
using <br> in your code will only work if you write the e-mail as HTML. Check the documentation for the e-mail library you use to see how you do that.
Now in stead of using <br> you may want to use the \n or \r\n symbol. Beware, that if you use that, then you must enclose your string with double quotes: $somevar."\n"
Alternatively try to use PHP_EOL like this: $somevar. PHP_EOL
I'm not sure how these two methods behave when using string interpolation, but it's worth a try.

Related

PHP variables look the same but are not equal (I'm confused)

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

Regex Extra Line Error

I was having an issue when I input comments into a log table the display would be incorrect.
For example when I input:
1
2
3
It would show up as:
1
2
3
To deal with this problem I commented out some of the code and added this regex line:
//$notes= str_replace("</br>","<br>",$sqlresult['Notes']);
//$notes = str_replace("\r","",$sqlresult['Notes']);
//$notes = str_replace("\n","",$sqlresult['Notes']);
//$notes = str_replace("\\","",$sqlresult['Notes']);
//$notes = str_replace("\r","<P>",$sqlresult['Notes']);
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
However now I am receiving an error when text is pasted from an application that appears as one line is coming up with a lot of extra lines in betweem.
E.g.
Files are.. CDSEYE SUBMIT BY M99-CDSENTD
Display:
Files are...
CDSXEYE
(10 EXTRA BLANK LINES)
SUBMIT BY M99-CDSENTD
Is there anyway I can get the $notes to display input EXACTLY how it is inputted?
The reason you had to use the
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
line in the first place is because there was something wrong with the way you were handling input and storing it in a sql database. We merely plugged that hole by removing that extra newline at the end. If we wanted a true 1 to 1 input to output, we would need to look at the way the data is stored from the input textbox to the sql database. Also how it is being pulled from that database and displayed back to the output. If somebody else wrote this code, then it may take a while to find how that was done.
final answer ended up being:
$notes = trim(preg_replace('/\r\r/', '<br>', $sqlresult['Notes']));
I think the problem lies in the second to last line, where you're replacing \r with <p>, which adds an extra blank line. Try <br> instead.
Your replacing every 2 spaces with a line break (<br>), this would be the reason for your breaks.
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
I suggest remove the above code and then put
echo nl2br($your_text_variable); //in the view

nl2br() not working with my textarea

Can somebody please help me with this problem.
I'm simply trying to display a message from users. The message comes to my database from a textarea. My problem is when I am typing message and formatting it with breaking into paragraphs it is not display in that format and display it as a one long paragraph.
like this.
To change the overall look of your document, choose new Theme elements
on the Page Layout tab. To change the looks available in the Quick
Style gallery, use the Change Current Quick Style Set command.
\r\n\r\nBoth the Themes gallery and the Quick Styles gallery provide
reset commands so that you can always restore the look of your
document to the original contained in your current template.
I tried with nl2br() and strip_tags() but still no luck
The Code from validation message.
// Check for message
if ( !empty ( $_POST['message'])) {
if ( mb_strlen ( $_POST['message'], 'UTF-8') <= 20 ) {
$reg_errors['message'] = 'Your message must be greater than 20 characters';
} else {
$message = mysqli_real_escape_string($dbc, $_POST['message']);
}
} else {
$reg_errors['message'] = 'Message: This field is required.';
}
This is the code I use when select message from db
$message= $row['message'];
$message= nl2br(strip_tags($message));
when echoing $message it print a paragraph like above.
You are doing excessive escaping when adding data into database.
If you are using prepared statements, just remove mysqli_real_escape_string() call from your code.
Otherwise you are doing it twice - som you have to find the place where it happens and remove extra mysqli_real_escape_string() call from your code.
From my understanding, by using mysqli_real_escape_string() you are making it escape the backslashes so at the time of transaction for example \r\n becomes \\r\\n, however, if those have already been escaped by Javascript then what you end up during transaction is \\\\r\\\\n which translates back into html as
a literal backward slash
r
a literal backward slash
n
So you might want to replace them with appropriate characters before adding into your database. Doing that you can pic from a variety of built-in functions such as preg_replace(), strtr(), str_replace()…

Undefined offset 1 in Android using PHP

I've looked around on here quite a bit for an answer to my problem but I can't seem to find anything that helps. I'm building an Android application that needs to access student classes through a php script on the server. Each class is made up of a subject, subject number, and section number stored in a mysql database. I send the subject and subject number separated by a '\n' character ("subject\nnumber") to the php script so that it can find and return all sections under that course. Here's the code my script runs:
$course = explode('\n', $_REQUEST['course']);
$sections=mysql_query("select section from class where subj = '".$course[0]."' and number = '".$course[1]."' order by section");
while($e=mysql_fetch_assoc($sections))
$output[]=$e;
print(json_encode($output));
When I pass in the subject and number through my browser with something like
getSections.php?course=CS\n101
It properly formats it into a JSON string and it works perfectly. But when I try to use it with my app, I get an undefined offset: 1 error at line 2. I've wrapped the input string in other characters to make sure that it was sending the same thing as what I try in my browser and it is. It's really boggling my mind why it's not working the way it should.
It's also saying that $output is undefined but I'm pretty sure that's because the while loop is failing.
Any help would be greatly appreciated.
You need to use double quotes for the explode \n ~ explode("\n", $_REQUEST['course']);
Escape characters like newline (\n) only work in double quotes:
echo '\n' prints \n
whereas echo "\n" will print a new line

PHP to Mysql Line break Question

I am having hard time getting a form submitted textarea where people put in line breaks when they hit enter on their address..For example.
<textarea name="address"></textarea>
I am using this to get the post
$address = mysql_real_escape_string(trim($_POST['address']));
They are entering 123 test <return>city,state.
Then after they submit, in the mysql database the address is showing 123 testnrcity state
So how can I handle this?
Thanks!
Use nl2br?
$address = mysql_real_escape_string(trim(nl2br($_POST['address'])));
HTH :)
Have you checked what's in your database field? Just show the database contents with phpMyAdmin or a similar tool. The line break can either be a line break character or two characters: \n. If it's the latter, then your input probably was escaped twice. Or is it just "n". Then there is probably another escaping somewhere along the way. Do you use a database abstraction layer? Maybe it escapes the values too.
I was not able to resolve this the way I wanted to and just settled with using str_replace() to replace all "\r\n" stuff with a space...

Categories