在不运行第一页的情况下将echo语句输出到另一页

时间:2016-05-04 22:09:28

标签: php phpmailer

我正在使用PHPMailer,并且有一个test.php文件。只要在浏览器中重新加载此页面,test.php文件就会执行并发送电子邮件并回显所使用的电子邮件地址。我有一个cronjob设置,每天执行一次。我创建了另一个文件body.php,其中包括:

<?php
$homepage = file_get_contents('http://www.myrealsite.com/mailer/test.php');
echo $homepage;
?>

这会返回我想要的信息,这基本上只是我通过电子邮件发送的输出,但问题是:每次重新加载body.php时,它都会执行test.php文件并再次发送电子邮件。我希望能够重新加载body.php而不运行body.php。我是新来的。

4 个答案:

答案 0 :(得分:0)

你可以通过在你对body.php的调用中添加一个参数来加载body.php而不发送电子邮件:

http://whatever.your.server.is/body.php?send=no

然后,你只需要$ _GET那个参数并实现一个简单的IF:

if (!$_GET['send'] != 'no'){
    //send the e-mail

答案 1 :(得分:0)

你问的是不可能的。您无法使用file_get_contents()运行包含phpmailer代码的文件并在cron作业中使用它。你可以,但这就是为什么它不会以你希望的方式为你服务。

  • 这是一个或另一个。

旁注:用于捕获每封电子邮件地址的方法和数组未知。

所以,基于以下内容,写入文件并从中读取,并检查文件是否首先存在。

<强> body.php

<?php 

if(file_exists('/path/to/email_sent_to.txt')){
    $show_emails = file_get_contents('/path/to/email_sent_to.txt');
    echo $show_emails;
}

您的cron作业文件以及效果:

<?php 

// your phpmailer code

$emails = array("email1@example.com", "email2@example.com", "email3@example.com");

foreach($emails as $value) {

    $value = $value . "\n";
    $file = fopen("email_sent_to.txt", "a");
    fwrite($file, $value);
    fclose($file);

}

以上将写入文件:

email1@example.com
email2@example.com
email3@example.com

<强>脚注:

您可能希望将日期/时间格式用于文件命名约定,否则该文件可能会随着时间的推移而变得相当大。这只是一个建议。

即:

$prefix = "email_logs_";
$date = date('Y-m-H');

$time = date('h_i_s'); 

$logfile = $prefix . $date . "_" . $time . ".log";

会产生类似email_logs_2016-05-23_11_59_40.log的内容。

然后使用PHP的filemtime()函数根据当前编写的文件读取您的文件。

借用这个问题,并在使用日期/时间文件命名约定时使用不同的方法,如我已建议你做的那样:

How to get the newest file in a directory in php

$files = scandir('logfiles', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];

答案 2 :(得分:0)

好吧我明白了。我的cronjob最初是这样的:

0 17 * * * php /var/www/html/mailer/test.php >> /var/www/html/mailer/cron_status.log

这将每天下午5点执行test.php文件并写入此cron_status.log文件。删除一个>并将cronjob更改为:

0 17 * * * php /var/www/html/mailer/test.php > /var/www/html/mailer/cron_status.log

删除cron_status.log中的内容并写入。然后我使用了body.php

$emailLog = file_get_contents("http://www.bartdangus.com/mailer/cron_status.log"); echo $emailLog;

现在显然最好让日志文件包含所有内容,但我需要满足的要求不包括记录所有内容,我只需要在过去24小时内发生的事情。

答案 3 :(得分:-1)

每当你运行body.php时,它都会向test.php发出http请求,因此它会发送电子邮件。如果我理解正确,您希望列出Cron Job运行时向其发送电子邮件的所有电子邮件地址。

因此,如果将结果保存在单独的文本文件中然后在body.php中读取该文件会更好。像这样,在你的cron文件(test.php)中:

$yourFile = fopen("email_logs.txt", "a"); //make sure this file is writeable by php

$fileContents = date('Y-m-d H:i:is')."\r\n"; //write the time of file saved
$fileContents .= 'email_address_here'; //all email addresses here
$fileContents .= '\r\n=======\r\n'; //a separator line.

fwrite($yourFile, "\n". $fileContents);
fclose($yourFile);

在您阅读电子邮件的其他文件中,请执行以下操作:

$emailLog = file_get_contents("http://www.myrealsite.com/mailer/email_logs.txt");