Skip to content
PHP Logo

How can PHP developers ensure that file names with spaces are properly displayed in URLs?

File names with spaces can cause issues in URLs because spaces are not valid characters in URLs and can lead to broken links or errors. To properly display file names with spaces in URLs, PHP developers can use the urlencode() function to encode the file name before including it in the URL. This function replaces spaces with "%20" which is the URL encoding for a space.

php
$filename = "file name with spaces.txt";
$encoded_filename = urlencode($filename);
$url = "http://example.com/files/" . $encoded_filename;
echo $url;