What are the best practices for handling data validation and response generation in PHP scripts?

When handling data validation in PHP scripts, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, generating appropriate responses to user input can improve user experience and provide meaningful feedback.

// Example of data validation and response generation in PHP

// Sanitize and validate user input
$input = $_POST['input'];
$clean_input = filter_var($input, FILTER_SANITIZE_STRING);

if (empty($clean_input)) {
    // Return an error response if input is empty
    $response = ['error' => 'Input cannot be empty'];
} else {
    // Process the input if it is valid
    // Generate a success response
    $response = ['success' => 'Input successfully validated'];
}

// Return the response as JSON
header('Content-Type: application/json');
echo json_encode($response);