Upload and Download Using PHP
Upload and Download Using PHP
H a m z a S h a r i f Aw a n
18 ARID 5148
OUTLINE
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above:
• Make sure that the form uses method="post"
The form also needs the following attribute:
enctype="multipart/form-data". It specifies which content-
type to use when submitting the form
• Without the requirements above, the file upload will
not work.
Other things to notice:
• The type="file" attribute of the <input> tag shows the
input field as a file-select control, with a "Browse"
button next to the input control
• The form above sends data to a file called
"upload.php", which we will create next.
CREATE THE UPLOAD FILE PHP SCRIPT
THE "UPLOAD.PHP" FILE CONTAINS THE CODE FOR UPLOADING A FILE:
CODE:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
PHP SCRIPT EXPLAINED:
$use_include_path:
it is the optional parameter. It is by default false. You
can set it to true to the search the file in the
included_path.
$context: represents the context stream resource.
<!DOCTYPE html>
<html>
<head>
<title>Download PDF using PHP from HTML
Link</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<center>
<h1 >Welcome to this website </h1>
<p><b>Click below to download PDF </b> </p>
<p1><br> The pdf will imideatly download onclick
</br> </p1>
<a href="newpath.php?file=assignment" target="
">Download PDF Now</a>
</center>
</body>
</html>
CODE:
//Php code
<?php
$file = $_GET['file'] .".pdf";
header("content-disposition: attachment;
filename=". urlencode($file));
$fb = fopen($file, "r"); while(!feof($fb)){ echo
fread($fb, 8295);
flush();
}
fclose($fb);
?>
XAMPP PATH
C:\xampp\php
CONFIGURATION SETTING
CREATING FILES
INDEX.PHP
UPLOADS.PHP
UPLOAD FILE
UPLOADING FILE
DOWNLOAD CODE
FILE DOWNLOADED