This code works fine besides one problem after it generates a random string for the filename it doesn't keep the file extension.
<?php
define("UPLOAD_DIR", "uploads/");
// process file upload
$file = $_FILES["file"];
if ($file["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// verify the file type
$fileType = exif_imagetype($_FILES["file"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
echo "<p>File type is not permitted.</p>";
exit;
}
// ensure a random filename
$name = generateName();
$redirect = "http://rmaltsaar.net/rfile/uploads/" . $name;
// preserve file from temporary directory
$success = move_uploaded_file($file["tmp_name"], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
echo "<p>Your file (" . $name . ") has been uploaded successfully!</p>";
echo "<p>Redirecting to file</p>";
}
// This returns a random string for the filename
function generateName($max = 6) {
$i = 0;
$possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$keys_length = strlen($possible_keys);
$str = "";
while($i < $max) {
$rand = mt_rand(1, $keys_length-1);
$str .= $possible_keys[$rand];
$i++;
}
return $str;
}
?>
<meta http-equiv="refresh" content="8;url=<?php echo $redirect ?>">
So what i'm trying to figure out is how can i make the function generatename not just return a random string for the file but also return the files extension. like this:
return $str . $ext;