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.
Related
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 need the PHP response as it is outputted on the php echo.
But when I have a process running, it returns all at once, only after the process has ended.
Is there a way around this?
Thank you in advance
Edit:
This is the ajax after getting the response:
// callback handler called on success
request.done(function (response) {
$('#add--response').html(response);
});
This is the PHP
$count=0;
foreach ($_POST['URLS'] as $url) {
if(!empty($url)){
echo '<div id="conversionSuccess">here is the progress bar for the download</div>';
if (<here I download a file that takes a long time>)
{
echo "success";
}
else
{
echo 'Error!';
}
$count++;
echo "count: ".$count."<br>";
}
}
I want the progress bar visible before the file finishes downloading.
I hope now it makes sense
Without your code, its hard to understand what you're asking or how to help. For better practice, please attach code in your next questions.
However, I'd approach this by building the string in a way you can then later split it and use the response: this meaning -
$response = "";
$response .= $outputOne . "/";
$response .= $outputTwo . "/";
echo $reponse;
Inside your JQuery:
var output = reponse.split("/");
output now becomes an array of each of your output's.
Hope this was relevant and helped.
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.
I'm very new to PHP, and I can't figure out why this is happening.
For some reason, when exit fires the entire page stops loading, not just the PHP script. Like, it'll load the top half of the page, but nothing below where the script is included.
Here's my code:
$page = $_GET["p"] . ".htm";
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
exit;
}
if ($_POST["page"]) {
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_POST["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
exit;
}
if (file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
exit;
}
Even if you have HTML code following your PHP code, from the web server's perspective it is strictly a PHP script. When exit() is called, that is the end of it. PHP will output process and output no more HTML, and the web server will not output anymore html. In other words, it is working exactly as it is supposed to work.
If you need to terminate the flow of PHP code execution without preventing any further HTML from being output, you will need to reorganize your code accordingly.
Here is one suggestion. If there is a problem, set a variable indicating so. In subsequent if() blocks, check to see if previous problems were encountered.
$problem_encountered = FALSE;
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
// Set a boolean variable indicating something went wrong
$problem_encountered = TRUE;
}
// In subsequent blocks, check that you haven't had problems so far
// Adding preg_match() here to validate that the input is only letters & numbers
// to protect against directory traversal.
// Never pass user input into file operations, even checking file_exists()
// without also whitelisting the input.
if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) {
$page = $_GET["p"] . ".htm";
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_GET["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
$problem_encountered = TRUE;
}
if (!$problem_encountered && file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
$problem_encountered = TRUE;
}
There are lots of ways to handle this, many of which are better than the example I provided. But this is a very easy way for you to adapt your existing code without needing to do too much reorganization or risk breaking much.
In PHP 5.3+ you can use the goto statement to jump to a label just before the ?> instead of using exit in the example given in the question.
It would'n work well with more structured code (jumping out of functions), tough.
Maybe this should be a comment, who knows.
I've recently posted here accessing $_SESSION when using file_get_contents in PHP about a problem I was having and the general consensus is that I'm not doing it right... while I generally think "as long as it works..." I thought I'd get some feedback on how I could do it better...
I was to send the exact same email in the exact same format from multiple different areas.
When a job is entered (automatically as a part of the POST)
Manually when reviewing jobs to re-assign to another installer
The original script is a php page which is called using AJAX to send the work order request - this worked by simply calling a standard php page, returning the success or error message and then displaying within the calling page.
Now I have tried to use the same page within the automated job entry so it accepts the job via a form, logs it and mails it.
My problem is (as you can see from the original post) the function file_get_contents() is not good for this cause in the automated script...
My problem is that from an AJAX call I need to do things like include the database connection initialiser, start the session and do whatever else needs to be done in a standalone page... Some or all of these are not required if it is an include so it makes the file only good for one purpose...
How do I make the file good for both purposes? I guess I'm looking for recommendations for the best file layout and structure to cater for both scenarios...
The current file looks like:
<?php
session_start();
$order_id = $_GET['order_id'];
include('include/database.php');
function getLineItems($order_id) {
$query = mysql_query("SELECT ...lineItems...");
//Print rows with data
while($row = mysql_fetch_object($query)) {
$lineItems .= '...Build Line Item String...';
}
return $lineItems;
}
function send_email($order_id) {
//Get data for current job to display
$query = mysql_query("SELECT ...Job Details...");
$row = mysql_fetch_object($query);
$subject = 'Work Order Request';
$email_message = '...Build Email...
...Include Job Details...
'.getLineItems($order_id).'
...Finish Email...';
$headers = '...Create Email Headers...';
if (mail($row->primary_email, $subject, $email_message, $headers)) {
$query = mysql_query("...log successful send...");
if (mysql_error()!="") {
$message .= '...display mysqlerror()..';
}
$message .= '...create success message...';
} else {
$query = mysql_query("...log failed send...");
if (mysql_error()!="") {
$message .= '...display mysqlerror()..';
}
$message .= '...create failed message...';
}
return $message;
} // END send_email() function
//Check supplier info
$query = mysql_query("...get suppliers info attached to order_id...");
if (mysql_num_rows($query) > 0) {
while($row = mysql_fetch_object($query)) {
if ($row->primary_email=="") {
$message .= '...no email message...';
} else if ($row->notification_email=="") {
$message .= '...no notifications message...';
} else {
$message .= send_email($order_id);
}
}
} else {
$message .= '...no supplier matched message...';
}
print $message;
?>
make a function and include it
Do separate functions. Authentication (which requires sessions) from mail sending (which don't)
Then include mail sending function into both tasks.