Jump to content

  •  

Photo
- - - - -

How to: Write Files to the Server in PHP

PHP

  • Please log in to reply
No replies to this topic

#1 Wilson18

Wilson18

    Administrator

  • root
  • 112 posts
  • LocationUniversity of Birmingham

Posted 23 July 2014 - 10:36 PM

Please see the example below for how you can write a file to the server in PHP.

 

Create a New File

If you want to write to a file that doesn't exist yet, you can do this:

 <?php 
 //The file you would like to create
 $YourFile = "myfile.txt"; 
 //Create a handler so we can write the file
 $FileHandler = fopen($YourFile, 'w');
 //The data we want to write to the file
 $Stuff2Write = "First Line\n"; 
 //Write the data to the file 
 fwrite($FileHandler, $Stuff2Write); 
 //Close the file
 fclose($FileHandler); 
 ?>

Append a File

If you want to append a file (add to) which already exists, you can do this:

<?php
//The file you would like to create
$YourFile = "myfile.txt";
//Create a handler so we can write the file
$FileHandler = fopen($YourFile, 'a');
//The data we want to write to the file
$Stuff2Write = "More stuff to write\n";
//Write the data to the file
fwrite($FileHandler, $Stuff2Write);
//Close the file
fclose($FileHandler);
?>

List what you read?

Check me out on: YouTube, Twitter, Facebook, Google+