Recently, I had to set up a scheduled task on a server, which is a little intimidating and scary the first time around, so here’s a quick article about the steps for setting up a basic cron job. In this article, we’ll create a simple PHP script to send out an email once per day.

Prerequisites
  • Basic command line familiarity.
  • Ability to SSH into a Linux server.
Goals
  • Learn how to set a basic scheduled task (cron job) in a Linux server environment.
  • Set a cronjob to send out an email every day at a specified time.

Sending an Email from PHP

First, we can make a simple PHP script to test. I’m going to make a file that sends a simple email to myself.

<?php
$to = 'me@example.com';
$message = 'This is the message.';
$subject = 'Insert Subject Here';
$headers = 'From: noreply@example.com' . "\r\n" .
           'Reply-To: me@example.com';

@mail($to, $subject, $message, $headers);
?>

If you’re not familiar with the mail() function in PHP, here is the official documentation. I’m setting variables for who the e-mail should send to, where it should come from, the subject, a message, and headers. This is not the most up-to-date or secure way to send an email, but it’s a script that works so I’m going to use it for testing. I’m just going to save this as cron.php.

The path to your public facing folder will depend on the Linux distro, but for the sake of this tutorial I’ll put it in /var/www/html/crontest. Therefore, the full path to my script will be /var/www/html/crontest/cron.php. You can test this script directly from your browser by hitting the file. If your website is example.com, it would most likely be example.com/crontest/cron.php. If you load the file and get an email, you know the script works.

localhost is not set up to send out PHP mail, so this script needs to be run from a live Linux environment.

#linux #snippets #server

Setting Up a Basic Cron Job on a Linux Server
1.20 GEEK