Log in

View Full Version : How to Rename file while uploading in PHP



ksamir2004
04-10-2008, 07:36 AM
Hi All,

I am posting code to you...
please help us..

my Question is: while uploading file i need to rename file name(special character should not be there like *, ? ,/ ,-)
example: sam-file / 21-11-08.xls

Ans should be: samfile221108.xls

So i am pasting code:

--------------------------------------------
File name is : upload_rename.php
-----------------------------------------------
<html><head>name this file</head>

<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="upload_rename.php " method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>Single File Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile" type="file" id="ufile" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

<?php
$file_name=$HTTP_POST_FILES['ufile']['name'];

$special = array('/','!','&','*',' ','-');

$new_file_name = str_replace(' ',' ',str_replace($special,'',$file_name));
echo '['.$new_file_name.']';

$path= "uploads/File/".$new_file_name;

if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
?>
</body>
</html>

Thanks
in advance..

Please mail this code after correction..

Thanks
Sam

thetestingsite
04-10-2008, 10:32 PM
The only thing I could see wrong with this code is this line:



$new_file_name = str_replace(' ',' ',str_replace($special,'',$file_name));


it should be like so:



$new_file_name = str_replace($special,'',$file_name);


If you are having problems with it, please post either a link to the problem page or post what exactly is giving you issues with it.

Hope this helps.