Skip to main content

Practical-14

Write a PHP Program to Upload File.

Introduction

Writing a PHP program to upload files is a common task that is used to send files from local computers to a remote server securely. This task is important for applications such as mobile and web applications, content management systems, and other applications that have access to the web. This tutorial provides an overview of the steps needed to successfully upload a file to the web.

Before attempting to write the code for file uploads, it is important to understand basic server-side scripting principles, including HTML and Basic PHP syntax. Additionally, the web developer should be familiar with the basics of network security, such as encryption and authentication methods, so that the transfer is secure and private.

Code

//Create directory
mkdir(PATH_TO_UPLOAD_DIRECTORY, 0755);

// Check to see if an upload button was clicked
if (isset($_POST['submit'])) {

// Get the file name
$file_name = $_FILES['file']['name'];

// Get the file extension
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);

// create a new file name by adding a timestamp
$file_name_new = time() . "." . $file_ext;

// Set the upload directory
$upload_dest = PATH_TO_UPLOAD_DIRECTORY . $file_name_new;

// Upload the file
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dest);
}

Output

[Empty in case of code]
Explanation

This code creates a directory with specified permissions and checks if an upload button has been clicked. The $file_name variable stores the name given to the file being uploaded and $file_ext stores the file extension. A new file name is created by adding a timestamp, then $upload_dest variable stores the file path to be uploaded. Finally, move_uploaded_file moves the temporary file stored in $_FILES['file']['tmp_name'] to the file path $upload_dest

Get Help