What are the best practices for handling subdomain configurations in PHP applications to avoid errors like invalid URLs?

When handling subdomain configurations in PHP applications, it is important to validate the subdomain input to avoid errors like invalid URLs. One way to do this is by using regular expressions to ensure that the subdomain follows a valid format. Additionally, it is recommended to sanitize and validate any user input to prevent malicious attacks or unexpected behavior.

// Validate subdomain input using regular expressions
$subdomain = $_GET['subdomain'];
if (!preg_match('/^[a-zA-Z0-9-]{1,63}$/', $subdomain)) {
    // Handle invalid subdomain input
    die("Invalid subdomain");
}

// Sanitize and validate user input
$subdomain = filter_var($subdomain, FILTER_SANITIZE_STRING);

// Use the sanitized subdomain in your application logic
echo "Subdomain: " . $subdomain;