How can PHP scripts detect the origin of POST data and prevent manipulation from external sources?

PHP scripts can detect the origin of POST data by checking the HTTP referer header. This header contains the URL of the page that sent the request. To prevent manipulation from external sources, you can compare the referer header with the expected origin URL and only process the data if they match.

if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == 'https://www.example.com/form.php'){
    // Process the POST data
    $data = $_POST['data'];
    // Additional processing code
} else {
    // Handle unauthorized access
    echo "Unauthorized access!";
}