Ben Koo
Ben Koo

Reputation: 89

php error with cron job sending email twice perday

I'm a newbie in PHP, I did created a cron job to send mail twice per-day in cPanel:

Minute  Hour    Day     Month   Weekday     Command
  0     0,12    *       *       *           /home/user/public_html/cronjob/send-mail.php

send-mail.php

<?php
$to       = "[email protected]";
$sender   = "[email protected]";
$subject  = "TEST CRONJOB";
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: ".strip_tags($sender)."\r\n";
$headers .= "From: Domain.com <".strip_tags($sender).">\r\n";
$html     = "<html>
                <body style='font-family:arial;'>
                    <p>Have a good day!<br>Test email sent twice per day.</p>
                </body>
            </html>";

mail($to, $subject, $html, $headers);
?>

after few test, I received following error:

/home/user/public_html/cronjob/send-mail.php: line 1: ?php: No such file or directory
/home/user/public_html/cronjob/send-mail.php: line 3: =: command not found
/home/user/public_html/cronjob/send-mail.php: line 4: =: command not found
/home/user/public_html/cronjob/send-mail.php: line 5: =: command not found
/home/user/public_html/cronjob/send-mail.php: line 6: =: command not found
/home/user/public_html/cronjob/send-mail.php: line 7: .=: command not found
/home/user/public_html/cronjob/send-mail.php: line 8: syntax error near unexpected token `('
/home/user/public_html/cronjob/send-mail.php: line 8: `$headers .= "Bcc: ".strip_tags($sender)."\r\n";'

I can sending email by simply running the script, but can't while in cron.

Upvotes: 1

Views: 691

Answers (2)

Rahul
Rahul

Reputation: 1336

When you executed from shell, it worked fine because the system knew that you are executing (through ./) but cron does not know that; so explicitly tell it to execute that file using php.

So in your crontab, replace

/home/user/public_html/cronjob/send-mail.php

with

php -f /home/user/public_html/cronjob/send-mail.php

Upvotes: 1

Raptor
Raptor

Reputation: 54212

Replace your cron tab contents with:

#Minute  Hour    Day     Month   Weekday     Command
  0     0,12    *       *       *           /usr/bin/php /home/user/public_html/cronjob/send-mail.php

Note that the path used in your send-mail.php may need to be changed to absolute path.

Upvotes: 0

Related Questions