useful php codes

Helpful PHP Codes for Efficiency


1. Clean Logs Created Under /home

If you need to clean all logs created under /home with filenames like cron.php?2323 every 12 hours, you can achieve this using a cron job.

Step 1: Create a file named clean-cron-logs.php and add the following code:

array_map('unlink', glob("../cron.php?*"));

Step 2: Add this file to your cron jobs:

/usr/bin/php /home/public_html/clean-cron-logs.php

This setup ensures that all matching log files are deleted every 12 hours.


2. Change Moodle’s Root Path

To change Moodle’s root path, you can modify the config.php file.

Step 1: Locate the line below in config.php:

$CFG->wwwroot = 'http://yourdomain.com';

Step 2: Change it to the desired path:

$CFG->wwwroot = 'http://yourdomain.com/the_path_to_be_the_root';

Remember to comment out the previous line to keep track of the change:

//$CFG->wwwroot = 'http://yourdomain.com';

3. Dynamic Root Path Based on Domain

To set Moodle’s root path dynamically based on the client’s domain, you can use the following code:

if (false !== strpos($_SERVER['HTTP_HOST'], "yourrefdomain")) {
    $CFG->wwwroot = 'https://yourrefdomain.com';
} else {
    $CFG->wwwroot = 'https://yournormaldomain.com';
}

This allows Moodle to serve different root paths depending on the domain from which the client is accessing the site.


Why These PHP Codes Are Useful

These PHP snippets address common challenges that developers face in managing server environments and web applications:

  • Automated Log Cleanup: Ensures your server stays clean without manual intervention.
  • Flexible Moodle Configuration: Makes it easier to adapt your Moodle installation to new requirements.
  • Dynamic Domain Handling: Streamlines multi-domain setups and simplifies configuration.

By implementing these snippets, you can improve the efficiency and reliability of your projects.


More Practical PHP Tips

If you found these snippets helpful, here are some additional ideas to explore:

  • Email Automation: Use PHP libraries like PHPMailer to send secure and formatted emails.
  • Error Handling: Implement robust error logging using PHP’s try-catch blocks and log files.
  • Database Optimization: Write efficient SQL queries and integrate them seamlessly with PHP’s PDO.

For more useful PHP tips, tricks, and real-world examples, stay tuned to our blog!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *