1

I want to upload a text file using html file upload option. By using php I want to put the content of that file into already created text file. But I am unable to do so, I am trying the following code but it only save the file name.

//This is HTML FORM

<form action="project.php" method="post" enctype="multipart/form-data" >
<input type="file" name="file1"><br>
<input type="file" name="file2"><br>
<input type="submit" name="submit" id="submit">
</form>

// THIS is my PHP SCRIPT

if(isset($_POST['submit']))
{
    $f1 = $_FILES['file1'];
 file_put_contents("a.txt", $f1);   

    $f2 = $_FILES['file2'];
 file_put_contents("b.txt", $f1);   
}

$string1=file_get_contents('a.txt');
$string2=file_get_contents('b.txt');

?>

Please help in this regards.

Thanks...

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Saleem Jafar
  • 123
  • 1
  • 3
  • 13
  • Possible duplicate of [How to upload & Save Files with Desired name](http://stackoverflow.com/questions/3509333/how-to-upload-save-files-with-desired-name) – Irrmich Feb 03 '16 at 12:27
  • Careful there not to overload your server's hard drive.. anybody could upload huge files with that :) – Nebula Feb 03 '16 at 12:39

1 Answers1

3

First you get the contain for file from temp then use file_put_contents as

$file = 'a.txt';
// Open the file to get existing content
$current = file_get_contents($_FILES['file1']['tmp_name']);

// Write the contents back to the file
file_put_contents($file, $current);

$file1 = 'b.txt';
// Open the file to get existing content
$current1 = file_get_contents($_FILES['file1']['tmp_name']);

// Write the contents back to the file
file_put_contents($file1, $current1);
Saty
  • 22,443
  • 7
  • 33
  • 51
  • What it does is that it append the existing file every time when i upload, I want to replace the existing file when ever i upload a file – Saleem Jafar Feb 03 '16 at 12:50
  • use this `$fh = fopen('a.txt','w'); fclose($fh);` before `file_put_contents` – Saty Feb 03 '16 at 12:53