I'm using PHPMailer, and have a test.php file. Whenever this page is reloaded in the browser, the test.php file executes and sends email messages and echoes the email addresses that were used. I have a cronjob setup for this to execute once a day. I created another file body.php, that includes this:
<?php
$homepage = file_get_contents('http://www.myrealsite.com/mailer/test.php');
echo $homepage;
?>
This returns the information that I want, which is basically just an output of who I emailed, but here is the problem: Every time I reload body.php it executes the test.php file and sends email again. I want to be able to reload body.php without it running body.php. I'm new at this.
You can get body.php to load without sending the e-mail by adding a parameter to your call to body.php:
http://whatever.your.server.is/body.php?send=no
Then, you just need to $_GET that param and implement a simple IF:
if (!$_GET['send'] != 'no'){
//send the e-mail
Okay I figured it out. My cronjob was initially this:
0 17 * * * php /var/www/html/mailer/test.php >> /var/www/html/mailer/cron_status.log
This would execute the test.php file everyday at 5pm and write to this cron_status.log file. By Removing one > and changing the cronjob to:
0 17 * * * php /var/www/html/mailer/test.php > /var/www/html/mailer/cron_status.log
deletes whats in the cron_status.log and writes to it. Then for body.php I just used:
$emailLog = file_get_contents("http://www.bartdangus.com/mailer/cron_status.log");
echo $emailLog;
Now obviously it would be better to have a log file loge everything, but my requirement that I needed to meet does not include logging everything, I just needed what happened in the past 24hrs.
Whenever you run body.php it will make http request to test.php and so it will send email. If I understand you correctly you wish to list all the email addresses to whom the email was sent when Cron Job ran.
So it would be better if you save the results in a separate text file and then in body.php read that file. Like this, in your cron file (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);
In your other file to read the emails, do:
$emailLog = file_get_contents("http://www.myrealsite.com/mailer/email_logs.txt");
What you're asking is impossible. You can't run a file that contains phpmailer code using file_get_contents() and using it in a cron job. You can, but that's why it's not working for you in the way you hoped it would.
It's one or the other.
Sidenote: The method and array used to catch the addresses of each email is unknown.
So, base yourself on the following, which writes to a file and reads from it, and checks if the file first exists.
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;
}
Your cron job file and to the effect of:
<?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);
}
which the above will write to file as:
email1#example.com
email2#example.com
email3#example.com
Footnotes:
You may want to use a date/time format for your file naming convention, otherwise that file may get rather large over time. This is just a suggestion.
I.e.:
$prefix = "email_logs_";
$date = date('Y-m-H');
$time = date('h_i_s');
$logfile = $prefix . $date . "_" . $time . ".log";
which would create something like email_logs_2016-05-23_11_59_40.log.
Then read your file based on the most currently written file using PHP's filemtime() function.
http://php.net/manual/en/function.filemtime.php
Borrowed from this question and using a different approach while using a date/time file naming convention as I already suggested you do:
How to get the newest file in a directory in php
$files = scandir('logfiles', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
Related
So I'm basically creating .txt files with unique filenames and then changing the ext. of the file to .mobileconfig. That's the overall goal but I wanted the files in a different directory, that's not my root directory.
So it's basically an HTML form, then it takes the data submitted through that form, figures out what to do with it here:
<?php
$txt = $_POST['content'];
$UUID = $_POST['UUID'];
$genfile = fopen('./generated/'$UUID.'.txt', w);
file_put_contents('./generated/'$UUID.'.txt', $txt);
rename('./generated/'$UUID.'.txt', './generated/'$UUID.'.mobileconfig');
?>
I had it working, but it was in the same directory as my other files. I've tried the code above, I've tried it using " instead of '. I've tried without the period before the /, and I've tried without the ./ all together.
Is there anything else that I could try besides just moving the .php file to another directory because I do want to set something up where it deletes all the files inside the generated folder every x amount of time.
You have many syntax errors in your code.
Additionally, using file_put_contents() doesn't require that you open the file first.
Lastly, why create a file with a .TXT extension if you're going to rename it immediately afterwards?
Try this:
$txt = $_POST['content'];
$UUID = $_POST['UUID'];
$fname = "./generated/$UUID.mobileconfig";
file_put_contents($fname, $txt);
See the PHP manual for details on variable expansion in double-quoted strings
actual I finished writing my program. Because it is only a plugin and it runs on a external server I still want to see if I get some errors or something else in the console.
I wrote every console input with echo ...;. My question now is if it is possible to get the text of the console?
Because then I could easily safe it in a .txt file and could get access to it from the web :) - Or is there another way to get the console text?
I could probably just say fwrite(...) instand of echo ...;. But this will cost a lot of time...
Greetings and Thank You!
An alternative that could be usefull on windows would be to save all the output buffer to a txt, first check your php configuration for the console app implicit_flush must be off then
<?php
ob_start(); //before any echo
/** YOUR CODE HERE **/
$output = ob_get_contents(); //this variable has all the echoes
file_put_contents('c:\whatever.txt',$output);
ob_flush(); //shows the echoes on console
?>
If your goal is to create a text file to access, then you should create a text file directly.
(do this instead of echoing to console)
$output = $consoleData . "\n";
$output .= $moreConsoleData . "\n";
(Once you've completed that, just create the file:)
$file = fopen('output.txt', 'a');
fwrite($file, $output);
fclose($file);
Of course, this is sparse - you should also check that the file exists, create it if necessary, etc.
For console (commando line interface) you can redirect the output of your script:
php yourscript.php > path-of-your-file.txt
If you haven't access to a command line interface or to edit the cronjob line, you can duplicate the starndar output at the begining of the script:
$fdout = fopen('path-to-your-script.txt', 'wb');
eio_dup2($fdout, STDOUT);
eio_event_loop();
fclose($fdout);
(eio is an pecl extension)
If you are running the script using the console (i.e. php yourscript.php), you can easily save the output my modifying your command to:
php yourscript.php > path/to/log.txt
The above command will capture all output by the script and save it to log.txt. Change the paths for your script / log as required.
I have a directory with a number of subdirectories that users add files to via FTP. I'm trying to develop a php script (which I will run as a cron job) that will check the directory and its subdirectories for any changes in the files, file sizes or dates modified. I've searched long and hard and have so far only found one script that works, which I've tried to modify - original located here - however it only seems to send the first email notification showing me what is listed in the directories. It also creates a text file of the directory and subdirectory contents, but when the script runs a second time it seems to fall over, and I get an email with no contents.
Anyone out there know a simple way of doing this in php? The script I found is pretty complex and I've tried for hours to debug it with no success.
Thanks in advance!
Here you go:
$log = '/path/to/your/log.js';
$path = '/path/to/your/dir/with/files/';
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
$result = array();
foreach ($files as $file)
{
if (is_file($file = strval($file)) === true)
{
$result[$file] = sprintf('%u|%u', filesize($file), filemtime($file));
}
}
if (is_file($log) !== true)
{
file_put_contents($log, json_encode($result), LOCK_EX);
}
// are there any differences?
if (count($diff = array_diff($result, json_decode(file_get_contents($log), true))) > 0)
{
// send email with mail(), SwiftMailer, PHPMailer, ...
$email = 'The following files have changed:' . "\n" . implode("\n", array_keys($diff));
// update the log file with the new file info
file_put_contents($log, json_encode($result), LOCK_EX);
}
I am assuming you know how to send an e-mail. Also, please keep in mind that the $log file should be kept outside the $path you want to monitor, for obvious reasons of course.
After reading your question a second time, I noticed that you mentioned you want to check if the files change, I'm only doing this check with the size and date of modification, if you really want to check if the file contents are different I suggest you use a hash of the file, so this:
$result[$file] = sprintf('%u|%u', filesize($file), filemtime($file));
Becomes this:
$result[$file] = sprintf('%u|%u|%s', filesize($file), filemtime($file), md5_file($file));
// or
$result[$file] = sprintf('%u|%u|%s', filesize($file), filemtime($file), sha1_file($file));
But bare in mind that this will be much more expensive since the hash functions have to open and read all the contents of your 1-5 MB CSV files.
I like sfFinder so much that I wrote my own adaption:
http://www.symfony-project.org/cookbook/1_0/en/finder
https://github.com/homer6/altumo/blob/master/source/php/Utils/Finder.php
Simple to use, works well.
However, for your use, depending on the size of the files, I'd put everything in a git repository. It's easy to track then.
HTH
Hi' I want to forward all the emails(which are come to my inbox) to php script and retrieve email content and save it in a file. So do that I was add email forwarder with piping path correctly.
Address to Forward :tickets#ana.stage.centuryware.org
Pipe to a Program : /home/centuryw/public_html/stage/ana/osticket/upload/api/pipe.php
I have used following script as pipe.php
#!/usr/bin/php –q
<?
/* Read the message from STDIN */
$fd = fopen("php://stdin", "r");
$email = ""; // This will be the variable holding the data.
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
/* Saves the data into a file */
$fdw = fopen("mail.txt", "w+");
fwrite($fdw, $email);
fclose($fdw);
/* Script End */
But there was no output file and all email are bounced to my inbox again. Can anyone help me please?
Make sure the PHP file has the execute bit set (i.e. chmod +x pipe.php).
I know this question is 2 years old but hopefully this will help anybody who stumbles across it as I did.
I had exactly the same issue and I spent ages trying to log errors etc. I then noticed that my script (and this one) had PHP short tags (i.e. <?) and my PHP config file had these turned off. I changed the tag to <?php and the script worked! Obvious but easy to miss...
try the following 2 options to check:
First, your php file must need to have execute permission(from owner group at least), otherwise it won't work.
What did you used when you were using forwarder? You need to mention php compiler path at the beginnig also.
I have recently written an article regarding the full detail process of piping email content to php program , you will may like to have a look. Let me know if you have any more question. Thanks.
Chanaka -
This doesn't address why there is no output file, but...
Don't you want to use a+ in your fopen() call? The w+ argument will delete any content that already exists in your output file.
PS: Have you tried doing a simple test which writes to the output file using dummy text (not the input from an e-mail) as the contents?
Jeff Cohan
I encountered the same problem. However I solved it by specifying the output file with full path name. Instead of just 'mail.text', i entered '/home/username/public_html/mail.txt'.
If this is actually an email box, why not use IMAP (PHP)? There are lots of classes to read the mail with imap # phpclasses.org
Ok so i have a .txt file with a bunch of urls. I got a script that gets 1 of the lines randomly. I then included this into another page.
However I want the url to change every 15 minutes. So I'm guessing I'm gonna need to use a cron, however I'm not sure how I should put it all into place.
I found if you include a file, it's still going to give a random output so I'm guessing if I run the cron and the include file it's going to get messy.
So what I'm thinking is I have a script that randomly selects a url from my initial text file then it saves it to another .txt file and I include that file on the final page.
I just found this which is sort of in the right direction:
Include php code within echo from a random text
I'm not the best with writing php (can understand it perfectly) so all help is appreciated!
So what I'm thinking is I have a
script that randomly selects a url
from my initial text file then it
saves it to another .txt file and I
include that file on the final page.
That's pretty much what I would do.
To re-generate that file, though, you don't necessarily need a cron.
You could use the following idea :
If the file has been modified less that 15 minutes ago (which you can find out using filemtime() and comparing it with time())
then, use what in the file
else
re-generate the file, randomly choosing one URL from the big file
and use the newly generated file
This way, no need for a cron : the first user that arrives more than 15 minutes after the previous modification of the file will re-generate it, with a new URL.
Alright so I sorta solved my own question:
<?php
// load the file that contain thecode
$adfile = "urls.txt";
$ads = array();
// one line per code
$fh = fopen($adfile, "r");
while(!feof($fh)) {
$line = fgets($fh, 10240);
$line = trim($line);
if($line != "") {
$ads[] = $line;
}
}
// randomly pick an code
$num = count($ads);
$idx = rand(0, $num-1);
$f = fopen("output.txt", "w");
fwrite($f, $ads[$idx]);
fclose($f);
?>
However is there anyway I can delete the chosen line once it has been picked?