What are some best practices for manipulating URLs and extracting information from them in PHP?
When manipulating URLs and extracting information from them in PHP, it is important to use built-in functions and libraries to ensure proper handling of the URLs. One common practice is to use the parse_url function to break down the URL into its components such as scheme, host, path, query, and fragment. Additionally, using functions like urlencode and urldecode can help encode and decode URL components safely.
// Example of parsing a URL and extracting information
$url = "https://www.example.com/path/to/page?query=123";
$urlComponents = parse_url($url);
echo "Scheme: " . $urlComponents['scheme'] . "\n";
echo "Host: " . $urlComponents['host'] . "\n";
echo "Path: " . $urlComponents['path'] . "\n";
echo "Query: " . $urlComponents['query'] . "\n";