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

File Upload

dcacadaccsdvddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddc

Uploaded by

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

File Upload

dcacadaccsdvddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddc

Uploaded by

ramand2523
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Here's a simple PHP program to upload a file to a specific folder.

The code will create a form that


allows users to upload a file, and then it handles the file upload process by saving it in a folder on the
server.

<?php

// Check if the form was submitted

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Folder where files will be uploaded

$targetDir = "uploads/";

// Create the directory if it doesn't exist

if (!is_dir($targetDir)) {

mkdir($targetDir, 0777, true);

// Path of the file to be uploaded

$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);

// Check if the file was successfully uploaded

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {

echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been


uploaded successfully.";

} else {

echo "Sorry, there was an error uploading your file.";

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">


<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>File Upload</title>

</head>

<body>

<form action="" method="post" enctype="multipart/form-data">

<label for="fileToUpload">Select file to upload:</label>

<input type="file" name="fileToUpload" id="fileToUpload">

<input type="submit" value="Upload File" name="submit">

</form>

</body>

</html>

Explanation

1. HTML Form: The form uses enctype="multipart/form-data" to handle file uploads.

2. Target Directory: The script creates an uploads folder if it doesn't already exist.

3. File Upload: The PHP code uses the move_uploaded_file() function to save the file to the
specified directory.

4. Validation: It checks for successful uploads and displays an appropriate message.

Steps to Use

1. Save the PHP file on your server (e.g., upload.php).

2. Make sure the server has permissions to write to the directory where the files will be
uploaded.

3. Access the page in your browser, choose a file to upload, and click the "Upload File" button.
The file should be saved in the uploads directory.

function basename()
The function basename() in PHP is used to return the base name of a file from a given path. In the
context of $_FILES["fileToUpload"]["name"], it extracts just the filename from the complete file
path.

Explanation

In the file upload process:

$_FILES is a superglobal array that holds information about files uploaded via the HTTP POST
method.

$_FILES["fileToUpload"]["name"] contains the original name of the file on the client machine (e.g.,
example.txt).
Using basename() ensures that only the filename itself is used, without any path information that
might be accidentally or intentionally included by the user.

Example

If a user uploads a file with the name C:\Users\User\Documents\example.txt, the value of


$_FILES["fileToUpload"]["name"] might include the entire path (although this is generally rare). To
prevent any issues, basename() extracts only the file name like this:

$fileName = basename($_FILES["fileToUpload"]["name"]);

echo $fileName; // Output: example.txt

Why It's Important

Using basename() helps protect against directory traversal attacks, where a malicious user might try
to manipulate the file path to upload files to unintended locations on the server. By ensuring that
only the base filename is used, the server won't be tricked into saving files outside the intended
directory.

move_uploaded_file() function
The move_uploaded_file() function in PHP is used to move an uploaded file to a new location on the
server. This function ensures that the file is properly handled and securely moved from the
temporary location where PHP stores uploaded files to a permanent directory specified by the
developer.

Explanation of the Parameters:

The function takes two parameters:

1. $_FILES["fileToUpload"]["tmp_name"]: This is the temporary file path on the server where


the uploaded file is stored initially.

o When a file is uploaded via an HTML form, PHP automatically stores it in a


temporary directory on the server.

o The temporary file's location is accessed using $_FILES["fileToUpload"]


["tmp_name"].

2. Destination Path (e.g., $targetFile): The second parameter is the destination path where
you want to move the uploaded file.

o This is the path where you want to permanently store the file on the server.

How it works:

 When a file is uploaded, PHP stores it in a temporary location for security and processing
purposes.

 The move_uploaded_file() function then moves the file from this temporary location to a
specified directory on your server.

 If the function succeeds, the file is safely stored in the target directory, and the temporary
file is removed.
Code Example

Here's the line from the previous code:

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile);

 $_FILES["fileToUpload"]["tmp_name"]: Represents the temporary file's path on the server.

 $targetFile: Represents the final destination of the file (e.g., uploads/example.txt).

Why It Is Important

1. Security: The move_uploaded_file() function checks that the file is indeed an uploaded file
(for security reasons) before it moves it. This prevents unauthorized manipulation of files on
the server.

2. File Handling: It properly manages the temporary file, ensuring it's transferred to a
permanent location without leaving any residual data behind.

Example Scenario

Suppose a user uploads a file named example.txt:

1. The file is temporarily stored in a location like /tmp/phpYzdqkD.

2. The code move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],


"uploads/example.txt") moves it from /tmp/phpYzdqkD to the permanent location
uploads/example.txt.

If the move is successful, the file is now in the uploads directory, ready for use. If it fails, PHP
generates an error, indicating an issue with the upload process or permissions.

You might also like