What best practices should be followed when concatenating strings to generate URLs in PHP?

When concatenating strings to generate URLs in PHP, it is important to properly handle any leading or trailing slashes to ensure that the resulting URL is correctly formatted. One common mistake is forgetting to include a slash between the base URL and the additional path segments, which can lead to broken URLs. To avoid this issue, it is recommended to use PHP's rtrim() and ltrim() functions to remove any extra slashes before concatenating the strings.

$baseURL = "https://example.com";
$path = "/products";

// Remove any trailing slash from the base URL
$baseURL = rtrim($baseURL, '/');

// Remove any leading slash from the path
$path = ltrim($path, '/');

// Concatenate the base URL and path to generate the complete URL
$url = $baseURL . $path;

echo $url;