Create txt file with jQuery - preserve line breaks - php

I use jQuery to serve a link where users can download a .txt file. jQuery just gets the content of a textarea and sets it as the href attribute. This is necessary because the content of the textarea is set with the response of an ajax call.
The download of the file works like this:
$(document).on('click', '#download', function(){
$(this).attr('href','data:text/plain;charset=utf-8,' + encodeURIComponent( $('#kundendaten').val() ) );
});
One part of the Ajax call response is the textarea:
$kundendaten = '<textarea id="kundendaten">';
$kundendaten .= 'Name: '. $_POST['nachname'] .' '. $_POST['vorname'] . PHP_EOL;
$kundendaten .= 'Email: '. $_POST['email'] . PHP_EOL;
$kundendaten .= '</textarea>';
On Mac OS I get a .txt file with line breaks and everything is fine. On Windows though the line breaks are missing in the .txt file. I also tried \n instead of PHP_EOL but there was no difference.
Any idea how I can solve this?

PHP_EOL only works to the system it is running on, so if your website is hosted on a linux box, it will do the EOL to a linux standard.
The following would be your best bet.
$kundendaten = '<textarea id="kundendaten">' . "\r\n";
$kundendaten .= 'Name: '. $_POST['nachname'] .' '. $_POST['vorname'] . "\r\n";
$kundendaten .= 'Email: '. $_POST['email'] . "\r\n";
$kundendaten .= '</textarea>' . "\r\n";
Also if you are using this a lot throughout a file I would create a constant referencing "\r\n" and use that. (If I remember the syntax correctly, as follows;
DEFINE("_EOL", "\r\n");

Related

how to line break in php

($message = 'EmailAddress : ' . $username . '-Accessed on : '.date("Y-m-d") . '-Time : ' . $datetime .'';)
This is my code it's made for sending messages to mailing someone using my login form. result going on like this (EmailAddress: dula#gmail.com-Accessed on 2021-02-23-Time: 10:59 AM) email data and time now I need to line break for before (Accessed on) I used <br\> \r\n but it's not working can you help me, someone, please...
($message = 'EmailAddress : ' . $username . '-Accessed on : '.date("Y-m-d") . '-Time : ' . $datetime .'';)
for this code how to used line break inside this code ?
You can use p element to automatically creates a new line.
$message = '<p>EmailAddress : '.$username.'</p><p>-Accessed on : '.date("Y-m-d") . '-Time : ' . $datetime .'</p>';
And set the headers to Content-Type to text/html.
header("Content-Type: text/html");
/* i think you suppose to use Content-Type is text/html for br tag when sending mail */

PHP won't echo html code to show a link on page

I have a simple echo statement that's supposed to display a link on the web page, but all it's doing is showing exactly "<a href=website.com>Link</a>" (without the quotes). To me, this should work with no problem. I thought maybe it's because the HTML for the website is in one file while the PHP is in another file.
foreach ($output as $output)
{
echo 'DATE: ' . $output['date'] . "\n";
echo 'TO: ' . $output['to'] . "\n";
echo 'FROM: ' . $output['from'] . "\n";
echo 'SUBJECT: ' . $output['subject'] . "\n";
echo "<a href=website.com>Link</a>\n\n";
}
Your loop isn't a valid one, you have $output as $output.
I also suggest printing $output before looping through it, to see if it even contains what you think it should.
In your 'a' tag, the actual URL needs to be in quotes
<a href='http://www.website.com'>

PHP variable containing white space causing emails to fail

I am trying to send emails using the PHP mail function, but I am running into issues when it actually sends the email.
For some reason, the $to variable has a space between each character. So when it's emailed, the spaces are filled with dots. The $to email is being grabbed from a TSV file generated from a remote system that I do not control.
I have seen where people have a line where it searches for white space and deletes it but i do not want to go that route.
The CC function works perfectly.
Does anyone know what may be happening? I have seen a couple of threads and bugs but they do not match it exactly.
<?php
$Name= $_POST["Name"];
//File Upload Script
if ($_FILES["file"]["error"] > 0)
{
}
else
{
echo "File name: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["file"]["tmp_name"], "C:/xampp/htdocs/Uploads/" . $_FILES["file"]["name"]);
echo "http://php/Uploads/" . $_FILES["file"]["name"];
}
$URLLink = "C:/xampp/htdocs/Uploads/" . $_FILES["file"]["name"];
//End File Upload Script
//Reading TSV File
$filename = $URLLink;
//Deleting first line and last 5 lines
$alines=file($filename);
$dlines=array_slice($alines,1, -5);
$fileContents=implode($dlines);
$fp=fopen($filename,'w+');
fwrite($fp,$fileContents);
fclose($fp);
//END of Deleting first line and last 5 lines
$filename = $URLLink;
$file = file($filename);
foreach($file as $line)
{
list($start_time, $end_time, $instance, $status, $coordinator) = explode(" ", $line);
$from = $SentFrom;
$to = $coordinator;
$to = str_replace(' ', '', $coordinator);
//$to = str_replace('.', '', $coordinator);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From:" . $from . "\r\n" . "CC:" . $mailer . "," . $emailone. "," . $emailtwo;
$subject = "Test";
include_once("EmailBody.php");
mail($to, $subject, $message, $headers);
}
?>
Page before is a form.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Impact Notification</title>
<link rel="stylesheet" href="../style/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../style/menustyle.css" type="text/css" media="screen" />
<style type="text/css">
.auto-style1 {
font-family: "Lucida Calligraphy";
}
</style>
</head>
<body style="color: #black; background-color: #0000FF;">
<div align="center"id="MainWrapper" style="width: 70%">
<div id="container" style="width:100%">
<div id="PageHeader">
<?php include_once("../template/template_header.php");?>
</div>
<div id="leftcolumn" style="height:auto;width:11%;float:left;padding:15px 15px 15px 15px;">
<?php include_once("../template/menu.php"); ?>
</div>
<div id="content" style="background-color:#EEEEEE;height:auto;width:80%;float:left;">
<h2 class="auto-style1">Email Notification</h2>
<form action="sendemail.php" method="post" name="emails" enctype="multipart/form-data">
<table style="width: 100%">
<tr>
<td>Enter Your Name</td>
<td><input name="Name" type="text" style="width: 300px; height: 24px;" /></td>
<tr>
<td style="width: 180px"><strong>File Upload:</strong></td>
<td><input type="file" name="file" id="file" /></td>
</tr>
</table>
<br />
<input name="Submit" type="submit" value="Submit" /><input name="Clear" type="reset" value="Reset" /><br />
<br />
</form>
</div>
</div>
</div>
Revised Answer: BAD DATA HANDLING!
Whilst it may still be a UTF / Charset issue, according to the code you have provided and sample data, your data handling is incorrect. Here are some tips for you (which have been incorporated into my suggested foreach loops below).
Your text file header contains a number of fields that you would like to retrieve. These are represented as the following fields sequentially in a row, separated by tabs:
Start Time End Time Instance Type Status Endpoint Organizer ....etc
You seem to be wanting a number of these fields to be captured, and amongst them, the $coordinator value needs to contain the data within the organiser field as listed within the text file (which appears to always be an email address):
Looking at your raw tsv file, your "list" processor is processing the wrong variables as you have missed the endpoint field!! Even if you're not going to use it, you'd need to put something in there for it to work the way you have set things up. At the very best, you would be storing the value for endpoint as $coordinator, but I suspect you wouldn't be getting that far because of the way you are exploding (see point 2 below).
The file you submitted seems to be separated by tabs, yet you're exploding using spaces. Change the " " in your explode to "\t". Currently, you're probably getting junk in your variable data (as it is splitting after every space in each line) - the organiser email address is not going to ever make it into $coordinator - perhaps you could echo your variables as a test to see what I mean (and comment out your mail function while you're testing).
I have revised your foreach loop:
foreach($file as $line)
{
list($start_time, $end_time, $instance, $status, $endpoint, $coordinator) = explode("\t", $line);
$from = $SentFrom;
$to = $coordinator;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From:" . $from . "\r\n" . "CC:" . $mailer . "," . $emailone. "," .$emailtwo;
$subject = "Test";
include_once("EmailBody.php"); // Can' really comment on what's going on here - as I don't know what is in this file ! :)
mail($to, $subject, $message, $headers);
}
You are stripping 5 lines from the bottom of the file and one from the top, but I see 6 lines that need to be removed from the bottom and one from the top in your sample file. Perhaps change the -5 to -6. Or alternatively, you could do something like this in your foreach loop to instruct the routine not to send an email if the $coordinator variable is "blank" so it doesn't fail if it reads a blank line, etc:
Alternative ForEach Loop - to stop blank lines within your file causing failures:
foreach($file as $line)
{
list($start_time, $end_time, $instance, $status, $endpoint, $coordinator) = explode("\t", $line);
if (trim($coordinator) !== '')
{
$from = $SentFrom;
$to = $coordinator;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From:" . $from . "\r\n" . "CC:" . $mailer . "," . $emailone. "," .$emailtwo;
$subject = "Test";
include_once("EmailBody.php"); // Can' really comment on what's going on here - as I don't know what is in this file ! :)
mail($to, $subject, $message, $headers);
}
}
You seem to be using a Windows implementation of PHP Mail. You may not have any issues with your current message content - just be aware that any lines starting with a period/fullstop will be removed. If you have any of your message lines starting with a '.', you might need something like this:
$vardata = str_replace("\n.", "\n..", $vardata);
Looking at a hex dump of the file, your data is encoded as UTF-16, which for ASCII data includes a nul character between each character of data. You can convert with iconv()
Note: you need to run this on the original file before you try extracting the data.
$str = file_get_contents('2.tsv');
$result = iconv($in_charset = 'UTF-16LE' , $out_charset = 'UTF-8' , $str);
if (false === $result)
{
throw new Exception('Input string could not be converted.');
}
$result = substr($result, 3); // Strip BOM
file_put_contents('3.tsv',$result);
echo $result;
Alternatively you can use
$str = file_get_contents('2.tsv');
$result = mb_convert_encoding($str, 'ASCII', 'UTF-16LE'); //instead of iconv()
file_put_contents('3.tsv',$result);
I have run both successfully on my development server.
You could use trim(), to strip all sorts of whitespace characters only at the beginning and end of the string. I don't think I've seen it suggested yet.
http://nl1.php.net/trim
This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.

Adding embedded images within mail body phpmailer class

Im trying to embed an image within my message body but it ends up as an attachment
$mailer->Subject = APP_NAME . " - " . $name . " send you and Ad : " . $row['name'];
$mailer->IsHTML(true);
$mailer->AddEmbeddedImage('../images/namDiams.png', 'logoimg', 'namDimes.png');
//footer
$footer = "Regards<br/><br/>";
$footer .= '<table style="width: 95%">';
$footer .= '<tr>';
$footer .= '<td>';
$footer .= "<strong><span style='font-size: 15px'>NamDimes Team</span></strong><br/>
NamDimes<br/>
Contact Number: " . APP_CONTACT . "<br/>
Email: " . APP_EMAIL . "<br/>
Website: " . APP_WEBSITE . "<br/>";
$footer .= '</td>';
$footer .= '<td style="text-align:right">';
$footer .= '<img src=\"cid:logoimg\" />';
$footer .= '</td>';
$footer .= '</tr>';
$footer .= '</table>';
$mailer->Body = $body . $footer;
$mailer->AltBody="This is text only alternative body.";
$mailer->AddAttachment('../' . $row['image_path'], $row['name'] . ".jpg");
i have set everything else, including the addresses, the mail gets send out, logo image that I want embed in the body gets attached as an attachment, anyone know why?
Don't use $mailer->AddEmbeddedImage, but directly add
<img src="http://.../images/namDiams.png" /> instead.
The mail length should be lighter... And it works.
EDIT
I don't know if it will help you but there is a little mistake here :
$mailer->AddEmbeddedImage('../images/namDiams.png', 'logoimg', 'namDimes.png');
Should be
$mailer->AddEmbeddedImage('../images/namDiams.png', 'logoimg', 'namDiames.png');//the last param the second 'a' was missing...
Another topic here
I can confirm that user2189925's answer does work. However, I use the absolute path since the location of the calling script is more likely to change than the location of the image.
e.g.
<img src="C:\folder\images\namDiames.png" />
Faced the same problem, then I decided to replace the following
<img src="img/example.jpg"
with
<img src= "https://mysitename.com/img/example.jpg">
and it worked.
just give path of your image to the mail body eg: (img src="../images/cat.jpeg) it will definately work

What is the best method to return JS within a PHP function?

so I have this PHP function which returns html/js. But I find the method I am using is wrong and not efficient. Is there a better way?
Here is just a simplified version of the code.
function doSomething() {
$speed = 1000;
$duration = 500;
$start = false; // this is a boolean and doesn't work below (not sure why)
$output = '<div class="container">something</div>' . "\r\n";
$output .= '<script type="text/javascript">' . "\r\n";
$output .= 'jQuery(document).ready(function() {' . "\r\n";
$output .= 'jQuery(".container.").cycle({' . "\r\n";
$output .= 'speed : ' . $speed . ',' . "\r\n";
$output .= 'duration : ' . $duration . ',' . "\r\n";
$output .= 'start : ' . $start . "\r\n"; // this doesn't work I think is because of it becoming a string instead of a boolean here.
$output .= '})' . "\r\n";
$output .= '})' . "\r\n";
$output .= '</script> . "\r\n";
return $output;
}
So as you can see above a bunch of output and bunch of linebreaks and basically very hard to maintain and debug. In addition, the START variable isn't working per the comment.
There has to be a better way. I thought about heredocs? But not sure...
Thanks for looking.
I would use something like the following:
function doSomething() {
$speed = 1000;
$duration = 500;
$start = (int)false; // this is a boolean and doesn't work below (not sure why)
$output = <<<END
<div class="container">something</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".container").cycle({
speed : $speed ,
duration : $duration,
start : $start
})
})
</script>
END;
return $output;
}
echo doSomething();
easy to maintain
You could do something like this:
function doSomething() {
$cycleArguments = array(
'speed' => 1000,
'duration' => 500,
'start' => false
);
$output = '<div class="container">something</div>' . "\r\n";
$output .= '<script type="text/javascript">' . "\r\n";
$output .= 'jQuery(document).ready(function() {' . "\r\n";
$output .= 'jQuery(".container.").cycle(' . "\r\n";
$output .= json_encode( $cycleArguments );
$output .= ')' . "\r\n";
$output .= '})' . "\r\n";
$output .= '</script>' . "\r\n";
return $output;
}
And with a combination of json_encode() and heredoc syntax:
function doSomething() {
$cycleArguments = array(
'speed' => 1000,
'duration' => 500,
'start' => false
);
$jsonCycleArguments = json_encode( $cycleArguments );
$output = <<<OUTPUT
<div class="container">something</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".container.").cycle( $jsonCycleArguments );
});
</script>
OUTPUT;
return $output;
}
Another option, still, could be:
function doSomething() {
$cycleArguments = array(
'speed' => 1000,
'duration' => 500,
'start' => false
);
$output = array(
'<div class="container">something</div>',
'<script type="text/javascript">',
'jQuery(document).ready(function() {',
' jQuery(".container.").cycle(' . json_encode( $cycleArguments ) . ');',
'});',
'</script>'
);
return implode( "\r\n", $output );
}
etc...
You can write your code in separate HTML file make AJAX call to that file from php and get code of HTML page in AJAX response use as you want.
Here are a couple of options:
1) at the top of your page (or if you have modularized all JS, and none of it will fire until the bottom of the page, before you call an initialize on anything), have php dump a JSON-encoded multidimensional array, containing all of the data you need on that page, into a single var.
Your JS (stored in static files) will have that var passed into one of the init functions, and will operate on that data.
2) call a php script from the html page src="script.php" from there, store the JS as a separate include, either as a HEREDOC or with template values.
Get your values, plug them into the template and echo the string back.
For this to work, you have to mess with MIME types for this to work properly.
3) rewrite your apache installation to rewrite names, write a routing script which will handle the value grabbing and templates, and return a mime type based on the file-extension which was requested.
This is way-overkill for most sites, but is useful for large sites which want all JS to be external, want JS files to contain dynamic data, AND want all script tags to have regular looking src tags.
An alternative would be to set php to treat ".js" files like php files (but then you need to figure out the type in the script, to set the MIME type).

Categories