I'll begin with something simple - opening a file and reading its contents. Let's assume that we have a text file called "mindspace.txt", containing the following random thoughts:
Now, in order to read this data into a PHP script, I need to open this file and assign it a file handle - I can then use this file handle to interact with the file and extract its contents into a PHP variable. Take a look:
And when you run this script, PHP should return the contents of the file "mindspace.txt", with a message at the end. A quick explanation: in order to read data from an external file, PHP requires you to define a file handle for it with the fopen() function. I've done this in the very first line of the script above.
You can specify a full path to the file as well:
Notice the second argument to fopen() - it's a string indicating the "mode" in which the file is to be opened. A number of modes are available - read, write, append and so on - and I'll discuss them in detail a little further along. If the fopen() function is successful, it returns a file handle (stored in
The second argument to fread() is the number of bytes to be read. In this case, I've used the filesize() function to obtain the size of the file in bytes and provide that number to the fread() function; you can set an arbitrary value here if you like, but be warned that reading will automatically stop once the end of the file is reached. Once the file contents have been read into a variable with fread(), the
blog comments powered by Disqus |