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);
?>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);
?>$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!";
?>if (you cannont write (!fwrite) the value of "$text" to "writetest.txt") {
print "Could Not write to the file!"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";
}
?>##################################################
## 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:
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!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:
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.
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.
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.
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:
<?php
echo $tile;
?>
<?php
echo "Welcome to $sitename";
?>
We are committed to serving you!
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. Donec luctus. 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.