In what ways can PHP scripts be modified to ensure data integrity and security when editing and saving files?

To ensure data integrity and security when editing and saving files in PHP scripts, it is important to sanitize user input, validate data before saving it, and restrict file permissions to prevent unauthorized access.

// Sanitize user input before saving to file
$data = filter_var($_POST['data'], FILTER_SANITIZE_STRING);

// Validate data before saving
if (strlen($data) > 0) {
    // Save data to file
    file_put_contents('file.txt', $data);
}

// Restrict file permissions
chmod('file.txt', 0600);