tekfoo

PHP file handling

In PHP on May 6, 2010 at 4:06 pm


File handling functions are an essential part of any coding language. PHP has a collection of functions to read and to files too. We can use them to create, edit, delete, move, check the existence of and upload files. That’s pretty much everything you can do with files, except using them in a script helps you automate those tasks.

Prerequisites

Like always I assume that you know the basics of php. For instance if you can understand what this
$variable=”value”;
if($variable==”value”)echo “Variable has a value”;
means, we’re good to go.

How does php treat files?

There isn’t any huge difference between how we open and read files and how php does it. Every file has data, in simple words they’re all text, even the image and video files, only unreadable text. What do we do when we need to read or write into a file. We open it and do our thing. That’s just the way php does it too. No extra complications except for some code. You’ll understand it as soon as we do some coding.

Read files


Reading a file in php can be done using a number of function. We can group them on the ease of use. So there are easy and hard ways to open and read a file. Lets look at the easy functions first.

Easy ways or functions to read a file

Location of the file

Its important that you specify the right location of the file you want to read. So if the file’s in the same directory as the script the location should be the filename, but if its in the parent directory if the script the location would be ../filename. And if the file’s located in a sub directory of the folder that script is in location is subdirectory/filename.

1. file()

file() reads a file and copies it into an array on a line by line basis, each line is treated as one value of the array.
Here’s how you use it.
$text=file($fileName)

If the contents of the file would have been like this.
First line
Second line
Third line
The array would be the same as.
$text[1]=”First line”;
$text[2]=”Second line” and so on.

2. file_get_contents()

This one’s pretty much like file() too. The only difference is that it reads the contents of the file into a string. No arrays.
$text=file_get_contents($fileName);
If the contents in the text file are the same as in the first function, the value of the $text variable would be like.

$text= “First line \n Second line \n Third line \n”;

3. readfile()

This ones a very much different from the other two in the manner it deals with the output. It reads the file and displays it on the screen. For example.
readfile($fileName);
Would output “First line \n Second line \n Third line\n” on to the screen. You cannot store it in a variable.

The little hard way, my way

Remember I told you about php opening the file before reading or writing to it, well.

Meet the big guy fopen(), file opener function.

It does exactly what its name suggests, opens a file to read or write. Now you might be thinking, why open a file where as we can use the easy functions like read or file_get_contents. You’ll have the reason soon, lets see how far the rabbit hole goes.

Something about fopen

But before we continue, fopen unlike all the functions above, takes two arguments.
fopen($fileName, $mode);
The first one as we can see is the filename, but the second one seems a little new. Mode tells fopen the reason we’re opening the file for. See? fopen can be used to open a file for both reading and writing. So if we’re opening the file to read we should specify “r”, the first character in read as mode and if we’re opening it to write we specify “w” as mode. Isn’t that convenient?
Keep in mind that.
“r” is the mode to read
“w” is to write

Alright lets open up the file to read.
$text=fopen($fileName,”r”);
Go ahead, you should try this, chose any text file and open it using fopen().

Lets echo the output now.
echo $text;
Did you see something like this Resource id # some number? What happened there? Well don’t worry its supposed to happen. Using fopen alone doesn’t read a file, it just opens a file for reading. The variable that uses fopen turns into a file handle.

File handle

Lets think of file as a room or a file cabinet. What you we do to see what’s in the room or file cabinet? We open it using our hands :P . File handles are the hands that open the file. They open the file and keep them open till we close them. That makes sense. Doesn’t it?

So $fileHandle=fopen($fileName,”r”);

1. Use fread to read the fopen’ed file

Ok, so fread here’s the function we use to read the opened file. We’ll use fwrite if we need to write, but we’ll discuss it later. This is how we make it read the fopen’ed file. fread has two arguments too damn.

$text=fread($fileHandle, $howMuchWeWantToRead);

$fileHandle’s an important thing here. We must always provide an fopen’d file handle to fread as its first argument. Its our file opening hand :P . fread cannot read a file that’s not opened. The other weird argument $howMuchWeWantToRead like the name suggests read the amount of data we specify in bytes we need it to read. It provides more control over reading the file. If we want it to read the whole file we need to provide it with the full size of the file in bytes. But how to we do that.

filesize() to the rescue

filesize is a very useful function. It provides us with the size of a file in bytes. There are a lot of other uses too. This is how its used.

$size=filesize($fileName);

$size will have the size of the file in bytes. So till now our file reading code should look like this.

$fileHandle=fopen($fileName,”r”);
$size=filesize($fileName);
$text=fread($fileHandle,$size);

Try echo’ing $text now.
echo $text;
Aha, the file has been read and output ed.

Quite a lot of work to open and read a file you might think. But the easy functions do it too, it just does it automatically. Doing it like this helps us know how things work and provides us with more control.

2. fgets

Don’t worry, its the same as fread, use it in case you get bored of fread or need a shorter named function like it. But it has one difference. You don’t need to specify the size of how much you want it to read, it just reads a whole line or till it reaches the end of a line if you don’t specify the length of how much to read. This is how we use it.
$text=fgets($fileHandle,$length[optional]);

You can also use it like this if you don’t wanna specify the size of the file but need to read the whole file.

$text=”;
while(!feof($fileHandle)){
$line=fgets($fileHandle,100);
$text.=$line;
}
echo $text;
Yea, you must have seen the new function feof up there. Its a simple function that checks if the pointer has reached the end of the file. Ah whats a pointer then? Well lets talk about opening a book to read, in order to finish reading it we need to read it line by line till we reach the end. Pointer’s the thing than helps the fileHandle move from line to line. Still not clear? Pointer’s and fileHandles are to the script as our eyes and hands are to us :P . When each loop finishes and each fgets reads the pointer moves further just like us turning pages. I know it sounds weird. But it’ll make sense soon.

feof()

feof’s a function that check’s if the pointer has reached the end of the file. This is how we use it.
feof($fileHandle);

You can use the same method with fread too. Just replace the fgets with fread.

There are a few more functions too, but we’ll just stick to the basic ones for now.

Now that we’ve done some extensive reading on reading files with php lets do some more reading on writing files with php, yay :D .

Write to files

This section’s going to be pretty short since we’ve covered all the basics up there. And like before we have the easy and hard ways and functions to write to a file.

The easy ways

1. file_put_contents

file_put_contents just like file_get_contents with the exception that we use it to write to a file. It takes three arguments. Two necessary and one optional. Here’s how we use it.

file_put_contents($fileName,$data,$option);

It takes a filename and writes $data to it, if the file doesn’t exist it creates it, pretty easy to understand. But the issue is that it overwrites the data in the file if it already exists. That’s when the third argument comes into play. It helps us set optional flag if we don’t want it to overwrite the file. So if we don’t want it to overwrite the data in an already existing file we set FILE_APPEND as the third argument. In this case it just appends the data on top of the existing ones. For example. If the file has data “old data” in it the new data will be appended to it and the file will look like “old data \n new data” now.You can also use the flag or option LOCK_EX which locks the file so that no one else writes to it while we do.

The little hard ways

1. fwrite

fwrite works almost the same as fread, the only difference is that it writes instead of reading and like file_put_contents creates a new file if the file doesn’t exists and appends or overwrites the data in the existing file depending on the mode you specify. This is how we can use it.
fwrite($fileHandle,$data,$maximumAmountOfDataAllowedToBeWritten);
The third argument is optional and is like a safety feature so that we don’t write more data in case we have a limit to write to the file. But you won’t be using it mostly.

Some modes for fopen’ ing a file

‘w’ Open a file to write. Create it if it doesn’t exist.
‘r’ Open a file to read.

‘w+ Open a file to read and write, attempt to create it if it doesn’t exist
‘r+’ Open a file to read and write

‘a’ Open a file in the append mode or don’t overwrite mode :P . Create it if it doesn’t exist.

‘a+’ Open a file in read and append mode. Create if it doesn’t exist.

2. fputs

Same as fwrite.

So that covers the basics of reading and writing files in PHP. Hope it was of some use.

Oh and always fclose what you fopen


PHP may not close the file if it ends prematurely. So its important that we close the file using fclose function, you know just to be safe or it may remained opened :P .

fclose($fileHandle);

This is how we fclose a file. Its not necessary to do this, but its a good coding habit.

Other file handling functions

unlink($fileName)

Deletes the file.

chmod($fileName,$perm)

Changes the permissions on a file.

chown($fileName,$user)

Changes the ownership of a file to $user.

copy($originalFile, $copyFile)

Makes a copy of a file in the destination provided as the first argument to the destination provided in the second argument.

file_exists($pathToTheFile)

Checks if a file exists and returns true or false depending on its existence.

mkdir($dirName,$perm[optional])

Creates a directory of the name $dirName with permission $perm if its specified.

rmdir($dirName)

Removes or deletes an empty directory.If the directory isn’t empty we’ll have to delete all the files in it.

link($fileName,$shortCut)

Creates a link or shortcut to the $fileName in the location or file specified in $shortCut.

basename($fullPathToTheFile, $suffix[optional]):

Given the full path to a file, this function will return the basename or name of the file. Its not much of a use, but who know, we might need it some day.

$name=baseName(“/path/to/file.php”);
//Returns file.php

$name=basename(“path/to/file.php”,”.php”);
//Returns file

PHP IRC Bot using fsockopen

In PHP on May 5, 2010 at 10:02 am

What in the name of Zeus is fsockopen?

If you didn’t already know, fsockopen is a function in enables us to connect to remote hosts by opening sockets to them. Have you heard some Linux user say everything in Linux is a file? Apparently fsockopen treats sockets like files too. You know what this means don’t you, We can use it like fopen to read and write from those open socket using functions like fwrite and fread. I think you can think of some cool uses for it already :P .

Things you need to know

The only thing I assume you know to completely understand this article is the basics of PHP.

Alright, so how do I create an IRC Bot?

Have you seen those fancy IRC bots and wondered how you can make them? Maybe not. But if you have, you’re in luck, because that’s what we’re gonna do in this article. Build an IRC bot, and its easy too. Woohoo :D .

But first some basic IRC commands

NICK: Sets the nick or display name you want to use in an IRC server or channel.

USER: I think its the same as nick, I’m not sure because, IRC clients like mIRC often set this variable as username on local computer. You can use the same value for for nick and user.

JOIN: Join a channel.

PART: Leave a channel

MSG: Send message to a user.

PRIVMSG: Like MSG but you can also use to send messages to channels.

QUIT: Quit IRC all together.

These are the commands we’re going to be using here. You can find more here.

How it works

Like I said fsockopen’s pretty much like fopen. So all we have to do is open a connection to the IRC server using.

$nick=”Bot”
$host=”irc.dal.net”;
$port=6667;
$chan=”";
$fp=fsockopen($host,$port);

Now that the connection’s been opened we can send data to the server using fwrite or fputs. Its as easy as writing to files.

Heres how we login to the server.
fwrite($fp,”NICK $nick\r\n”);
fwrite($fp,”USER localuser $host erl: luser \r\n”);
fwrite($fp, “JOIN #chan \r\n”);
fwrite($fp,”PRIVMSG #chan Hi, I’m an IRC bot\r\n”);

Its important that each command we send ends with “\r\n” because it simulates the return or enter key press that we normally do on terminal, it helps the server know that we’re issuing a command. And in order to keep it running we’ll need to implement a while loop so that it doesn’t end till we want it to.

while($msg=fgets($fp,200)){

$msg=explode(“:ping”,$msg);

$msg[0]==’ping’?fwrite($fp,”PONG “.$msg[1].”\r\n”):”";

//This checks for any line with JOIN in them, gets the nick of the person who joined the chat or channel and greets them

preg_match(“/:(.*)\!.* JOIN :.*/Ui”,$msg,$nick)?fwrite($fp,”PRIVMSG #php hello “.$nick[1].”\r\n”):”";

echo $msg.”\n”;
}

Everything in the code above’s pretty straight forward except for the line that checks ping requests and preg_match thats checks for new people joining the channels and greets them. The IRC’s protocol requires the server to check if the user has timed out or gone offline so that it can close the connection, that’s the reason why it sends :ping requests all the time, if we don’t respond with pong and the message to it the connection gets close.

The whole code would look like this.

Running it from the terminal

Its better to run it from the terminal because its easy to close using the Ctrl+c or z buttons rather than closing the browser tab. In order to run it from the terminal do this.

cd /to/the/script’s/location
php scriptname.php

Teaching it more tricks

There are a lot of things you can make it do like trivia games, or output random quotes or jokes, display google, and stuff like that. But its outside the scope of this article. The functions you need to make it do all those things are fsockopen, cURL and regexp.

Create a simple drop down menu with CSS

In CSS on May 3, 2010 at 2:09 pm

Drop down menus aren’t very hard to make, especially with CSS. If take a look at how it works, all it does is show up when you hover the mouse over a button and disappear when you move the mouse away.
So it mustn’t be that hard to make one right? Correct. I bet anyone with basic knowledge in HTML and CSS can build it in under 10 minutes or you can have your money back, oh we don’t have any money involved here, too many tele ads I guess. When we’re done the finished product would look something like this :P .

Download.

We can do it using a few unordered lists and a maximum of six CSS rules. Don’t believe me, look at the code. This is what our markup code should be.
<ul id=”menu”>
<ul>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</li>
Menu 1</ul>
<ul>
<li>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</li>
Menu 2</ul>
<ul>
<li>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</li>
Menu 3</ul>
</li>
</ul>
See what happened up there? We have a main <ul> tag with id named menu, each sub <ul> tags are treated as the visible part of the menu and sub-sub
<ul> tags under the them are hidden, they’re the drop down part of the menu. But markup alone doesn’t do anything we need CSS to do its thing here.

Alright, so what kind of CSS voodoo do we use do make some element disappear? Aha, display: hidden or display: none . But we’re gonna be using display:none because the hidden property seems to function weird on some browsers. Now that we’ve managed to hide the “drop down” menu’s we need to find some way to make them re-appear once mouse is hovered over the main menu. That is when someone hovers the mouse over menu 1, 2 or 3, we need the ul with items 1, 2 and 3 to appear. Thats when :hover comes into play. Its the property of CSS that lets us do something when mouse is hovered over an element. Our drop down menu’s done. The CSS part of the menu looks like this.

*{padding:0px;margin:0px;}

#menu{float:left;padding:0px;}

#menu ul{background:#131313;color:#ffffff;text-align:center;
background:url(menub.jpg);border-left:1px solid #343434;float:left;
padding:3px;list-style:none;width:100px;}

#menu ul ul{display:none;position:absolute;background:#131313;
color:#ffffff;text-align:center;padding:0px;margin:-4px;border:none;
width:100px;padding:4px;}

#menu ul ul li{float:left;border:1px solid #343434;width:99px;
clear:both;}

#menu ul:hover ul{display:block;}
#menu ul ul li:hover{background:url(hovb.jpg);color:#131313;
border:1px solid #fdae16}

Told you, easy peasy . Are the 10 minutes over yet? Make it 20 if it is.

The ie6 fix


Sorry it took me this long to update this. Looks like ie6, Microsoft’s wrath on mankind doesn’t know how to handle the :hover property in CSS. One solution for this will be that everyone switch to another way cooler browser like firefox chrome or opera, nah just kidding :P , that’s easier said than done. So lets see what we can do with some javascript using onmouseover, onmouseout events and setAttribute function. I was trying to keep pure from any script, but

file: menu.js

Follow

Get every new post delivered to your Inbox.