How to upload file in php and send filename to database?
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script. The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
tmp_name is the temporary name of the uploaded file which is generated automatically by php, and stored on the temporary folder on the server. name is the original name of the file which is store on the local machine.
The filesize() function in PHP is an inbuilt function which is used to return the size of a specified file. The filesize() function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.
<?php
if (isset($_FILES['file']))
{
$file = $_FILES['file'];
// File Properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
// Work out the file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png', 'jpg');
//filename
$id = 'uploads/Test';
if (!file_exists($id))
{
mkdir($id, 0777, true);
}
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) {
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = $id .'/'. $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
echo $file_destination;
}
}
}
}
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With