View uploaded file in php
|
I'm having some issues with uploading files from HTML to a PHP based web server. The following is my HTML code. No issues here I believe.
PHP code:
I can't figure out how to make it work in PHP. I've been trying several different ways and the above code is just my latest desperate attempt at figuring it out by trying to store the value into a new variable. What I want to do is the following:
Any kind of hint or help in any way would be greatly appreciated. Thanks! PS. It's not going live, so any security issues are irrelevant at the moment. Hi! In this tutorial let me show you about upload, view and download file in php and mysql. The file uploading process is similar to what we have discussed here, but this php script not only uploads file to the server but also stores the file path and its created date in mysql database. Apart from uploading file, it also gives you the option to view file on browser and download it from server. With PHP you can practically upload any type of files and the file uploading script I have shared below will work for all file types like PDF, Document, Images, MP3, Videos, Zip archives etc. Just include those file extensions in the filtering process ( How to Upload, View & Download File in PHP & MySQL?Let's move on to the coding part. First you should create mysql database to store file details. Create MySQL Database:CREATE DATABASE `demo` ; Use `demo`; CREATE TABLE IF NOT EXISTS `tbl_files` ( `id` int(9) NOT NULL AUTO_INCREMENT, `filename` varchar(255) NOT NULL, `created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1; Next is the database connectivity script that establishes connection to mysql database from php. dbconnect.php<?php
//connect mysql database
$host = "localhost";
$user = "username";
$pass = "password";
$db = "demo";
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_error($con));
?>
Then create index.php - this is the main file containing user interface. It has an upload form and a html table to display the list of uploaded files from database along with 'View' & 'Download' links for them. index.php<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename from tbl_files";
$result = mysqli_query($con, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload View & Download file in PHP and MySQL | Demo</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
</head>
<body>
<br/>
<div class="container">
<div class="row">
<div class="col-xs-8 col-xs-offset-2 well">
<form action="upload.php" method="post" enctype="multipart/form-data">
<legend>Select File to Upload:</legend>
<div class="form-group">
<input type="file" name="file1" />
</div>
<div class="form-group">
<input type="submit" name="submit" value="Upload" class="btn btn-info"/>
</div>
<?php if(isset($_GET['st'])) { ?>
<div class="alert alert-danger text-center">
<?php if ($_GET['st'] == 'success') {
echo "File Uploaded Successfully!";
}
else
{
echo 'Invalid File Extension!';
} ?>
</div>
<?php } ?>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>File Name</th>
<th>View</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['filename']; ?></td>
<td><a href="uploads/<?php echo $row['filename']; ?>" target="_blank">View</a></td>
<td><a href="uploads/<?php echo $row['filename']; ?>" download>Download</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Note: This demo uses twitter bootstrap for css stylesheet. Running index.php will generate a page with upload form and table with files details similar to this. Users can either click on 'View' link to view the files on browser or on 'Download' to download the files from server. Finally there is 'uploads.php' file which will be executed when the form is submitted to upload the selected file. Here is where we actually upload the file to the server from the client machine and save its name and uploaded date into the database. uploads.php<?php
//check if form is submitted
if (isset($_POST['submit']))
{
$filename = $_FILES['file1']['name'];
//upload file
if($filename != '')
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = ['pdf', 'txt', 'doc', 'docx', 'png', 'jpg', 'jpeg', 'gif'];
//check if file type is valid
if (in_array($ext, $allowed))
{
// get last record id
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
if (count($result) > 0)
{
$row = mysqli_fetch_array($result);
$filename = ($row['id']+1) . '-' . $filename;
}
else
$filename = '1' . '-' . $filename;
//set target directory
$path = 'uploads/';
$created = @date('Y-m-d H:i:s');
move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename));
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
This script upload file from local machine to server and stores its details into database and redirects to index.php. If everything goes right you will be able to see success message on completion. If there's any error you will be notified about it. Also Read:
So we have seen about file upload and to view and download them using php and mysql database. If you want you can set the file size limit or restrict users to upload only pdf or images etc. How can I view uploaded files in PHP?
In PHP, we can access the actual name of the file which we are uploading by keyword $_FILES[“file”][“name”]. The $_FILES is the by default keyword in PHP to access the details of files that we uploaded. The file refers to the name which is defined in the “index. html” form in the input of the file.
How can I view uploaded image in PHP?
"upload/" . $_FILES["file"]["name"]. "<br>"; $image=$_FILES["file"]["name"]; /* Displaying Image*/ $img="upload/". $image; echo '<img src= "upload/".
How can I recover my uploaded file in PHP?
4 Answers. Sorted by: ... .
Upload form. What does your form tag look like? ... .
Sanitisation. $company = mysql_real_escape_string($_POST['company']); $location = mysql_real_escape_string($_POST['location']); $pic = mysql_real_escape_string($_FILES['userfile']['name']); ... .
SQL Query. ... .
HTML Output..
Where does PHP store uploaded files?
php stores all temporary files, that includes uploaded files, in the temporary files directory as specified in the php. ini.
|
Bài Viết Liên Quan
Hướng dẫn dùng python .t python
Python hiện là một trong những ngôn ngữ lập trình phổ biến nhất thế giới. Python đặc biệt phổ biến trong cộng đồng nghiên cứu. Tuy vậy Python không bị ...
Hướng dẫn gmt php
Để giải quyết vấn đề này có nhiều cách, tuy nhiên trong chuyên đề này mình đi về time trong php nên mình sẽ dùng luôn hàm set lại ...
Hướng dẫn dùng cookie file trong PHP
Cookie cung cấp cho ứng dụng web một phương thức lưu trữ thông tin trên trình duyệt của người dùng và truy xuất khi người dùng gửi yêu cầu xem trang.Cookie ...
Hướng dẫn dùng scalar example trong PHP
By default, Enumerated Cases have no scalar equivalent. They are simply singleton objects. However, there are ample cases where an Enumerated Case needs to be able to round-trip to a database or ...
Hướng dẫn dùng increment trong PHP
#1 AUto increment là 1 tính năng rất phổ biến trong sql nó được sử dụng hầu hết cho tất cả các bạn để tăng ID 1 cách tự động dễ dàng trong việc insert ...
Hướng dẫn insertadjacenthtml js
Trong bài này chúng ta sẽ tìm hiểu hàm insertAdjacentHTML trong javascript, đây là một hàm khá hay và có thể dùng để thay thế cho nhiều hàm khác.Bài viết này ...
Hướng dẫn php delete file
View DiscussionImprove ArticleSave ArticleReadDiscussView DiscussionImprove ArticleSave ArticleTo delete a file by using PHP is very easy. Deleting a file means completely erase a file from a ...
Chi tiết vision 2023
349.000,0₫ƯU ĐIỂM HDPRO LOCKMạch Bật Tắt đèn xe vision 2021 2022, tắt đèn trong 3 giâyTích hợp chức năng passing, từng đó các dòng xe đều passing được như các ...
Hướng dẫn dùng array includes trong PHP
Trang chủHướng dẫn họcHọc PHPPHP include và requireĐịnh nghĩa và cách dùng include và requireinclude hoặc require tiện lợi cho việc sử dụng những phần dùng chung, ...
Hướng dẫn dùng php doc trong PHP
Trong bài học này, mình sẽ hướng dẫn các bạn một số những thao tác cơ bản về thao tác với FILE trong PHP như mở file, lấy dữ liệu, ghi mới, xóa, sửa.Video ...
Hướng dẫn format currency php
Hàm currency_format() giúp bạn dễ dàng hiện thị dữ liệu có định dạng tiền tệ như VNĐ, USD…Cú phápcurrency_format($number[, $suffix = đ])Input: $number: Số cần ...
Hướng dẫn dùng arrayphp trong PHP
Trang chủHướng dẫn họcHọc PHPPHP array thường dùngĐịnh nghĩa và cách dùng PHP arrayPHP count(), đếm số lượng phần tử trong mảngCũng có thể xem là chiều dài ...
Abstract class implements interface php
In every example Ive seen, extended classes implement the interfaces of their parents. For reference, the following example:interface MyInterface{ public function foo(); public function ...
Hướng dẫn php artisan make:auth
Xin chào anh em, như anh em cũng biết là một hệ thống nào cũng cần có xác thực khi thực hiện một hoặc nhiều hành vi mà hệ thống cho phép. Để tiếp tục ...
Hướng dẫn run python on mac
Python là một ngôn ngữ kiểu Mac. Nó loại bỏ nhiều quy ước cú pháp của các ngôn ngữ lập trình truyền thống để ưu tiên mã có thể đọc được của con ...
Hướng dẫn dùng kotlin collections python
Không giống như các ngôn ngữ lập trình khác, Kotlin phân biệt rõ 2 loại Collections(Mutable collections và Immutable collections).Mô hình lớp kế thừa của các Collection ...
Hướng dẫn dùng concatonate python
Hàm concatenate () là một hàm từ gói NumPy. Về cơ bản, hàm này kết hợp các mảng NumPy với nhau. Hàm này về cơ bản được sử dụng để nối hai hoặc nhiều ...
Hướng dẫn dùng microseconds trong PHP
Hàm microtime() sẽ lấy timestamp của thời điểm hiện tại bao gồm cả microseconds.Bài viết này được đăng tại freetuts.net, không được copy dưới mọi ...
Hướng dẫn magic constants in php
PHP cung cấp một số lượng lớn các hằng số được xác định trước cho bất kỳ kịch bản mà nó chạy. Nó có thể được gọi ở bất kỳ nơi đâu trong ...
Hướng dẫn string module python
Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...
