0% found this document useful (0 votes)
20 views

File Upload

Uploaded by

BAKAMO
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

File Upload

Uploaded by

BAKAMO
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

File upload in PHP

• File upload in PHP allows you to upload files with


different extensions to the server.
• We can use HTML forms and enable the users to
upload files to the server.
• These files are stored in a temporary directory unless
moved to a target location for permanent storage. But
for the file upload in PHP to work, we have to ensure
some configuration settings are set appropriately.
• In your "php.ini" file, search for
the file_uploads directive, and set it to On:
• file_uploads = On
How to Configure PHP Settings to Ensure Smooth File
Upload in PHP?
• If you are aware of the php.ini file location, it’s
well and good. But if you don’t know the exact
location, use the below code to locate it.
• <? php echo php_ini_loaded_file(); ?>
• php_ini_loaded_file() is a built-in function.
Create a PHP file with this code and open it
from your browser through a local server to get
the location of the php.ini file.
• Once you have the location, you need to find
and configure some settings.
The primary settings along with recommended
values are:
• Allows file uploads
file_uploads = On
Temporary directory where upload files are temporarily stores
upload_tmp_dir =
• Max file size approval
: upload_max_filesize = 16M
• Max files upload allowed per request
: max_file_uploads = 20
• POST data max size accepted by PHP
: post_max_size = 20M
• max_input_time = 60
• memory_limit = 128M
• max_execution_time = 30
$_FILES
• $_FILES is a super global variable which can be
used to upload files. Here we will see an
example in which our php script checks if the
form to upload the file is being submitted and
generates a message if true.
$_FILES superglobal in PHP
• The $_FILES superglobal in PHP is used to
handle file uploads through an HTML form
• You need an HTML form to allow users to
choose and upload files.
• The form should use the POST method with
enctype="multipart/form-data" to properly
handle file uploads.
enctype="multipart/form-data
• The enctype attribute specifies how the form-
data should be encoded when submitting it to
the server.
• Note: The enctype attribute can be used only
if method="post".
• use multipart/form-data when your form
includes any <input type="file"> elements
enctype="multipart/form-data"
$files[] in PHP
• In PHP, $files[] typically refers to an array that
holds multiple file data, such as those
uploaded via an HTML form using the $_FILES
superglobal. The $_FILES array contains
information about uploaded files and allows
you to manage them effectively
Structure of $_FILES
• When a file is uploaded using an HTML form
with enctype="multipart/form-data", PHP
populates the $_FILES array. The structure
looks like this for a single file:
'tmp_name'
• In PHP, 'tmp_name' is a key within the $_FILES
superglobal array, which refers to the
temporary file path where the uploaded file is
stored on the server during the file upload
process.
• When a user uploads a file via an HTML form,
PHP stores the file in a temporary directory on
the server. The 'tmp_name' value contains the
path to that temporary file.
$fileName = $_FILES["fileUpload"]["name"];

• $fileName = $_FILES["fileUpload"]["name"];
• Description: This retrieves the original name of the
file that the user uploaded from their computer.
• Example: If the user uploads a file named
document.pdf, then $fileName will contain the
value "document.pdf".
• Use Case: You can use this to show the original file
name to the user or store it in a database for
reference.
$fileTmpName = $_FILES["fileUpload"]
["tmp_name"];
• Description: This gets the temporary file name
and path that the server uses to store the
uploaded file before you move it to a
permanent location.
• Example: The value might look something like
"/tmp/phpYzdqkD", which is a temporary path
where the file is stored.
• Use Case: You will typically use this with
move_uploaded_file() to move
$fileSize = $_FILES["fileUpload"]["size"];
• Description: This gives the size of the
uploaded file in bytes.
• Example: If a file is 2MB, then $fileSize might
have the value 2097152 (because 2MB = 2 *
1024 * 1024 bytes).
• Use Case: You can use this to check if the
uploaded file exceeds a certain size limit and
reject it if it's too large
$fileType = $_FILES["fileUpload"]["type"];

• Description: This retrieves the MIME type of the


uploaded file, which describes the type of file.
• Example: Common MIME types are:"image/jpeg"
for JPEG images"application/pdf" for PDF
files"text/plain" for text files
• Use Case: You can use this to ensure that only
certain types of files (e.g., images or PDFs) are
allowed for upload. This helps with security and
maintaining file-type consistency.
$fileError = $_FILES["fileUpload"]["error"];

This checks for any errors that may have


occurred during the file upload.
•Use Case: This is useful for checking if the
file was successfully uploaded or if an error
occurred during the process.
PHP uses specific error codes to indicate what went wrong (if anything)

• Example of Error Codes:


• 0 (UPLOAD_ERR_OK): No error, the upload was successful.
• 1 (UPLOAD_ERR_INI_SIZE): The uploaded file exceeds the
upload_max_filesize directive in php.ini.
• 2 (UPLOAD_ERR_FORM_SIZE): The uploaded file exceeds
the MAX_FILE_SIZE directive that was specified in the
HTML form.
• 3 (UPLOAD_ERR_PARTIAL): The file was only partially
uploaded.
• 4 (UPLOAD_ERR_NO_FILE): No file was uploaded.
mkdir()
• The PHP function mkdir() is used to create
directories in the filesystem.
• <?php
mkdir("test");
?>
The mkdir() function creates a directory
specified by a pathname.
Permission Breakdown
• 7 (Owner): Read (r), Write (w), Execute (x) — Full
permissions.
• 5 (Group): Read (r), Execute (x), but no write
permission.
• 5 (Others): Read (r), Execute (x), but no write
permission.
• In summary, 0755 makes the directory accessible
for reading and executing by everyone, but only
the owner can write (modify) the files inside it.
pathinfo(path, options)
• The pathinfo() function returns
information about a file path.
Creating the HTML Form for File Upload in PHP
• <?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP File Upload</title>
</head>
<body>
<?php
if (isset($_SESSION['message']) && $_SESSION['message'])
{
printf('<b>%s</b>', $_SESSION['message']);
unset($_SESSION['message']);
}
?>
<form method="POST" action="fileUpload.php" enctype="multipart/form-data">
<div>
<span>Upload a File:</span>
<input type="file" name="uploadedFile" />
</div>
<input type="submit" name="uploadBtn" value="Upload the File" />
</form>
</body>
</html>
Creating the Upload Logic for File Upload in PHP
<?php
session_start();
$message = '';
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload the File')
{
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
{
// uploaded file details
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
// removing extra spaces
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
// file extensions allowed
$allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc');
if (in_array($fileExtension, $allowedfileExtensions))
{
// directory where file will be moved
$uploadFileDir = 'C:\xampp\htdocs\test';
$dest_path = $uploadFileDir . $newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path))
{
$message = 'File uploaded successfully.';
}
else
{
$message = 'An error occurred while uploading the file to the destination directory. Ensure that the web
server has access to write in the path directory.';
}
}
else
{
• $message = 'Upload failed as the file type is not acceptable. The allowed file types are:' .implode(',',
$allowedfileExtensions);
}
}
else
{
$message = 'Error occurred while uploading the file.<br>';
$message .= 'Error:' . $_FILES['uploadedFile']['error'];
}
}
$_SESSION['message'] = $message;
header("Location: index.php");
Resolving the Common Errors That May Be
Encountered While a File Upload in PHP
• Some standard errors are:
1. The File Is Too Large-UPLOAD_ERR_INI_SIZE or
UPLOAD_ERR_FROM_SIZE errors
2. Temporary Folder is Missing--
UPLOAD_ERR_NO_TMP_DIR error
UPLOAD_ERR__NO_FILE error
3. Partial Upload--UPLOAD_ERR_PARTIAL error
4. Can’t Write to Disk--UPLOAD_ERR_CANT_WRITE
error
5. A PHP Extension Stopped the File Upload
UPLOAD_ERR_EXTENSION
Creating an html form
• Next, create an HTML form that allow users to c
<!DOCTYPE html>
<html>
<body>

<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>
Upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

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;
}
}
• You will need to create a new directory called
"uploads" in the directory where "upload.php"
file resides. The uploaded files will be saved
there.
Check if File Already Exist

if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
• Limit File Size

• we want to check the size of the file. If the file


is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type

• if($imageFileType != "jpg" &&


$imageFileType != "png" && $imageFileType !
= "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files
are allowed.";
$uploadOk = 0;
}
Now complete it
<?php

$target_dir = "uploads/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;

$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

if(isset($_POST["submit"])) {

$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

if($check !== false) {

echo "File is an image - " . $check["mime"] . ".";

$uploadOk = 1;

} else {

if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

if ($_FILES["fileToUpload"]["size"] > 500000) {


echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]
["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Php sending E-mails()
• The mail() function allows you to send emails
directly from a script.
syntax
• mail(to,subject,message,headers,parameters);
To: Required. Specifies the receiver / receivers of
the email
Subject: Specifies the subject of the email.
Message: Defines the message to be sent. Each
line should be separated with a LF (\n). Lines
should not exceed 70 characters.
• Headers: Optional. Specifies additional
headers, like From, Cc, and Bcc. The additional
headers should be separated with a CRLF (\r\
n).
• Parameters: Optional. Specifies an additional
parameter to the sendmail program (the one
defined in the sendmail_path configuration
setting).
• <?php
$msg = "First line of text\nSecond line of text";
$msg = wordwrap($msg,70);
mail("[email protected]","My subject",
$msg);
?>
• The mail() function allows you to send email
directly from a script.
• https://github.com/mailhog/MailHog/releases
• Accessing the mailhog
• http://localhost:8025
• Configure PHP to use MailHog:
• Open PHP.ini
• Search mail function and replace
• Localhost:25 with Localhost:1025
• <?php
$to=‘[email protected]’;
$subject=‘test Email’;
$message=‘this is a test email using MailHog on Windows’;
$headers=‘From: [email protected].’”\r\n”;
‘Reply –To: [email protected]’.”\r\n.
‘X-Mailer:PHP/’.phpversion();
If (mail($to,$subject,$message,$headers))
{
echo ‘Email sent successfully!’;
}
Else
{
echo ‘Failed to send email.’;
}
?>
Task
• Create a simple image gallery system in PHP
where users can upload images.
• a).Once uploaded, the images should be
stored on the server and displayed in a grid
format on the webpage.
• b).Ensure that only images of type JPEG, PNG,
and GIF are accepted, and enforce a maximum
file size of 3MB.

You might also like