How to Read a Text File From a Client Using PHP

By Deborah Lee Soltesz

There are two methods you can use for handling file uploads from a client to a server using PHP. The POST method, used by Web page forms, encodes the file as part of the HTTP request from the client. The PUT method, used by clients like Netscape Composer, writes the file directly to the socket connection established with the server.

POST Method

Step 1

Create a file upload form on your Web page. The action attribute is the path and file name of the PHP file that will be handling the file upload. The MAX_FILE_SIZE input value is the maximum size in bytes you will allow for the uploaded text file.

Upload file:

Step 2

Edit your PHP file. Set the path and file name where the uploaded text file will be saved on the server. The $_FILES array contains information about the uploaded file, referenced using the file input name attribute assigned in the Web page form.$uploaddir = '/srv/www/uploads/';$filename = basename($_FILES['fileupload']['name']);$uploadfile = $uploaddir . $filename;

Step 3

Move the uploaded file from the temporary location where the server stored it to the destination you set for the upload.if (move_uploaded_file($_FILES['fileupload']['tmp_name'], $uploadfile)) { echo $filename . " uploaded. Thank you!\n";} else { echo "Error uploading " . $filename . ": " . $_FILES['userfile']['error'] . "\n";

PUT Method

Step 1

Edit your PHP file. Set the path and file name where the uploaded text file will be saved on the server. The $_SERVER array contains information about the request, including the destination path and file name requested by the client ('REQUEST_URI').$uploaddir = '/srv/www/uploads/';$filename = basename($_SERVER['REQUEST_URI']);$uploadfile = $uploaddir . $filename;

Step 2

Open the input stream to the file data that's being uploaded.$incoming = fopen("php://input", "r");

Step 3

Open a pointer to the destination file where you want to save the uploaded file.$saveto = fopen($uploadfile, "w");

Step 4

Read the data from the incoming stream and write it to the destination file.while ($indata = fread($incoming, 1024)) { fwrite($saveto, $indata);

Step 5

Close the input and file streams.fclose($saveto);fclose($incoming);

Tips & Warnings

  • Multiple files can be uploaded with a single form submission using the POST method. In the Web page form, give each file input field the same name, with square brackets after the input name value (e.g., name="fileupload[]"). Reference each file in your PHP file using a third array index matching the index number of the specific file (e.g., $_FILES['fileupload']['name'][0]).
  • Allowing file uploads to your website poses a considerable security risk. Implement appropriate authentication and security in the server configuration and within your PHP files to ensure only authorized users can upload files, restrict the destination directories for file uploads and provide only the necessary access to uploaded files.