Posted by: prajapatinilesh | May 8, 2009

Process the uploaded file in php instead of storing it into physical location

Hi,
We are using   move_uploaded_file($_FILES['myFile']['tmp_name'], ‘/upload_files/myFile.txt’);   function in php to upload files into physical location (destination directory).
But in case if you want to process that uploaded file instead of storing it into destination directory then we can use other php function for file handling.
For example:

if (is_uploaded_file($_FILES['myFile']['tmp_name']))
$fileData = file_get_contents($_FILES['myFile']['tmp_name']);

$fileData = str_replace(“A”, “B”, $fileData);

OR
if file size is large then better to use following way: means use of diff file handling functions of php such as fopen(), feof(), fclose(), etc.

if (is_uploaded_file($_FILES['myFile']['tmp_name'])) {
$filePointer = fopen($_FILES['myFile']['tmp_name'], “rb”);

if ($filePointer!=false){
while (!feof($filePointer)){
$fileData = fread($filePointer, 4096);
// Process the contents of the uploaded file here… and also we can make insert query to store into db
}
fclose($filePointer);
}

}

Working Example:

<?php
if ($_FILES) {
echo “<pre>”;
print_r($_FILES);
echo “</pre>”;

$fileContent = file_get_contents($_FILES['upload']['tmp_name']);
echo “<pre>”;
print_r($fileContent);
echo “</pre>”;
//now you can process your content here…
die;
}
?>

<form enctype=”multipart/form-data” method=”POST”>
<input type=”file” name=”upload”>
<button type=”submit”>Enter</button>
</form>
Thanks,   Nilesh.


Leave a response

Your response:

Categories