What are the best practices for handling external data and file paths in PHP scripts to prevent errors and security risks?

When handling external data and file paths in PHP scripts, it is important to sanitize user input to prevent SQL injection and other security risks. Use functions like `mysqli_real_escape_string()` to escape user input before using it in database queries. Additionally, always validate and sanitize file paths to prevent directory traversal attacks by using functions like `realpath()` or `basename()`.

// Example of sanitizing user input for database queries
$user_input = $_POST['user_input'];
$escaped_input = mysqli_real_escape_string($connection, $user_input);

// Example of validating and sanitizing file paths
$file_path = $_GET['file_path'];
$real_path = realpath('uploads/' . basename($file_path));