Skip to content

Instantly share code, notes, and snippets.

@zvineyard
Created August 30, 2012 15:29
Show Gist options
  • Select an option

  • Save zvineyard/3530917 to your computer and use it in GitHub Desktop.

Select an option

Save zvineyard/3530917 to your computer and use it in GitHub Desktop.
PHP: Upload and Rename File
<form action="" enctype="multipart/form-data" method="post">
<input id="file" name="file" type="file" />
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
<?php
// Upload and Rename File
if (isset($_POST['submit']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.doc','.docx','.rtf','.pdf');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000))
{
// Rename file
$newfilename = md5($file_basename) . $file_ext;
if (file_exists("upload/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
?>
@danielsdeboer
Copy link
Copy Markdown

Have a look at pathinfo(): http://php.net/manual/en/function.pathinfo.php

It's a lot easier (and less fragile) than calling strpos() and whatnot.

@blackestwhite
Copy link
Copy Markdown

thanks man!

@alexfrenk
Copy link
Copy Markdown

hello, I would like to use this that after loading any png image with the result after the upload must always be "image.png", I can not

@Bk201Freelance
Copy link
Copy Markdown

Bk201Freelance commented Oct 21, 2018

Hi!
Thank you for this code very simple than mine.

One thing, I don't understand how it deal with "$allowed_file_types = array('.doc','.docx','.rtf','.pdf');"

Can you give me some explanations, please?

Thank you

EDIT: Do not matter about my question, I just didn't read carefully your code. Thank you.

@subrotoice
Copy link
Copy Markdown

good job

@sefakor20
Copy link
Copy Markdown

Thanks, the code was very helpful to me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment