问题
every book and article that i've read recommend that we should rename upload file for security purpose. let say i have a code like this:
if (!isset($error)) {
$file = $_FILES['images'];
$real_pic_name = $_FILES['images']['name'];;
// Create a tmp_name for the file:
$tmp_name = sha1($file['name']) . uniqid('',true);
// Move the file to its proper folder but add _tmp, just in case:
$dest = PDFS_DIR . $tmp_name . '_tmp';
if (move_uploaded_file($file['tmp_name'], $dest)) {
//insert into database with a prepared statement
$stmt = $pdo->prepare('INSERT INTO users (real_pic_name, tmp_name, dateAdded) VALUES (:real_pic_name, :tmp_pic_name, now())');
$stmt->execute(array(
':real_pic_name' => $real_pic_name,
':tmp_pic_name' => $tmp_name
));
// Rename the temporary file:
$original = PDFS_DIR . $tmp_name . '_tmp';
$dest = PDFS_DIR . $tmp_name;
rename($original, $dest);
// Print a message:
echo '<div class="alert alert-success"><h3>The file has been uploaded!</h3></div>';
} else {
trigger_error('The file could not be moved.');
unlink ($file['tmp_name']);
}
}
the problem is i'm confuse about what is a better way to display the images files because i don't think that renaming the file isn't good idea. I'm thinking about add some extra column in my mysql to save the extension and then maybe put in in session to call the images file, i don't know. can anyone give me some solution or sample code that can help me since most of tutorial that i've read only explain about uploading and renaming file name and not the file extension neither display the upload files. thanks.
回答1:
Try to use this code
$temp = explode(".",$_FILES["file"]["name"]);
$newfilename = rand(1,99999) . '.' .end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename;
来源:https://stackoverflow.com/questions/27616475/renaming-an-upload-file-and-display-it