Renaming uploaded images
Posted: Wed May 25, 2005 9:52 pm
What I am trying to do is once a user has uploaded an image to the server using the PHP form, I want it to display a link to the image that was just uploaded. In my code, i have that, but what I am trying to do is automatically add a %20 in replace of every space that is in the filename.
For example, if the user uploads the file 'photo 1.jpg', I want the URL to be displayed as http://www.server.com/photo%201.jpg. Here is my code.
Go to http://www.plastikracing.net/images/TSN/images.php to view the page to understand what I am talking about. Feel free to upload a image with a space in the filename to see what I am talking about.
For example, if the user uploads the file 'photo 1.jpg', I want the URL to be displayed as http://www.server.com/photo%201.jpg. Here is my code.
Code: Select all
<html>
<body bgcolor="black" text="white" link="red" alink="red" vlink="red">
<FORM ENCTYPE="multipart/form-data" ACTION="images.php" METHOD="POST">
To upload a file, click 'Browse' to navigate your local hard drive. Only GIF and JPEG file types are supported.<br><br> <INPUT TYPE="file" NAME="userfile">
<INPUT TYPE="submit" VALUE="Upload">
</FORM>
<p>To view the files currently in the directory, <a href="http://www.plastikracing.net/images/TSN/">click here</a>.
</body>
</html>
<?php
$path = "";
$max_size = 500000000;
if (!isset($HTTP_POST_FILES['userfile'])) exit;
if (is_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'])) {
if ($HTTP_POST_FILES['userfile']['size']>$max_size) { echo "The file is too big. Files may not exceed 200 KB.<br>\n"; exit; }
if (($HTTP_POST_FILES['userfile']['type']=="image/gif") || ($HTTP_POST_FILES['userfile']['type']=="image/pjpeg") || ($HTTP_POST_FILES['userfile']['type']=="image/jpeg") || ($HTTP_POST_FILES['userfile']['type']=="image/JPEG")) {
if (file_exists($path . $HTTP_POST_FILES['userfile']['name'])) { echo "The filename already exists. Please choose a different image or rename the image.<br>\n"; exit; }
$res = copy($HTTP_POST_FILES['userfile']['tmp_name'], $path .
$HTTP_POST_FILES['userfile']['name']);
if (!$res) { echo "Your file upload has failed!<br>\n"; exit; } else { echo "Your file has been uploaded successfully!<br>\n"; }
echo "<br><br>To link to your file, please copy the following address:<br><br>";
echo "<a href=\"http://www.plastikracing.net/images/TSN/".$HTTP_POST_FILES['userfile']['name']."\">http://www.plastikracing.net/images/TSN/".$HTTP_POST_FILES['userfile']['name']."</a><br>\n";
} else { echo "<br><br> <font color=\"yellow\">Wrong file type. Only GIF and JPEG file types are supported.</font><br>\n"; exit; }
}
?>