Hi,
Today I have a file upload script. The problem is that it does not rename file names, and has a maximum file upload size.
How can I add this to my current script?
$Filename=$_POST['Filename'];
$Name=$_POST['Name'];
$pic=($_FILES['Filename']['name']);
if (isset($_POST['save']) && !empty($_POST['Name']) && !empty($_POST['Category']) && !empty($_POST['Time'])){
$sql = "INSERT INTO View SET MergeID='{$_GET['id']}', Name='{$_POST['Name']}', Category='{$_POST['Category']}', Media='$pic', Time='{$_POST['Time']}'";
mysql_query($sql) or die(mysql_error());
GetFileUpload();
}
function GetFileUpload() {
if (file_exists("Media/" . $_FILES["Filename"]["name"])) {
echo $_FILES["Filename"]["name"] . " file already exist ";
} else {
move_uploaded_file($_FILES["Filename"]["tmp_name"], "Media/" . $_FILES["Filename"]["name"]);
// echo "File: ". basename( $_FILES['Filename']['name']). " has been created.";
}
}
if ($_FILES["Filename"]["size"] < 2000000)
{
if ($_FILES["Filename"]["error"] > 0)
{
echo "Return Code: " . $_FILES["Filename"]["error"] . "<br>";
}
else
{
$rand =rand(1000,9999);
$fname=$rand."-".$_FILES["Filename"]["name"];
move_uploaded_file($_FILES["Filename"]["tmp_name"], "Media/" .$rand );
}
For Ramdon name you can use timestamp along with the filename that will make it unique use the DateTime() function of php.
If you are not using any framework you can set the fileupload limit from php.ini file
or use this
// You should also check filesize here. if ($_FILES['upfile']['size'] > 1000000) { throw new RuntimeException('Exceeded filesize limit.'); }
reference http://www.php.net/manual/en/features.file-upload.php
$_FILES['Filename']['size']
will return you the size of the file in bytes, make a check on it accordingly to your maximum allowed size.
As for the renaming file, I use this piece of function:
function rename_file($file_to_rename)
{
$actual_name = pathinfo($file_to_rename,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($file_to_rename, PATHINFO_EXTENSION);
$name = $actual_name.".".$extension;
$i = 1;
while(file_exists("Media/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name.'_'.$i;
$name = $actual_name.".".$extension;
$i++;
}
return $name; //For example, if file name is 1.jpg, this returns 1.jpg if that file doesn't exist else keeps incrementing like 1_1.jpg, 1_2.jpg etc.
}
function GetFileUpload($new_name) {
move_uploaded_file($_FILES["Filename"]["tmp_name"], "Media/" . $new_name);
// echo "File: ". basename( $_FILES['Filename']['name']). " has been created.";
}
$new_file_name = rename_file($_FILES['Filename']['name']);
GetFileUpload($new_file_name);
GetFileUpload
changed to match with the rename_file
function.