Trong bài viết này mình sẽ hướng dẫn các bạn tạo một trang upload và download file đơn giản sử dụng PHP và MySQL.
Form:
Trong khi để upload file lên server chúng ta cần tạo một HTML form và đồng thời phải chỉ rõ loại content-type được sử dụng khi submit form. "multipart/form-data"
được sử dụng khi form yêu cầu dữ liệu dạng binary, ví dụ như việc upload file. Thuộc tính type="file"
của thẻ input
chỉ rõ tại đó một file được đưa vào. Thường thẻ input
này sẽ đi kèm với một nút Browse
ngay bên cạnh để duyệt đến file cần upload. Bằng cách sử dụng PHP $_FILE
array, chúng ta có thể upload bất kỳ file nào đang có trên thiết bị lên server. Index đầu tiên của PHP $_FILE
array là form input và index thứ hai có thể là name, type, size, tmp_name,error, …
$_FILES["file"]["name"]
: chỉ rõ tên file sẽ upload.$_FILES["file"]["type"]
: kiểu file upload.$_FILES["file"]["size"]
: kích thước của file upload (tính bằng byte).$_FILES["file"]["tmp_name"]
: chỉ rõ file sẽ được lưu tạm trên server.$_FILES["file"]["error"]
: chỉ rõ lỗi của file nếu upload lỗi.
Tăng giới hạn kích thước file upload:
Theo mặc định thì kích thước tối đa file upload chỉ là 8MB. Do đó để thay đổi hạn chế về kích thước file được upload thì chúng ta chỉnh sửa file PHP.ini hoặc htaccess. Hầu hết các nhà cung cấp host đều cho phép ghi đè file PHP.ini hoặc .htaccess để thay đổi các giá trị mặc định.Một vài cài đặt có thể được cấu hình bằng phương thức ini_set()
khi chạy.
Tăng giới hạn kích thước file upload bằng PHP.ini:
upload_max_filesize = 10M ; post_max_size = 20M ; memory_limit = 128M
Tăng giới hạn bằng cách chỉnh sửa file .htaccess:
php_value upload_max_filesize 10M php_value post_max_size 20M php_value memory_limit 128M
Gần như mọi host đều cho phép sửa file .htaccess, cho đó bạn có thể thêm đoạn code trên vào cuối file .htaccess, sau đó lưu lại.
HTML form input:
<form enctype="multipart/form-data" action="" id="wb_Form1" name="form" method="post"> <div class="form-group"> <input type="file" name="photo" id="photo" class="file"> <div class="input-group col-xs-12"> <span class="input-group-addon"><i class="glyphicon glyphicon-picture"></i></span> <input type="text" class="form-control input-lg placeholded" disabled="" placeholder="Upload Image"> <span class="input-group-btn"> <button class="browse btn btn-primary input-lg" type="button"><i class="glyphicon glyphicon-search"></i> Browse</button> </span> </div> </div> <div class="form-group"> <div class="input-group "> <input type="submit" class="btn btn-success" name="submit" value="Submit"> </div> </div> </form>
Database connection:
mysql_select_db('filemgr',mysql_connect('localhost','root',''))or die(mysql_error());
Thêm một số hạn chế khi upload file:
if(isset($_POST['submit'])!=""){ $name=$_FILES['photo']['name']; $size=$_FILES['photo']['size']; $type=$_FILES['photo']['type']; $temp=$_FILES['photo']['tmp_name']; $error = $_FILES['photo']['error']; $date = date('Y-m-d H:i:s'); if ($error > 0) //Check file upload has error { $_SESSION['alert'] = "danger"; $_SESSION['result'] = "<strong>Error:</strong> " . $error . "<br>"; //Sesssio to carry error } else{ if ($size > 500000) { //Check File Size $_SESSION['alert'] = "danger"; $_SESSION['result'] = "<strong>Error:</strong> Maximum file size 5MB!!!<br>"; }else{ $targetPath = "files/".$name; if(file_exists($targetPath)){ // Check whether the file name already exist in the server. $rename_file= rand(01,1000).$name; //Rename the current file $targetPath = "files/".$rename_file; }else{ $rename_file = $name; } move_uploaded_file($temp,$targetPath); $query=$conn->query("INSERT INTO upload (name,rename_file,date) VALUES ('$name','$rename_file','$date')"); if($query){ $_SESSION['alert'] = "success"; $_SESSION['result'] = "<strong>Well done!</strong> File successfully uploaded!!!"; //Session to carry success message } else{ die(mysql_error()); } } } }
Download file bằng PHP:
<!--?php function output_file($file, $name, $mime_type = '') { if (!is_readable($file)) die('File not found!'); $size = filesize($file); $name = rawurldecode($name); $known_mime_types = array( "pdf" =--> "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "php" => "text/plain" ); if ($mime_type == '') { echo $file_extension = pathinfo($file, PATHINFO_EXTENSION); if (array_key_exists($file_extension, $known_mime_types)) { $mime_type = $known_mime_types[$file_extension]; } else { $mime_type = "application/force-download"; } ; } ; @ob_end_clean(); if (ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); header('Content-Type: ' . $mime_type); header('Content-Disposition: attachment; filename="' . $name . '"'); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); header("Cache-control: private"); header('Pragma: private'); header("Expires: Mon, 26 Jul 2017 05:00:00 GMT"); if (isset($_SERVER['HTTP_RANGE'])) { list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2); list($range) = explode(",", $range, 2); list($range, $range_end) = explode("-", $range); $range = intval($range); if (!$range_end) { $range_end = $size - 1; } else { $range_end = intval($range_end); } $new_length = $range_end - $range + 1; header("HTTP/1.1 206 Partial Content"); header("Content-Length: $new_length"); header("Content-Range: bytes $range-$range_end/$size"); } else { $new_length = $size; header("Content-Length: " . $size); } $chunksize = 1 * (1024 * 1024); $bytes_send = 0; if ($file = fopen($file, 'r')) { if (isset($_SERVER['HTTP_RANGE'])) fseek($file, $range); while (!feof($file) && (!connection_aborted()) && ($bytes_send < $new_length)) { $buffer = fread($file, $chunksize); print($buffer); flush(); $bytes_send += strlen($buffer); } fclose($file); } else die('Error - cannot open file.'); die(); } set_time_limit(0); $file_path = 'files/' . $_REQUEST['filename']; output_file($file_path, '' . $_REQUEST['filename'] . '', ''); ?>
Lưu ý:
Có một lưu ý nhỏ là code được viết bằng PHP sử dụng mysql
thay vì mysqli
, do đó các bạn nên chỉnh sửa lại cho phù hợp hoặc chỉ mang tính chất tham khảo. Bài viết được lấy từ: Simple File Manager Using Php Mysql.
Các bạn có thể xem demo và download tại đây.