求助:使用CodeIgniter实现无需表单提交,周末自动查库发邮件
Hey there! I’ve built exactly this kind of scheduled automation with CodeIgniter before, so let’s break down how to make this work without any user-triggered actions like form submits or buttons.
Core Idea
This requirement boils down to three key pieces:
- Scheduled Execution: Use server-side cron jobs (or Windows Task Scheduler) to run a script automatically on weekends.
- Database Check: Fetch and evaluate the target data you need from your database.
- Email Dispatch: Leverage CodeIgniter’s built-in Email library to send notifications based on your data check results.
Step 1: Build Core Functions in CodeIgniter
First, let’s set up the foundational components within your CI app:
1.1 Configure Email Library
You can set email settings globally in application/config/email.php, or configure it dynamically in your controller. Here’s a quick dynamic setup example:
$this->load->library('email'); $config['protocol'] = 'smtp'; $config['smtp_host'] = 'your-smtp-host.com'; $config['smtp_port'] = 587; $config['smtp_user'] = 'your-email@domain.com'; $config['smtp_pass'] = 'your-email-password'; $config['mailtype'] = 'html'; $config['charset'] = 'utf-8'; $this->email->initialize($config);
1.2 Database Query Logic
Create a model (e.g., Email_model.php) to handle your data fetching. For example, if you need to notify users with pending tasks:
class Email_model extends CI_Model { public function get_users_to_notify() { // Adjust this query to match your actual data requirements return $this->db->select('email, username') ->from('users') ->where('has_pending_tasks', 1) ->where('last_weekend_notified !=', date('Y-m-d')) // Avoid same-day duplicates ->get() ->result(); } }
Step 2: Create a CLI-Only Controller Method
We’ll make a controller that can only run via the command line (CLI) — this avoids web request timeouts and is the standard way to run scheduled tasks in CI.
Create application/controllers/Cron.php:
class Cron extends CI_Controller { public function __construct() { parent::__construct(); // Block web browser access for security if (!$this->input->is_cli_request()) { show_404(); } $this->load->model('Email_model'); $this->load->library('email'); } public function send_weekend_notifications() { // Check if today is Saturday (6) or Sunday (7) $current_day = date('N'); if (!in_array($current_day, [6,7])) { log_message('info', 'Skipped: today is not a weekend'); return; } // Fetch target users from database $users = $this->Email_model->get_users_to_notify(); if (empty($users)) { log_message('info', 'No users need weekend notifications this week'); return; } // Send emails to each user foreach ($users as $user) { $this->email->clear(); $this->email->from('notifications@yourdomain.com', 'Weekly Reminder'); $this->email->to($user->email); $this->email->subject('Your Weekend Task Reminder'); $email_body = "Hi {$user->username},\n\nYou have pending tasks waiting for you. Take a moment to wrap them up before the weekend ends!\n\nBest,\nYour Team"; $this->email->message($email_body); if ($this->email->send()) { // Update user's notification status to avoid duplicates $this->db->where('email', $user->email) ->update('users', ['last_weekend_notified' => date('Y-m-d')]); log_message('info', "Notification sent to {$user->email}"); } else { log_message('error', "Failed to send to {$user->email}: " . $this->email->print_debugger()); } } } }
Step 3: Set Up Server-Side Scheduled Task
Now tell your server to run this script automatically on weekends.
For Linux/Unix Servers (Cron Job)
- Open your crontab file with
crontab -e - Add a line to run the script every Saturday and Sunday at 9 AM (adjust time as needed):
0 9 * * 6,7 php /absolute/path/to/your/codeigniter/index.php cron send_weekend_notifications
- Breakdown:
0 9 * * 6,7means "9:00 AM, every day of the month, every month, on Saturday (6) and Sunday (7)". - Replace
/absolute/path/to/your/codeigniterwith your CI project’s actual root folder path.
For Windows Servers (Task Scheduler)
- Open Task Scheduler and create a new task.
- Set the trigger to run weekly on Saturday and Sunday at your desired time.
- Set the action to "Start a program", with the program/script as your PHP executable path (e.g.,
C:\php\php.exe), and add arguments:
C:\path\to\your\codeigniter\index.php cron send_weekend_notifications
Key Best Practices
- CLI Restriction: The controller uses
is_cli_request()to block web access, preventing unauthorized execution. - Logging: Use CodeIgniter’s built-in
log_message()to track runs, successes, and failures — critical for debugging. - Avoid Duplicates: The
last_weekend_notifiedfield ensures you don’t send multiple emails to the same user in one weekend. - Test Manually: Run the script via CLI first to catch issues:
php /path/to/your/codeigniter/index.php cron send_weekend_notifications
内容的提问来源于stack exchange,提问作者Mia

