How can PHP developers implement user consent mechanisms, such as cookie-based opt-ins, when embedding external scripts on websites?

When embedding external scripts on websites, PHP developers can implement user consent mechanisms by using cookie-based opt-ins. This involves setting a cookie when a user gives consent to load external scripts, and checking for this cookie before loading the scripts. If the user has not given consent, the scripts should not be loaded.

<?php
// Check if user has given consent
if(isset($_COOKIE['external_scripts_consent']) && $_COOKIE['external_scripts_consent'] === 'true') {
    // Load external scripts here
    echo '<script src="https://example.com/external-script.js"></script>';
} else {
    // Display a message or alternative content
    echo 'Please consent to load external scripts.';
}
?>