File Upload With Renaming Using PHP

by Hiroshi on June 17, 2008

in File Upload

This example takes a name and file. Uploads it to upload directory and rename it name_filename if file name is ‘name’. If the file name is cat and you have typed animal then script will rename the file as animal_cat.

Form Code

<form method="post" enctype="multipart/form-data" action="uploadit.php">
<input type="text" name="name1" id="name1">
<input type="hidden" name="action" value="upload">
Upload image:
<input type="file" name="picThumbnail"><br />
<input type="submit" value="upload">
</form>

PHP Code

<?php
	if ($_FILES['picThumbnail']['name'] != "")
	{
		$sUploadDir = 'upload/';
		$sUploadedFile = $sUploadDir . basename($_FILES['picThumbnail']['name']);
		if (move_uploaded_file($_FILES['picThumbnail']['tmp_name'], $sUploadedFile))
		{
		$sThumbnail = $_FILES['picThumbnail']['name'];
					$sThumbnail = $name1."_".$sThumbnail;
					$sFileName = strtolower(($sThumbnail));
					if (file_exists(($sUploadDir.$_FILES['picThumbnail']['name'])))
						rename(($sUploadDir.$_FILES['picThumbnail']['name']), ($sUploadDir.$sFileName));
		echo "file uploaded successfully";
		}
	}
?>

Precautions

  • CHMOD ‘upload’ folder to 777 if it is at online server
  • Use enctype=”multipart/form-data” in form tag

Upoad File With Rename Script Download

Related Posts

Previous post:

Next post: