I am trying to use the php mail function to send an email. However, I am not sure how to structure the message part. I am processing an HTML form and I want that to be the message of the html. How could I wrap all of the output in a variable that I can pass as the message argument to the mail() function?
MY PHP:
//Contact Information
$array = $_POST['contact'];
echo '<hr>CONTACT INFORMATION<hr>';
foreach ($array as $key=>$value) {
if ($value != NULL) {
echo '<strong>' . $contact[$key] . '</strong><br/>';
echo $value . '<br/><br/>';
}
}
//Services Information
$array = $_POST['services'];
echo '<hr>SERVICES INFORMATION<hr>';
foreach ($array as $key=>$value) {
if ($value != NULL) {
echo '<strong>' . $services[$key] . '</strong><br/>';
echo $value . '<br/><br/>';
}
}
//Background Information
$array = $_POST['background'];
echo '<hr>BACKGROUND INFORMATION<hr>';
foreach ($array as $key=>$value) {
if ($value != NULL) {
echo '<strong>' . $background[$key] . '</strong><br/>';
echo $value . '<br/><br/>';
}
}
//Services Needed
$value = $_POST['servicesneeded'];
$value = rtrim($value, ", ");
echo '<hr>WHICH SERVICES ARE YOU INTERESTED IN?<hr>';
echo $value;
//Goals
$value = $_POST['goals'];
$value = rtrim($value, ", ");
echo '<hr>WHAT IS THE CORE PURPOSE OF YOUR PROJECT?<hr>';
echo $value;
if (!empty($_POST['goalsOther'])) {
echo '<br/>OTHER: ' . $_POST['goalsOther'];
}
........ I have about a dozen or so of these codeblocks
This isn't really a question about php mail, but more about concatenation. To solve your problem, create a variable, let's call it $message. Then, instead of echoing things out, append them to $message. So, instead of echo '<strong>' . $background[$key] . '</strong><br/>';, you'd have $message .= '<strong>' . $background[$key] . '</strong><br/>';.
I think it will be much easier for you to use SwiftMailer or PHPMailer
They both have a really easy to use API for sending emails using SMTP or php mail() function.
best of luck.
As mentioned by Brian Ray you should create a variable containing the message text that is later being sent using the mail() function. Depending on your server setup you may retrieve the content of the output buffer (things you have echo'd out before) and instead of sending it to the browser load it into a variable. Here's a sample how this could be achieved:
ob_start(); // enable output buffering
ob_clean(); // if content has been buffered before, discard it
// this would contain your echo() statements
echo(...);
...
// load the data from the output buffer into a variable
$message= ob_get_contents();
ob_clean(); // remove the buffered contents from the output buffer
// send the mail:
// PLEASE add security measures to avoid being used as spambot; I would strongly
// recommend to not allow any user input for the $recipient variable or
// additional header variable (if applicable)
mail($recipient, $subject, $message);
Things to keep in mind: output buffering is not always available and the output buffer differs from server to server. If the buffer limit is reached, the server will automatically flush the data (=send it to the browser), in that case you will find no or truncated data inside the output buffer. The method is OK in cases you are in full control of your server, do not allow direct access to the mail routine and can make sure that the buffer is sufficiently sized to contain the generated output.
Some additional reading on output control and ob_get_contents.
Related
I have this code snippet:
foreach ($data as $key => $value) {
$result = $this->_restFetch($value);
$mode[$key] = $result[0]->extract;
}
Just some basic code that runs in a for loop sending a request to some API.
It takes time to finish the script, so I'd like to output some text to the user while the script is executing, something like bellow:
foreach ($data as $key => $value) {
print "Started importing $value \r\n";
$result = $this->_restFetch($value);
$mode[$key] = $result[0]->extract;
print "Finished importing $value \r\n";
}
I've tried various approached with ob_ commands but none of them worked.
Any ideas?
After each print line, you have to put flush(), so the content would be printed out immediately. Good to keep in mind that the browser needs to have some minimum data to display (about .5Kb). I have put both ob_flush() and flush() because in that way you are sure that output will be shown. More on flush() and ob_flush() you can see in this topic PHP buffer ob_flush() vs. flush().
usleep function you can use to delay execution of code for debugging purposes.
foreach ($data as $key => $value) {
print "Started importing $value \r\n";
usleep(3600); // if you are debugging, otherwise just comment this part
ob_flush();
flush();
$result = $this->_restFetch($value);
$mode[$key] = $result[0]->extract;
print "Finished importing $value \r\n";
usleep(3600); // if you are debugging, otherwise just comment this part
ob_flush();
flush();
}
I've been looking up how I can debug PHP code in Chrome or Firefox but I can;t really find a solution. This is my PHP:
<?php
if(isset($_POST["data"]))
{
$var = $_POST["data"];
print "your message: " . $_POST["data"];
if(!empty($_POST['ip.data'])){
$data = $_POST['ip.data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
}
?>
I want to be able to see the output of print "your message: " . $_POST["data"]; or any errors in Chrome or Firefox. I've tried Firefox Quantum that should be able to debug php? Anyways, how can I console log this?
The first step is to recognize that PHP, which is generally a server side language is a completely different context than the browser's console, which is fundamentally Javascript. Thus, to show messages to the browser's console from the server, you will need to find some way to communicate those messages (e.g., errors) to the browser.
At that point, you might consider something as simple as embedding a script tag with your PHP:
function debugToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.debug( \"PHP DEBUG: $msg\" );</script>";
}
function errorToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.error( \"PHP ERROR: $msg\" );</script>";
}
function warnToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.warn( \"PHP WARNING: $msg\" );</script>";
}
function logToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.log( \"PHP LOG: $msg\" );</script>";
}
# Convenience functions
function d2c ( $msg ) { debugToBrowserConsole( $msg ); }
function e2c ( $msg ) { errorToBrowserConsole( $msg ); }
function w2c ( $msg ) { warnToBrowserConsole( $msg ); }
function l2c ( $msg ) { logToBrowserConsole( $msg ); }
if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
if ( isset( $_POST['data'] ) ) {
d2c( "Your message: {$_POST['data']}"
e2c( "This is an error from PHP" );
w2c( "This is a warning from PHP" );
l2c( "This is a log message from PHP" );
...
}
}
But this will be a fundamentally weak and brittle approach. I would suggest instead tailing your log files on the server directly. If you are after some color, consider using clog, lwatch, or grc:
$ grc tail -f /var/log/syslog
echo "console.log( 'Debug Objects: " . $output . "' );";
I ran through the same problem recently, just couldn't find a simple enough way without installing some large external package.
I first tried the obvious way:
<?php echo "<script>console.log(".$myVar.")<script>" ?>
but it only works with scalar types. For example:
<?php
$arr = [ 'x' => 42 ];
echo "<script>console.log(".$arr.")</script>";
?>
will output to the html
<script>console.log(Array)</script>
a solution to this is to use json_encode on the variable in the php side, then JSON.parse it in the javascript and finally console.log.
However this approach fails to capture non public properties of objects:
<?php
class Test {
private $x = 42;
public $y = 13;
}
$obj = json_encode(new Test());
echo "<script>console.log(JSON.parse('".$obj."'))</script>";
?>
will output to the browser console:
{y: 13}
Because private/protected fields can't be accessed by json_encode.
The solution here is either to add a __toString method to your class where you properly expose those fields as strings, or use some hack like calling var_export then process the output string to make it json_encode-able.
I ended up writing a small helper using the latter approach, and an output prettifier in the javascript side
Leaving the link here if anyone wants to use it.
If you want to see errors on an Ubuntu machine and you run an Apache server, you can constantly monitor and output changes to the error.log file in the apache folder with this command:
tail -f /var/log/apache2/error.log
If you have a server running on apache then this will output any errors occurred.
The tail command simply outputs the last 10 lines of a file and updates when new data is piped into the file.
I hope will help:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Try this
<?php
function temp()
{
if(isset($_POST["data"]))
{
$var = $_POST["data"];
print "your message: " . $_POST["data"];
if(!empty($_POST['ip.data'])){
$data = $_POST['ip.data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
}
}//function
?>
<script>
console.log(".<?php temp(); ?>.");
</script>
On Chrome, you can use phpconsole which works quite well.
If anybody knows of something similar for Firefox Quantum please comment.
this is my first time using PHP, so I'm here because I don't even know how to look for the information I want (function name's, properties, etc). As I said before, my code receives a string with two variables and uploads it to a log with the format:
Raw time data, var1, var2
So, I want to add some lines that allow the code to send an "OK" confirmation when data has been successfully posted. How can I get it?
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "<pre>";
echo "hello! \n";
$file = 'measures.txt';
$time = time();
$row = "$time";
if ( isset( $_GET["T"] ) )
{
$new_measure = $_GET["T"];
echo "Temperature: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
if ( isset( $_GET["H"] ) )
{
$new_measure = $_GET["H"];
echo "Humidity: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
file_put_contents($file, "$row\n", FILE_APPEND | LOCK_EX);
echo "</pre>";
?>
Julio,
in your file_put_contents function you could simply echo a " OK" message if the file is successfully stored in the location you set. Now if you are trying to do email confirmation you would need to setup a mail function within your php application and have the proper smtp configurations so your server can do that.
I am assuming you have verification checks before the file is given to your file_put_contents function.
I am writing a PHP script that will send via a cron an email every night. In this script, I have multiple functions which output particular text. I am then trying to send the contents of those functions in the email. For some reason the email is going through fine, but the body of the content is showing up empty. If there's a better way to do this, by all means I'm open to it.
function function1() {
global $new;
echo "<p>";
while ($row = mysql_fetch_array($query)) $content = $row["COUNT(column1)"];
if ($content != 0) echo "output1";
else echo "output2";
echo "</p>";
}
$emailMessage = function1().function2().function3();
if ($_GET['version'] == "email") {
mail ($emailTo, $emailSubject, stripslashes($emailMessage));
}
else echo $emailMessage;
Obviously the code is obfuscated a bit, but the general outline is there.
echo sends the output to the standard out, it doesn't return it from the function. Try this.
ob_start()
// run function contents, including echo
var message = ob_get_clean();
return message;
This will capture what you echo into the buffer, prevent the buffer from being sent, and then reading the buffer into a variable. It will then empty the buffer ready for next time.
I'm trying to write a script which downloads all mail in a certain folder without a custom flag, let's call the flag $aNiceFlag for now; after I've fetched a mail I want to flag it with $aNiceFlag. However before tackling the flag problem I've got a problem to extract the content i need from the mail right now.
This is the information I need:
Sender (email and name if possible)
Subject
Receiver
Plain text body (if only html is available I will try convert it from html to plaintext)
Time sent
I can easily get the subject by using $mailObject->subject. I'm looking at the Zend Documentation but it's a bit confusing for me.
Here's my code right now, I'm not supposed to echo out the content but that's just for now while testing:
$this->gOauth = new GoogleOauth();
$this->gOauth->connect_imap();
$storage = new Zend_Mail_Storage_Imap(&$this->gOauth->gImap);
$storage->selectFolder($this->label);
foreach($storage as $mail){
echo $mail->subject();
echo strip_tags($mail->getContent());
}
I'm accessing the mail using google oAuth. $this->label is the folder I want to get. It's quite simple for now but before making it to complex I want to figure out the fundamentals such as a suitable way to extract all above listed data into separate keys in an array.
You can get the headers for sender, receiver and date quite easily using the same technique you used for the subject, however the actual plaintext body is a bit more tricky, here's a sample code which will do what you want
$this->gOauth = new GoogleOauth();
$this->gOauth->connect_imap();
$storage = new Zend_Mail_Storage_Imap(&$this->gOauth->gImap);
$storage->selectFolder($this->label);
// output first text/plain part
$foundPart = null;
foreach($storage as $mail){
echo '----------------------<br />'."\n";
echo "From: ".utf8_encode($mail->from)."<br />\n";
echo "To: ".utf8_encode(htmlentities($mail->to))."<br />\n";
echo "Time: ".utf8_encode(htmlentities(date("Y-m-d H:s" ,strtotime($mail->date))))."<br />\n";
echo "Subject: ".utf8_encode($mail->subject)."<br />\n";
foreach (new RecursiveIteratorIterator($mail) as $part) {
try {
if (strtok($part->contentType, ';') == 'text/plain') {
$foundPart = $part;
break;
}
} catch (Zend_Mail_Exception $e) {
// ignore
}
}
if (!$foundPart) {
echo "no plain text part found <br /><br /><br /><br />\n\n\n";
} else {
echo "plain text part: <br />" .
str_replace("\n", "\n<br />", trim(utf8_encode(quoted_printable_decode(strip_tags($foundPart)))))
." <br /><br /><br /><br />\n\n\n";
}
}