How to Read a Text File From a Client Using PHP
- 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.
<form enctype="multipart/form-data" action="your.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="64000" />
Upload file: <input name="fileupload" type="file" />
<input type="submit" value="Upload" />
</form> - 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; - 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"; - 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; - 2). Open the input stream to the file data that's being uploaded.
$incoming = fopen("php://input", "r"); - 3). Open a pointer to the destination file where you want to save the uploaded file.
$saveto = fopen($uploadfile, "w"); - 4). Read the data from the incoming stream and write it to the destination file.
while ($indata = fread($incoming, 1024)) {
fwrite($saveto, $indata); - 5). Close the input and file streams.
fclose($saveto);
fclose($incoming);