Download File in PHP & Upload File in PHP

Hi guys, we are going to take a look on how to use PHP to download file from server.
The following code explains how to upload and download file in PHP.

Let’s jump into the coding part.

PHP Download File Script

PHP-download-file-script

Demo Video:

 

1.  Code to upload and display all the files in the server

index.php


<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
$sdb=mysql_select_db("uploadphp",$conn) or die(mysql_error());
if(isset($_POST['submit'])!=""){
 $name=$_FILES['photo']['name'];
 $size=$_FILES['photo']['size'];
 $type=$_FILES['photo']['type'];
 $temp=$_FILES['photo']['tmp_name'];
 $caption1=$_POST['caption'];
 $link=$_POST['link'];
 move_uploaded_file($temp,"upload/".$name);
$insert=mysql_query("insert into upload(name)values('$name')");
if($insert){
header("location:index.php");
}
else{
die(mysql_error());
}
}
?>
<html>
<head>
<title>Upload And Download Files In PHP</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>

<h3><p align="center">Upload And Download Files In PHP</p></h3> 
<form enctype="multipart/form-data" action="" name="form" method="post">
<table border="0" cellspacing="0" cellpadding="5" id="table">
<tr>
<th >Upload File</th>
<td ><label for="photo"></label>
<input type="file" name="photo" id="photo" /></td>
</tr>

<tr>
<th colspan="2" scope="row"><input type="submit" name="submit" id="submit" value="Submit" /></th>
</tr>
</table>
</form>
<br />
<br />
<table border="1" align="center" id="table1" cellpadding="0" cellspacing="0">
<tr><td align="center">Download File</td></tr>
<?php
$select=mysql_query("select * from upload order by id desc");
while($row1=mysql_fetch_array($select)){
 $name=$row1['name'];
 $id=$row1['id'];
?>
<tr>
<td width="300">
<?php echo $id;?>. <a href="download.php?filename=<?php echo $name;?>"><?php echo $name ;?></a><td align="center"><a href="delete.php?id=<?php echo $row1["id"]; ?>">Delete</a></td>
</td>
</tr>
<?php }?>
</table>
</body>
</html>

 

2. Script to download file from the server

download.php


<?php
function output_file($file, $name, $mime_type='')
{
if(!is_readable($file)) die('Error');

$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==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
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 1997 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 - can not open file.');
die();
}
set_time_limit(0);
$file_path='upload/'.$_REQUEST['filename'];
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>

 

3. Delete file from server

delete.php


<?php 
$conn=mysql_connect("localhost","root","") or die(mysql_error());
$sdb=mysql_select_db("uploadphp",$conn) or die(mysql_error());
$id=$_REQUEST['id'];
$query = "DELETE FROM upload WHERE id=$id"; 
$result = mysql_query($query) or die ( mysql_error());
header("Location: index.php"); 
 ?>

 

Attachments

Insert Update Delete In PHP

Hi guys, we are going to take a look on how to insert, update & delete in PHP with Mysql database.
Whatever application or technology it may be inserting, updating and deleting operations are a key.
Let’s jump into the coding part.

insert-update-delete-in-php

Demo Video:

 

1. Configuration file to connect to database.

config.php

<?php
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('samplephp');
if (!$select_db){
die("No database selected" . mysql_error());
}
?>

 

2. View all recorded data from the database.

index.php

<?php 
require('config.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>View Data</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<center><p><a href="insert.php">Insert New Data</a></p>
<h2>View Data</h2></center>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr><th><strong>No</strong></th><th><strong>Name</strong></th><th><strong>City</strong></th><th><strong>Phone</strong></th><th><strong>Update</strong></th><th><strong>Delete</strong></th></tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="Select * from sample ORDER BY id asc;";
$result = mysql_query($sel_query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr><td align="center"><?php echo $count; ?></td><td align="center"><?php echo $row["name"]; ?></td><td align="center"><?php echo $row["city"]; ?></td><td align="center"><?php echo $row["phone"]; ?></td><td align="center"><a href="edit.php?id=<?php echo $row["id"]; ?>">Update</a></td><td align="center"><a href="delete.php?id=<?php echo $row["id"]; ?>">Delete</a></td></tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>

 

3. Insert record into the database.

insert.php

<?php
require('config.php');
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$name =$_REQUEST['name'];
$city =$_REQUEST['city'];
$phone = $_REQUEST['phone'];
$ins_query="insert into sample(`name`,`city`,`phone`)values('$name','$city','$phone')";
mysql_query($ins_query) or die(mysql_error());
$status = "New Record Inserted Successfully.</br></br><a href='index.php'>View Inserted Record</a>";
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert New Data</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<center><p><a href="index.php">View Data</a></p></center>
<div>
<h2>Insert New Data</h2></center>
<form name="form" method="post" action=""> 
<input type="hidden" name="new" value="1" />
<p><input type="text" name="name" placeholder="Enter Name" required /></p>
<p><input type="text" name="city" placeholder="Enter City" required /></p>
<p><input type="text" name="phone" placeholder="Enter Phone" required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#FF0000;"><?php echo $status; ?></p>
</div>
</div>
</body>
</html>

 

4. Update record in the database.

edit.php


<?php 
require('config.php');
$id=$_REQUEST['id'];
$query = "SELECT * from sample where id='".$id."'"; 
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Data</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="insert.php">Insert New Data</a></p>
<h1>Update Data</h1>
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$id=$_REQUEST['id'];
$name =$_REQUEST['name'];
$city =$_REQUEST['city'];
$phone =$_REQUEST['phone'];
$update="update sample set name='".$name."',city='".$city."', phone='".$phone."' where id='".$id."'";
mysql_query($update) or die(mysql_error());
$status = "Data Updated. </br></br><a href='index.php'>View Data</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
header("Location: index.php");
}else {
?>
<div>
<form name="form" method="post" action=""> 
<input type="hidden" name="new" value="1" />
<input name="id" type="hidden" value="<?php echo $row['id'];?>" />
<p><input type="text" name="name" placeholder="Enter Name" required value="<?php echo $row['name'];?>" /></p>
<p><input type="text" name="city" placeholder="Enter City" required value="<?php echo $row['city'];?>" /></p>
<p><input type="text" name="phone" placeholder="Enter Phone" required value="<?php echo $row['phone'];?>" /></p>
<p><input name="submit" type="submit" value="Update" /></p>
</form>
<?php } ?>
</div>
</div>
</body>
</html>

 

5. Delete record from the database.

delete.php

<?php 
require('config.php');
$id=$_REQUEST['id'];
$query = "DELETE FROM sample WHERE id=$id"; 
$result = mysql_query($query) or die ( mysql_error());
header("Location: index.php"); 
 ?>

 

6. Sql database file.

samplephp.sql


CREATE TABLE IF NOT EXISTS `sample` (
`id` int(50) NOT NULL,
 `name` varchar(100) NOT NULL,
 `city` varchar(100) NOT NULL,
 `phone` varchar(100) NOT NULL
)

INSERT INTO `sample` (`id`, `name`, `city`, `phone`) VALUES
(15, 'John Doe', 'New York City', '6544375554'),
(16, 'Alex Texas', 'California', '6456778888'),
(17, 'Leo Moosa', 'London', '123456789'),
(18, 'Pedro Santos', 'Madrid', '2345087665');