How can paths and variables be properly assigned in PHP scripts to avoid security violations?

To properly assign paths and variables in PHP scripts to avoid security violations, it is important to sanitize user input to prevent injection attacks and validate input to ensure it matches the expected format. Additionally, use predefined constants for sensitive information like database credentials and avoid hardcoding them directly in the script.

// Sanitize user input to prevent injection attacks
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Validate input to ensure it matches the expected format
if (preg_match("/^[a-zA-Z0-9]+$/", $user_input)) {
    // Proceed with processing the input
} else {
    // Handle invalid input
}

// Use predefined constants for sensitive information
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');