PHP tutorial - How to write a file in PHP


How To Write A File In PHP

After learning how to read file discussed in previous tutorial, probably you will be asking how to write data to a text file in PHP! Well, this is what you are going to learn now.

The process of writting a file in PHP is similar to reading a file. The only different is the access mode will be 'w' and the function is fputs( ). Let say you are going to write this to an empty 'data.txt' file .

hello@example.com
php@example.com

The first thing you have to do is establish a connection.

<?php

$file = "data.txt";
$fp = fopen($file, "w");
fclose($fp);

?>

As you can see here, the code is exactly the same as the one used to read a file in previous tutorial. The only difference is the access mode 'w' which represents 'write' while 'r' represents 'read'. After a connection had been made, now you tell PHP to write those data to an empty file.

<?php

$file = "data.txt";
$fp = fopen($file, "w");
fputs($fp, "hello@example.com\nphp@example.com");
fclose($fp);

?>

When the above code is executed, it will output the result below.

hello@example.com
php@example.com

Try this Now try to write a script which will note down a visitor IP address and date when he visit your web site.

**You can use $REMOTE_ADDR to find IP address.

  

Optimize Website - Webmasters optimize their site and gain higher search engine ranking

Webmaster tools - Free online webmaster toolkits, website reporting and free PHP opensource scripts.

Free Photo Hosting - Free File Hosting, Free ZIP file Hosting, Free Image Hosting, Free MP3 Hosting.

Funny Videos, Stupid Videos

Stupid Videos - Custom Pimped Motorcycle Pictures, Videos, and Articles

Planet Diaz - Programming Community - Online programming resource for programmers all around the world

Forectory - Webmaster Directory

St Louis Computer Networking

Website Templates - 1000s of Templates $5 - Many Templates to help you build your site!

 


Each and every tutorial published in PHPhelps.com is originally written by PHPHELPS OWNERS. None of the content is allowed to be replicated without prior notice to writter.
Copyright © 2006 PHPhelps.com