Saturday 16 April 2011

PHP: File Input and Output

So i was meddling around today will File input and output functions. These functions are relatively the same as what i have dealt with in C and C++. One thing that's bothering me is the newline command is still acting weird for me. Another thing I experimented with was getting a string or value from a user input. This involves HTML forms. Which i have very little experience with too. So today was very hectic trying to learn and correct a lot of mistakes and errors while trying to code and learn new things. I also noticed what i was coding actually required a server this time. So i used a nice program called xampp to set up a PHP server for me. So testing the code on that has been splendid. So anyhow on to the coding.

Source Code
-------------------------------------------------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=us-ascii" />

    <title>form.htm</title>
</head>

<body>
    Form site
    <br />

    <form action="fileio.php" method="post">
        username:<input name="name" type="text" /> <input type="submit" />
    </form>
</body>
</html>
----------------------------------------------------------------------------------------------------------------
Now the code that makes the least amount of sense is this.

Source Code
-------------------------------------------------------------------------------------------------
    <form action="fileio.php" method="post">
        username:<input name="name" type="text" /> <input type="submit" />
    </form>
---------------------------------------------------------------------------------------------------
 Now you are probably wondering what in the world is this. Well, I will start with saying it is a form. If you haven't figured that out then i don't know if programmings right for you. What this form does is allows the user to enter a string into a box. Then hit a little submit button. This is appropriate for numerous situations and can be used as a login.

In this codes case it's to check the availability of a username. If it is free, it allows the user to use it.
Another important part of the form is the top where it says

action="fileio.php" method="post"

the action part is when the user clicks the submit button.It will bring them to another page i called fileio.php. I will show the code for that soon. The next important thing is the method="post". This takes whatever the user entered into the text box and transfers it over to the fileio.php page. Now this may be explained poorly and i am sorry if it is. This is how i understand it. So if this is not the case as to what is going on correct me in a comment.  So the user clicks submit after filling out the forms.

Now on to the fileio.php page.

Source Code
-------------------------------------------------------------------------------------------------

<?php

$fp = fopen("usernames.txt", "r") or die("Could not open requested file");

$usrname = $_POST['name'];
$used = 0;
while ($str = fgets($fp)) {
    if ($usrname == $str) {
        print ("This username has already been used");
        $used = 1;
        break;
    }
}
fclose($fp);

if ($used == 0) {
    $fp = fopen("usernames.txt", "a");
    fwrite($fp, "\r\n$usrname");
    fclose($fp);
}

?>
----------------------------------------------------------------------------------------------------------
Okay so we have lots going on here in this code. I will try and touch on all bases.

$fp = fopen("usernames.txt", "r") or die("Could not open requested file");

This line of code has created a variable that points to a file. That file is usernames.txt and the "r" signifies that we have open that file for reading only. fopen stands for file open and takes two parameters a string and what you want to do to the file.

$usrname = $_POST['name'];

Remember that method="post" code from earlier. This is where that comes into play. What ever the user typed into that box is now a string held by the variable $usrname. As far as I know this is the only way to prompt the user for a variable. How neat.

 $used = 0;
while ($str = fgets($fp)) {
    if ($usrname == $str) {
        print ("This username has already been used");
        $used = 1;
        break;
    }
}

Now this big ugly control structure. The variable $used is just there to keep track of whether or not the username has been used already. where it says while( $str = fgets($fp) ). This is a loop, and the condition for that loop is keep looping while there is still a string for use to get from the file.

$str = fgets($fp)

in other words the condition above is using fgets(). fgets() is a function that reads a line from a file. So what is happening is it is reading a line from the file and storing that string into the variable $str. Now this function fgets will keep being called until it finds no more lines left in the file. In this case it will stop running and when this happens the loops stops looping.

if ($usrname == $str) {
        print ("This username has already been used");
        $used = 1;
        break;

This line of code is saying hey! if the username is equal to a string already in the file then lets alert the user, change the value of the variable used to one, and then stop the loop by using break. Simply right.
 
So after this comes an important function for files once they are open.

fclose($fp);

fclose just closes your file that is opened.  In this case our file pointer $fp which points to usernames.txt.

if ($used == 0) {
    $fp = fopen("usernames.txt", "a");
    fwrite($fp, "\r\n$usrname");
    fclose($fp);
}

This last piece of code is saying. Hey if the username was not already used. Then lets store it in the file so it can't be used again. We determine if the username has been used already from the while loop statement and by using the variable $used. Also you will notice we are pointing to the same file again. But the difference being this time. We are opening the file for appending. Denoted by "a" in the second parameter.

What is happening here is we have opened the file to add on to the file without erasing anything.

The last line of code we have not seen is

fwrite($fp, "\r\n$usrname");

fwrite() is a function that adds a string to the file. So we are adding the username to the file in this line of code. We are also creating a newline so the username is spaced out among the others.

So hopefully that was not too confusing and I will be adding onto this code as  i progress and get better.

14 comments:

  1. never had php, but looks a lot like visual basic. so i understood it all.

    ReplyDelete
  2. Me too, I have a strong background in VB so that helps.

    ReplyDelete
  3. i think its funny i read your post but i have no idea whats going on or what you are saying, and then i get to the bottom and im like oh no i have to write something to show i was paying attention because i was but i have no idea what to say, nevertheless good show.

    ReplyDelete
  4. how about creating the file if it cant be found
    and you should really switch to real language php is horrible

    ReplyDelete
  5. next teach ppl to hide files in jpgs! ;)

    Following your blog!

    http://teemoreporting.blogspot.com/

    ReplyDelete
  6. I have always wanted to learn programming, but I guess I'm too lazy to do it. One course at the university wasn't quite enough.

    ReplyDelete
  7. man, its all too much for my tiny brain. think ill stick with drawing art in Microsoft paint. much easier! lol

    ReplyDelete
  8. cool post, very informative! awsome blog, followed!

    ReplyDelete
  9. i agree with erika, php looks like a jumbled up mess. usually i can understand a language i dont particularly understand but this is just beyond words

    ReplyDelete
  10. This is so great that I found this blog. Learning code for the last 2 weeks.

    ReplyDelete
  11. I need to start learning php

    ReplyDelete
  12. I'm lost. Looks like I need to read some of your previous stuff to figure out what is going on!

    ReplyDelete