Jul 26, 2008

How To Read And Write Files Using Php - php :: reading and writing files

Free Web Hosting, No Ads > CONTRIBUTE > Tutorials
Pages: 1, 2, 3

free web hosting

How To Read And Write Files Using Php - php :: reading and writing files

electriic ink
How To Read And Write And Files
a simple trick using php

For this script all you need is a php enabled server, a text document and a basic understanding of php itself:

Beginning
  1. Create a text file called name.txt in any directory.
  2. Change the file permissions to 777
  3. Create a empty php file in the same directory.

You are now ready to begin reading and writing your files. If you just want to read the file scroll straight down to Reading the File else read through the whole tut smile.gif


Open The File

Before you can write to the file, you need to open it:

CODE
<?

$thefile = "name.txt"; /* Our filename as defined earlier */
$towrite = "Black widgets rule!"; /* What we'll write to the file */

$openedfile = fopen($thefile, "w");


This opens the file name.txt which we created earlier for writing, but you can open it for reading and both. Just replace the w with one of the following:

QUOTE(php.net)

r -- Open for reading only; place the file pointer at the beginning of the file.
r+ -- Open for reading and writing; place the file pointer at the beginning of the file.
w -- Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
w+ -- Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.


You can find more of these at php.net. I have only quoted a few.

Also, the fopen() function must be stored as a variable!

If you have done what I have said correctly, the file should be opened so now we are ready to write things into it:

Writing The File

Writing to the file is very easy. You use the fwrite() function like so:

CODE
<?

$thefile = "name.txt"; /* Our filename as defined earlier */
$towrite = "Black widgets rule!"; /* What we'll write to the file */

$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);


Again, a breeze all it does is write $towrite to $thefile. You must always write the content to the variable with fopen() stored within it not the one just containing the path to the file! Please bare in mind that because of the way we opened the file all information previously stored in the file will be overwritten!

Note: I was told that you can use file_put_contents() instead of fwrite(). You use it in the same way as fwrite() except you would use $thefile instead of $openedfile and like file_get_contents() there's no fopen() and fclose()! Only for PHP5+ though.

Reading The File

Reading a file is even easier. You could go through the fopen() method but I'm gonna show you an easier way:

CODE
<?
$thefile = "name.txt"; /* Our filename as defined earlier */
$towrite = "Black widgets rule!"; /* What we'll write to the file */

$whatsinthefile = file_get_contents($thefile); ?>


No opening the file, no closing the file. Just that.

Closing the file

If you opened the file using fopen() then you have to close it using fclose(). Simple:

CODE
<?
$thefile = "name.txt"; /* Our filename as defined earlier */
$towrite = "Black widgets rule!"; /* What we'll write to the file */

$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
?>


It couldn't be easier than that and if everything is done just as I say there should be no php errors at all smile.gif

Any questions about this tutorial?

 

 

 


Reply

wariorpk
That is a nice tutorial you wrote here. If I ever learn php (not likely I am way too lazy) I would look here. Keep up the good work.

Reply

neokid
OMG thank you, i had alot of trouble but im a beginner

Reply

shadowdemon
were do u write in it

Reply

thablkpanda
Nice tut, simple though, I'd expect adding by-line writing and such..

I'd also think you don't want to add '?>' to the end of the previous code boxes, but it's not there...

Panda - oh, maybe because it's not the end of the file yet- lol

Reply

Amezis
Great tutorial biggrin.gif

I'm only a newbie at PHP but I am trying to learn, so thanks alot tongue.gif

Reply

good-baby
Buddy , a real nice sharing . Infact last night i was just wondering how to read files with .php extension.
Tonight i will just try your Tutorial and hope that shuld work for me. however , thanx for such a nice sharing ! biggrin.gif

Reply

Outsider
QUOTE(cmatcmextra @ Aug 26 2005, 10:46 AM) *

How To Read And Write And Files
a simple trick using php

CODE
<?
$thefile = "name.txt"; /* Our filename as defined earlier */
$towrite = "Black widgets rule!"; /* What we'll write to the file */

$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
?>


Any questions about this tutorial?

What if I dont want to add the contents but I want to add something?

Can I move the file pointer to the end of the following and protect the previously entered contents from being deleted?

For example:

Say I have a website.
I have made a form in which people can send me messages.
I could use mail() to get it as a mail message.

But I want to store such info in a single file one after the other.
Is it possible?

Another question : Does it support multi-line passages?
i.e. Can many lines be sotred in a single file?

 

 

 


Reply

jlhaslip
QUOTE
What if I dont want to add the contents but I want to add something?

Can I move the file pointer to the end of the following and protect the previously entered contents from being deleted?

Use $openedfile = fopen($thefile, "a+");
QUOTE

I have made a form in which people can send me messages.
I could use mail() to get it as a mail message.

NO, send the email is seperate function, but you could write the information to a file at the same time, then you have a copy in case the email fails to send or gets lost.
QUOTE

But I want to store such info in a single file one after the other.

See above. Check the link posted above that goes to the php.net page. All the possible choices are listed there. Use one that will 'append' to the file. either "a" or "a+" will work.
QUOTE

Another question : Does it support multi-line passages?

Yes, add newline and or return-line characters to the message body or use comma seperated values format with a unique character string as a seperator.
QUOTE

i.e. Can many lines be sotred in a single file?

As many as the File Manager will allow you to have for your system on the server. On a LInux based Apache server like the one here at the Trap, LOTS.

Reply

Outsider
Thanks for all the support. I will be putting the above tips into action.

Reply

Latest Entries

GaiaZone
Great!

You see, after I read this I questioned myself if this could be used to create new pages on a website, apparently, it is possible.

For example, you have a member register for your site, lets say a Blog site, and when they confirm the account a new page will be written and saved to be used as his "Blog Page".

I'm not sure if this is the most efficient way to do this or not, but it might just work. happy.gif

Reply

anachro
I read on read & write a bit before; This is a good tutorial, thank you for posting it. also good measure posting the link to the origional, but skipping some info will just leave you with more questions to answer (not for next time you make a tutorial)

Reply

rvalkass
Yes, just set the file name to something.html and it will work.

You could also get it to write PHP scripts I suppose. A self replicating PHP script... tongue.gif

Reply

GaiaZone
Ah, that sounds excellent!

So the filename would be "name.html" then, right?

Also, if the HTML document is possible to create, that means that I could create PHP scripts also?

Reply

rvalkass
An HTML document is just a text document. As long as you worked out all the HTML code beforehand, you could use PHP to put that into a file. You also have the advantage of being able to use loops, which are excellent for doing tables and lists - you only need to write the HTML code for one line, and PHP puts different data in, then repeats it.

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Pages: 1, 2, 3
Recent Queries:-
  1. script read write edit flat file php - 4.98 hr back. (1)
  2. including php files with javascript - 6.36 hr back. (1)
  3. how to write in a doc file in php - 6.53 hr back. (1)
  4. php writing flat files on server - 7.46 hr back. (1)
  5. how to write in text using php - 8.76 hr back. (1)
  6. write to file php - 10.69 hr back. (1)
  7. php write files - 12.88 hr back. (1)
  8. how to write at any place of a file in php - 13.71 hr back. (1)
  9. php read and write a file - 14.16 hr back. (1)
  10. php read and write to file - 15.51 hr back. (1)
  11. how to create file in php - 16.63 hr back. (1)
  12. example read write file php - 16.22 hr back. (2)
  13. write in the .doc file using php - 17.90 hr back. (1)
  14. php safemode file read write - 18.01 hr back. (1)
Similar Topics

Keywords : read, write, files, php, php, reading, writing, files

  1. Debug Exe Files
    How to debug an exe file. (4)
  2. Download Files Off Esnips.com
    even now that the download button is gone! (0)
    hey everyone, i am sure that many of you may have heard of esnips , which is basically online file
    storage/sharing. you can now find almost any file imaginable on esnips, and in many ways it is
    better than rapidshare. previously, once you are signed in to esnips, you were able to download any
    esnips file via a button only viewable to members. back then, there was a method to download any
    file without even signing in. then, probably due to legal issues, users were able to choose whether
    or not people could download their files. the hack mentioned above, though, still....
  3. How To Hide Your Important Files And Folders
    In Ms. Windows, Without Using Programmes. (7)
    Most of people share their computers with others -family, mates, buddy or whoever- and that sharing
    threatens their secrets and private file to be revealed, letting some people to know things they
    shouldn't know.. My Securing Way: Operation - Camouflage Use an Icon
    Editor to generate a 1x1 Transparent Icon and Save it .. > 1 Open CMD.. Start >> Run or Press
    WindowsLogo+R.. Lets Say you wanna hide a Folder named " secure " and it's located in
    E:\folder\ so Write E: and Press Enter then Write Cd folder and Enter then At....
  4. Writing An Essay - Part I: Sentences
    Fragments and Run-ons (6)
    Writing essays is NOT a talent; it's a skill. As a skill, it can be honed and improved, like
    playing basketball, carving wood, or cooking. True, there are those who just do it better, as in the
    other areas mentioned, but that doesn't mean that you can't be good at it with a little
    know-how and practice. As an English teacher, it's my job to show students how to do that, so I
    figured that I would give everyone a few tips on how to improve your writing and, someday, make my
    job a little easier. The first basic building block of a good essay is to have well....
  5. How To Better Compress Files In Winrar
    (7)
    How to better compress files in winrar As you know Winrar is more popular and powerful than
    other compressor softwares. To better compress your files and folders follow below steps: 1- Right
    click on your file and select "Add to archive…" from context menu. A dialog box will appear. 2- In
    General tab and in "Compression Method" dropdown menu, select "Best". 3- Click on Advanced tab and
    then click on "Compression" botton. Advanced Compression Parameters dialog box will appear. 4- In
    Text Compression section select Force and in Prediction Order type 63 and in Memory....
  6. Cpanel Analysis And Log Files
    Part 4 of My 7 Part Tutorial (0)
    This Tutorial will be divided into 7 different parts, and this is the first part, when i get the
    other parts together, i will post the links under here /biggrin.gif" style="vertical-align:middle"
    emoid=":D" border="0" alt="biggrin.gif" /> Enjoy. Part 1: E-mail Management Part 2: Useful Site
    Management Tools Part 3: Useful Site Management Tools2.1 Part 5: Advanced Tools Part 6:
    PreInstalled Scripts, Extras, and Cpanel Options Part 7: Fantastico Detailed Cpanel Tutorial
    Part 3: Analysis and Log Files In this tutorial I will, in detail explain all ....
  7. How To Fix Problems With Shareaza
    ONLY for people to download LEGAL files with. (1)
    Can't run shareaza and surf the internet at the same time? There could be two
    problems: Your uploads are killing your downloads and/or you are using Windows 95/98/ME. If you
    are uploading constantly and havent limited the bandwidth then it is likely that you are killing
    your download speed which is affecting your ability to surf the web and do other tasks. If you
    are uploading lots and download speeds are suffering: Start Shareaza. Click on the Tools menu,
    then click Shareaza Settings. In the box that just popped up, there is a list of men....
  8. Flatfile User Login/signup
    Uses text files only (compatable with forums and message system) (24)
    With this tutorial, you will learn how to create a textfile login script. This user membership
    script is for use also with my forums and message system scripts. I will also give you the scripts
    to make it so that people can change their profiles. Ok, The first thing we need to do is make the
    database. To do this, create a blank text file called 'userdata.txt' , make sure it is ALL
    LOWER-CASE. Edit this file and put
    '**username|##|password|##|email|##|rank|##|userid|##|name|##|picture**'. This will not be
    used, however it will give you an idea of how the....
  9. How To Chmod Files
    (16)
    This is a short but useful tutorial on how to chmod files I offen find wap/web masters
    uploading scripts into their severs,creating databases,confirming scripts to work with the databases
    etc. but little you know that some people dont know how to chmod files.know how can you become a
    good wap/web master without knowing the important basics? Never the less this tutorial will guide
    and teach you how to chmod files and the importance it has. How many times have you uploaded a
    script/file and did everything right but you still getting errors,or you not being able to ....
  10. How To Create Self-unzipping Files
    for beginners (18)
    This tutorial is based on winzip 10.0 (but it should work on other versions). Create or open the
    file you would like unzipped. Now, on the Actions menu, click make .exe file. A popup box should
    popup. Click ok. Now in the popup box that appears, type in the default folder that the program
    will unzip to. Press ok. Now another popup will tell you if you want to test the file, click yes.
    Now click ok again in the box that appears. Now press unzip. If it says - files unzipped
    succsessfully! Click ok and pat your self on the back! You have created the self-....
  11. How To Open Bam & Tt Files, long 3 part tutorial
    (2)
    Part 1 Extracting files PLEASE DO NOT COPY ! This links with my other topic to 5.6
    bams , Loads of people have asked me how do you get pview , extract .mf files. Well im going to show
    you all in one. 1. Download Panda3D v.1.1.0 from here Start Picture Totorial Again,
    ugggh ! 1. Navigate your way to where you installed Panda3D ( It is usually :
    C:\Panda3D-1.1.0 ) 2. Open the bin folder in the Panda3d directory 3. Find and copy
    Multify.exe and PView.exe 4. Paste the Files to the desktop 5. Navigate your way to C:�....
  12. Php Script To Make A Link List
    From the list of the Directory Files (6)
    Well, it has been a while since I have added anything to the Tutorial Sectiion, so here is another
    script for the members to enjoy. This one creates a list of links from the contents of the directory
    which it is run from. For instance, if you run it from the public_html folder, then all the files
    (not the Directores) are listed and linked so when you click on the link, that file is parsed and
    output to the browser. Here is the code: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    An XHTML 1.0 Strict Page to List the files in this directory ....
  13. Templating System Using Php Includes
    Building a Dynamic site using Includes and flat-files. (13)
    Php based Templating System http://jlhaslip.trap17.com/template/index.php The Source Code
    for the scripts are included (literally) on the different pages on the Demo, including the Contact /
    Email script. The only page not there yet is the Message Script. Maybe tonight I will upload that.
    This one uses a little bit of query-string checking to confirm that the contents of the page are
    actually available (file_exists())and an allowed page content before serving it up. The
    'allowed page content' is done by checking against a flat-file containing an array....
  14. Building An Unordered List Of Anchors
    From a list of files in a folder (4)
    Building an Unordered List of Anchors from a Folder of files This script reads files from the
    named folder and then builds a list of links from the filenames using the contents of the first
    tag as the link description and the file-name as the anchor href . The file should be a web
    readable file such as html or php. This script may come in handy for creating a list of clickable
    links for use in sidebars and on 'sitemap' pages. Simply build a series of html files and
    store them all in a single folder, ensuring that the description inside the first h3....
  15. How To Clear Your Temp Files
    (17)
    You can clear your temp file a number of ways!! First way 1. Go to Start 2. Go to RUN
    http://img.photobucket.com/albums/v610/123...90/977a6e18.jpg 3. Type in temp, or TEMP, or Temp caps
    doesn't matter just as long as it says temp 4. Now if there is somthing there...then you should
    delete it..no harm will come to the computer.. if it gives you an error of this file is in use..then
    you cant delete it for now because the file is in use.... Second Way 1. Go To My Computer
    http://img.photobucket.com/albums/v610/123...90/3c3784d4.jpg 2. Go To Local Disk (C:) h....
  16. How To Read Large Files In Php.
    Tutorial on reading large files in PHP. (3)
    First of all don't use file() function instead use fread() functions. I think you should deploy
    the split-script technique. Its different from splitting your text file. Instead you get two scripts
    to do the same job. Or you can deploy the following method. First of all you should be knowing the
    size of the max text file which can be read in the max_execution_time on your Web Server. For that
    you need to use fread() function. with something like this: CODE
    $file=fopen("file.txt","r"); $count=0;
    while(!feof($file&....
  17. Delete Files And Directories Using Php
    following up from creating and writing (7)
    How To Delete Files and Directories follow up from creating them Hello all and
    welcome to my second tutorial involving file management. In my previous tutorial , I explained how
    to create, write and read files. In this tutorial I'll explain how to remove the files and
    directories you took so long to create. I did not explain last time how to create directories as I
    did not know, now I do, you can use the mkdir() function. Now with this tutorial.... Removing
    Files Removing files can easily be done with the unlink() function: CODE <? un....
  18. Adding Ur Own Files On Send To
    Windows xp (0)
    This tutorial will enable you to add places on the context menu under the Send To option. This is
    how u do it. Create a shortcut of the folder you want to add.Cut/Copy the shortcut and go to
    C:\Windows\Documents and Settings\Your user\Send To and paste the shorcut
    there. You can also rename the shortcut from shortcut to xxxxx to xxxxx Remember Your user stands
    for your userid that you have used to login. If you have any probs PM me.....
  19. Writing On Images
    ...with PHP and GD library (2)
    Demo: http://www.fantastictutorials.com/files/av...er&color=random ..and:
    http://www.fantastictutorials.com/files/avatar/index.php This tutorial is based on the code I used
    for this avatar generator . This tutorial is for people that are reasonably comfortable with
    php. I have went to a lot of work making it as simple as possible so even if you are a beginer you
    shouldn't have problems. After writing the tutorial, I realised how difficult it is to read
    when the source and tutorial seperately ... so I commented the tutorial into the source of the php.
    First....
  20. Css And Javascript Combined For Dynamic Layout
    use of different CSS files at same site (9)
    This tutorial is meant for people that are dealing with problems while coding their site at 100% of
    width. Important notice: Some people has JavaScript disabled, so they will not be able to load CSS
    file (take this in account when creating your website). How this script works. In the HEAD of your
    HTML document will apply this command, so variable.js file will be load at start: CODE
    <script type="text/javascript" src="variable.js"></script> In
    browser JavaScript file variable.js is loaded. This Javascript file consist of this para....

    1. Looking for read, write, files, php, php, reading, writing, files

Searching Video's for read, write, files, php, php, reading, writing, files
advertisement



How To Read And Write Files Using Php - php :: reading and writing files



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE