Code2Design.com
P.S. Don't leave without watching the Video Tutorials!

User login

Programming

The Layout

Navigation

Popular content

Resources

Who's online

There are currently 0 users and 5 guests online.

Lesson 18 - Reading External Files into PHP - Part 3

Now that we know how to read data from files into arrays, strings, and variables, lets try writing to files. Writing to files is pretty much the same as reading from them:

1) First you put the file name/path in a variable so that we can tell the computer what file we want edited (We can it "the file handle").
2) Then we open the file.
3) Now instead of reading from the file we write to the file.
4) Finally we close the file.

Open up you text editor (SciTE I hope) and type the following into it. When you are done, upload it to your web server.

<?php
// 1) Store the file name in a string (this is the file handle).
$filename "writetest.txt";
// 2) Open the file
$filehandle fopen($filename'w');
// 3) Write what we want to the file
fwrite($filehandle"This goes in the file.\n");
// 4) Close the file
fclose($filehandle);
?>

(Note: if you don't see anything when you browse to the file, it worked. You won't see anything because we don't "echo" or "print" anything in this script; all we do is write to a file.)

One thing you might notice is that in addition to the script writing to the file, the script also CREATED the file! The "w" command that we put in the fopen function ( fopen($filename, 'w') ) means this to the computer: "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."

Now if you open "writetest.txt" you will see this in it:

This goes in the file.

And there you have it! I told you it was just as easy to write to files! :)

Now lets modify the file to create five lines of text, we will put them on different lines using the "next line" (\n) character:

<?php
// Put the text we want in the file in a string.
$text "This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";

// 1) Store the file name in a string (this is the file handle).
$filename "writetest.txt";
// 2) Open the file
$filehandle fopen($filename'w')
// 3) Write what we want to the file
fwrite($filehandle$text);
// 4) Close the file
fclose($filehandle);
?>

Now after running the file you will see this in writetext.txt:

This is line one.
This is line two.
This is line three.
This is line four.
This is line five.

Peace of cake, huh? 8)

To finish off our file lets delete the comments in the code (you can keep them if you want) and add a couple of error checking functions - just so you learn to code properly. First lets add a "die" command to the fopen function:

<?php
$text 
"This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";
$filename "writetest.txt";
$filehandle fopen($filename'w') or die('Could not open the file');
fwrite($filehandle$text);
fclose($filehandle);
?>

The or die command just means:
If there is an error: stop the script and display [i]this message instead of a cryptic PHP error message.[/i]
Feel free to change "Could not open the file" to anything you want the error to say. You can test it by putting an error like this in the code:

$filehandle = fopen($filename22222, 'w') or die('Could not open the file');

Second lets add a message that lets us know that everything went all right. (First fix the error you just made :wink:

<?php
$text 
"This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";
$filename "writetest.txt";
$filehandle fopen($filename'w') or die('Could not open the file');

if (!
fwrite($filehandle$text)) {
    echo 
"Could Not write to the file!";
} else {
    echo 
"Wrote the following to the file:<BR>$text";
}

fclose($filehandle);
?>

For those of you who don't know; this is an if statement. Lets take it line by line to make it easier to understand:

<?php
if (!fwrite($filehandle$text)) {
    echo 
"Could Not write to the file!";
?>

In english it reads:
if (you cannont write (!fwrite) the value of "$text" to "writetest.txt") {
print "Could Not write to the file!"

Basically, if something goes wrong and you CANNOT write to the file, tell the user.

Here is the next part that will run if the first part of the loop is false:

<?php
} else {
    echo 
"Wrote the following to the file:<BR>$text";
}
?>

This else statement will ONLY run if the first part ("if could not write") is false. If this does run then that means that the script COULD write to the file! Along with letting the user know that everything is OK, we print out the value of what we put in the file ($text).

##################################################
## Checking Files
##################################################

Now lets practice with some of the other functions made for files:

is_file() - returns True/False indicating whether the specified file is a regular file
is_executable() - returns True/False indicating whether the specified file is executable
is_readable()- returns True/False indicating whether the specified file is readable
is_writable()- returns True/False indicating whether the specified file is writable
filesize() - gets size of file
filemtime() - gets last modification time of file
filetype() - gets file type

(Note: you can find ALL of the functions for files at php.net)

Lets put each one to use in a new script; type this into you editor:


Submitted by David on November 10, 2006 - 8:01pm.
read more | 3 comments

Lesson 17 - Reading External Files into PHP - Part 2

Now lets put what we learned about the explode() function and arrays into practice parsing (dealing with) files. Lets make a file called "file.txt" and fill it with at least 5 lines of non-sense. Open up SciTE or Notepad and type the following:

This is line 1
This is line 2
This is line ...uh... (what is after 2?)
anyways, this is the next line
And this is the last line!

Save the file and up load it to your web server.

Make an new make a new file called "filetoarray.php". After you save it type the following into it:

". count($contents). " lines in this file. Here is what he array looks like now:


Submitted by David on November 10, 2006 - 7:58pm.
read more | 1 comment

Lesson 16 - Reading External Files into PHP

Now it's time for us to learn how to use PHP's file API to create, edit, and destroy files through PHP.

"One of the most basic things you can do with any programming language is create and manipulate data structures. These structures may be transient - in-memory variables like arrays or objects - or more permanent - disk-based entities like files or database tables; however, the ability to create, modify and erase them in a convenient and consistent manner is of paramount importance to any programmer.


Submitted by David on November 10, 2006 - 7:55pm.
read more | 5 comments

Lesson 15 - Explode

As you keep advancing in your knowledge of PHP you will find that you need to break-up large strings every now and then - enter the explode() function.

explode(); - Splits a string by string (Turns a string into an array made up of the different values.)

<?php
$fullname 
"John Doe";
$name explode(" "$fullname);
echo 
$name[0]; // 'John'
echo $name[1]; // 'Doe'
?>

This is very useful if you have several different values you need hidden in one string.


Submitted by David on November 10, 2006 - 7:50pm.
read more | add new comment

Lesson 3 - Strings

Watch the Movie of Lesson 3

Strings

Strings in PHP could be thought of as sentences such as: "I went to the store". Strings differ from variables in that they are a COLLECTION of values in one variable.
Example:

<?php
$variable 
'9';
$string 'abcdefghijklmnopqrstuvwxyz';
?>

Stings can be used to store names, tiles, addresses, and all kinds of things. So expect to use them often! Just like variables - you don't need to tell the computer that it is a "string". The computer can tell just by what value you put in it.


Submitted by David on November 9, 2006 - 5:53pm.
read more | 4 comments

Lesson 2 - PHP Code

Watch the Movie of Lesson 2

If you visited the link in the last lesson you probably already know how to tell PHP code and how to comment it. Never the less, I want to make sure and go over it just so that no one is confused.

This is what PHP code looks like by itself:

<?php
 
...(more code)....
 ...(
more code)....
 echo 
"$$var dollars spent.";
 ...(
more code)....
 ...(
more code)....
?>

Everything between the opening "<?php" & "?>" tags is sent to the PHP core to be processed, then the result is sent back. and the rest of the page continues to load. Here is what PHP code might look like in an HTML file:




<div class="codeblock"><code><font color="#000000"><font color="#0000BB"><?php<br /> </font><font color="#007700">echo </font><font color="#0000BB">$tile</font><font color="#007700">; <br /></font><font color="#0000BB">?></font></font></code></div><TITLE><br /> </HEAD><br /> <BODY><br /> <div class="codeblock"><code><font color="#000000"><font color="#0000BB"><?php<br /> </font><font color="#007700">echo </font><font color="#DD0000">"Welcome to $sitename"</font><font color="#007700">; <br /></font><font color="#0000BB">?></font></font></code></div></p> <p>We are committed to serving you!</p> <br /> <div class="info_box"> Submitted by David on November 9, 2006 - 5:46pm. <br /> <a href="/lesson_2_php_code" title="Read the rest of this posting." class="read-more">read more</a> | <a href="/lesson_2_php_code#comment" title="Jump to the first comment of this posting.">3 comments</a> </div> </div> </div> <br /><div class="lbbg"> <div class="node"> <h2 class="title"><a href="/lesson_1_welcome_to_php">Lesson 1 - Welcome to PHP</a></h2> <!--paging_filter--><p><span style="font-weight:bold">Welcome to Beginning PHP!</span></p> <p><a href="/flashmovies.php?movie=phplesson1" target="_blank" class="movie_link">Watch the Movie of Lesson 1</a><br /> <br></p> <br /> <div class="info_box"> Submitted by David on November 9, 2006 - 5:44pm. <br /> <a href="/lesson_1_welcome_to_php" title="Read the rest of this posting." class="read-more">read more</a> | <a href="/lesson_1_welcome_to_php#comment" title="Jump to the first comment of this posting.">7 comments</a> </div> </div> </div> <br /><div class="lbbg"> <div class="node"> <h2 class="title"><a href="/subpage">Subpage</a></h2> <!--paging_filter--><p>Aenean eros arcu, condimentum nec, dapibus ut, tincidunt sit amet, urna. Quisque viverra, eros sed imperdiet iaculis, est risus facilisis quam, id malesuada arcu nulla luctus urna. Nullam et est. Vestibulum velit sem, faucibus cursus, dapibus vestibulum, pellentesque et, urna. <span style="font-weight:bold">Donec luctus.</span> Donec lectus. Aliquam eget eros facilisis tortor feugiat sollicitudin. Integer lobortis vulputate sapien. Sed iaculis erat ac nunc. Etiam eu enim. Mauris ipsum urna, rhoncus at, bibendum sit amet, euismod eget, dolor. Mauris fermentum quam vitae ligula. Vestibulum in libero feugiat justo dictum consectetuer. Vestibulum euismod purus eget elit. Nunc sed massa porta elit bibendum posuere. Nunc pulvinar justo sit amet odio. In sed est. Phasellus ornare elementum nulla. Nulla ipsum neque, cursus a, viverra a, imperdiet at, enim. Quisque facilisis, diam sed accumsan suscipit, odio arcu hendrerit dolor, quis aliquet massa nulla nec sem.</p> <br /> <div class="info_box"> Submitted by David on November 4, 2006 - 3:05am. <br /> <a href="/subpage" title="Read the rest of this posting." class="read-more">read more</a> | <a href="/comment/reply/3#comment_form" title="Add a new comment to this page.">add new comment</a> </div> </div> </div> <br /><div id="pager"><a href="/node" class="pager-first active" title="Go to first page">« first</a><a href="/node?page=5" class="pager-previous active" title="Go to previous page">‹ previous</a><span class="pager-list"><a href="/node" class="pager-first active" title="Go to page 1">1</a><a href="/node?page=1" class="pager-previous active" title="Go to page 2">2</a><a href="/node?page=2" class="pager-previous active" title="Go to page 3">3</a><a href="/node?page=3" class="pager-previous active" title="Go to page 4">4</a><a href="/node?page=4" class="pager-previous active" title="Go to page 5">5</a><a href="/node?page=5" class="pager-previous active" title="Go to page 6">6</a><strong class="pager-current">7</strong><a href="/node?page=7" class="pager-last active" title="Go to page 8">8</a></span><a href="/node?page=7" class="pager-last active" title="Go to next page">next ›</a><a href="/node?page=7" class="pager-last active" title="Go to last page">last »</a></div><!-- end content --> <br /><br /><br /> <h3>Like what you see?</h3> Why not add more? C2D is looking for other Christian Web Masters who would like to help write articles for this site. If you have expericance in FLASH, CSS/HTML, PHP/MySQL, PhotoShop/GIMP, Blender, Javascript, or just General Design - our users would love to hear what you have to say. <a href="/contact/">Contact Us</a> <br /><br /> <div id="breadcrumb"> </div> </div> </div> <div id="topfooter"> <a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&title=" title="Bookmark this post on del.icio.us." rel="nofollow"><img src="/modules/service_links/delicious.png" alt="delicious" /></a>   <a href="http://digg.com/submit?phase=2&url=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&title=" title="Digg this post on digg.com." rel="nofollow"><img src="/modules/service_links/digg.png" alt="digg" /></a>   <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&title=" title="Submit this post on reddit.com." rel="nofollow"><img src="/modules/service_links/reddit.png" alt="reddit" /></a>   <a href="http://ma.gnolia.com/bookmarklet/add?url=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&title=" title="Submit this post on ma.gnolia.com." rel="nofollow"><img src="/modules/service_links/magnoliacom.png" alt="magnoliacom" /></a>   <a href="http://www.newsvine.com/_tools/seed&save?u=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&h=" title="Submit this post on newsvine.com." rel="nofollow"><img src="/modules/service_links/newsvine.png" alt="newsvine" /></a>   <a href="http://www.furl.net/storeIt.jsp?u=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&t=" title="Submit this post on furl.net." rel="nofollow"><img src="/modules/service_links/furl.png" alt="furl" /></a>   <a href="http://www.google.com/bookmarks/mark?op=add&bkmk=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&title=" title="Bookmark this post on Google." rel="nofollow"><img src="/modules/service_links/google.png" alt="google" /></a>   <a href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u=http%3A%2F%2Fwww.code2design.com%2Fnode%2F&t=" title="Bookmark this post on Yahoo." rel="nofollow"><img src="/modules/service_links/yahoo.png" alt="yahoo" /></a>   <a href="http://technorati.com/cosmos/search.html?url=http%3A%2F%2Fwww.code2design.com%2Fnode%2F" title="Search Technorati for links to this post." rel="nofollow"><img src="/modules/service_links/technorati.png" alt="technorati" /></a></div> <div id="footer"> <div class="innertube"> <br /><br /> <div class="footer_box"> <h2>Recent blog posts</h2> <div class="item-list"><ul><li><a href="/david/portable_nginx_php_memcached_mysql_server_for_windows">Portable Nginx PHP Memcached MySQL Server for Windows</a></li><li><a href="/david/beginning_photo_editing">Beginning Photo Editing</a></li><li><a href="/david/micromvc">MicroMVC</a></li><li><a href="/david/php_video_tutorials">PHP Video Tutorials</a></li><li><a href="/david/md5_hashes_passwords_salts_and_more">MD5, hashes, passwords, salts and more</a></li><li><a href="/david/free_autodesk_inventor">Free AutoDesk Inventor</a></li><li><a href="/warpnacelle/instant_html_help">Instant HTML Help</a></li><li><a href="/maspick/you_can_cms_without_one_two">You Can CMS Without One Two</a></li><li><a href="/david/persecution">Persecution</a></li><li><a href="/david/c2ds_open_search_and_razor_blades">C2D's Open Search and Razor Blades</a></li></ul></div><div class="more-link"><a href="/blog" title="Read the latest blog entries.">more</a></div></div> <div class="footer_box"> <h2>Recent comments</h2> <div class="item-list"><ul><li><a href="/forums/new_version_and_installing_in_subdirectories#comment-7618">Changes</a><br />2 weeks 3 days ago</li><li><a href="/forums/i_have_been_looking_for_a_tiny_mvc_to_learn_and_adapt_to_my_own_usage#comment-6994">Nice</a><br />5 weeks 6 days ago</li><li><a href="/david/rooted_in_christ#comment-5594">temptations</a><br />38 weeks 1 day ago</li><li><a href="/lesson_6_post#comment-4908">In this lesson, even if I</a><br />51 weeks 4 days ago</li><li><a href="/tutorial/members_system_using_my_sql#comment-4659">header problems</a><br />1 year 3 weeks ago</li><li><a href="/tutorial/convert_mysql_tables_to_sqlite_tables#comment-4543">MySQL -> SQLite3</a><br />1 year 5 weeks ago</li><li><a href="/david/rooted_in_christ#comment-4252">If you just love God , he</a><br />1 year 11 weeks ago</li><li><a href="/autocad#comment-4197">Autocad inventor</a><br />1 year 12 weeks ago</li><li><a href="/tutorial/convert_mysql_tables_to_sqlite_tables#comment-4148">People wanting to go the other way</a><br />1 year 13 weeks ago</li><li><a href="/forums/php_xml_socket_server#comment-4135">I am doing a xmlSocket server stuff right now</a><br />1 year 13 weeks ago</li></ul></div></div> <div class="footer_box"> <h2>New forum topics</h2> <div class="item-list"><ul><li><a href="/forums/new_version_and_installing_in_subdirectories" title="1 comment">New version and installing in subdirectories?</a></li><li><a href="/forums/i_have_been_looking_for_a_tiny_mvc_to_learn_and_adapt_to_my_own_usage" title="1 comment">I have been looking for a tiny mvc to learn and adapt to my own usage.</a></li><li><a href="/forums/php_coding">php coding</a></li><li><a href="/forums/modules_and_hooks">modules and hooks</a></li><li><a href="/forums/dvdrw_wont_burn_cd">DVDRW won't burn cd?</a></li><li><a href="/forums/forget_about_photoshop_five_css_hacks_to_help_you_stop_using_images">Forget About Photoshop: Five CSS Hacks to Help You Stop Using Images</a></li><li><a href="/forums/introduction_video">Introduction Video</a></li><li><a href="/forums/why_cant_my_last_login_date_and_time_be_displayed_whenever_i_login" title="1 comment">Why can't my last login date and time be displayed whenever I login?</a></li><li><a href="/forums/please_help_with_this_question" title="1 comment">Please help with this question.</a></li><li><a href="/forums/php_not_working_on_xp_home_edition_have_apache_and_mysql_do_l_also_need_wamp" title="1 comment">PHP not working on XP Home Edition (have APACHE and MySQL; do l also need WAMP?)</a></li></ul></div><div class="more-link"><a href="/forum" title="Read the latest forum topics.">more</a></div></div> <br class="clearall" /> <h2>About C2D</h2> Code2Design is a "for Web Masters by Web Masters" Christian Community. Our goal is to teach you the skills and theories behind award winning designs so that you can create amazing sites! This is more than a tutorial site though - We will lead you though every step of the online world, from start to finish. So join our community and get ready to rock your web!<br/> <center><br /> <a href="http://www.spreadfirefox.com/?q=affiliates&id=183912&t=218"><img src="/misc/firefox.png" alt="Firefox" /></a>   <a href="http://www.allaboutgod.com/God.htm"><img src="/misc/God.jpg" alt="Supported By God" /></a>   <a title="RSS feed" href="/rss.xml"><img src="/misc/rss_image.png" alt="RSS Feed" /></a><br /><a href="http://www.1and1.com/?k_id=8532941" target="_blank"><img src="http://banner.1and1.com/xml/banner?size=5%26%number=1" width="140" height="28" alt="Banner" border="0" /></a>  <br /> <!-- <a rel="license" href="http://creativecommons.org/licenses/by/2.5/"><img alt="Creative Commons License" style="border-width: 0" src="http://creativecommons.org/images/public/somerights20.png" /></a> --> <br /> Copyright 2007 Code2Design.com (<a href="/Legal">More...</a>)<br /> <small>(Yes, this is yet another of <a href="http://claimid.com/davidpennington">David's</a> valid <a href="http://jigsaw.w3.org/css-validator/validator?uri=http://www.code2design.com/themes/foreverwhite/style.css" alt="Validate CSS" target="_blank">css</a> and <a href="/valid/" alt="Validate XHTML" target="_blank">almost valid xhtml</a> projects...)</small><br /><br /> </center> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-244873-7']); _gaq.push(['_setDomainName', '.code2design.com']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body></html><!-- Rendered in 1.02956 -->