Tags

, ,

object-oriented-design-patterns-in-php7 for web

object-oriented-design-patterns-in-php7 for web

There are several methods available for file opening, reading and writing.
Let’s check them one by one.
The first example deals with while() loop and feof() function. It returns true when you are at the end of the file. The code is like this:

/* 
 * Opening, reading and closing a file
 */
$handle = fopen("file.txt", "r");
while (!feof($handle)) {
    $text = fgets($handle);
    echo $text ;    
}
fclose($handle);

At the end of the file, while() loop returns true, and you can read the entire file.
When you’re done with the file reading, don’t forget to close the file by fclose() function. It frees up the resource so that if you want to work with the same handle later, it avoids any other conflict.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books. You can buy from either Leanpub or Amazon or from my publisher Apress.

As always we can also read a file by character with fgetc() function.

/* 
 * Opening, reading by character and closing a file
 */
$handle = fopen("file.txt", "r");

while ($char = fgetc($handle)) {    
    if($char == "\n"){
        $char = ; // use the br tag for n
    }
    echo $char";    
}
fclose($handle);

Here you start by opening the file to read from, file.txt. Next, we loop over all the characters.
You can read a file just like an array. Each line acts like a $key. And the $value denotes the line. You can also var_dump() the whole file and see what is inside.

/* 
 * reading a file into an array
 * each line is a new value
 */

$data = file("file.txt");
//var_dump($data);
foreach ($data as $key => $value) {
    echo $key . " = " . $value;
}

In the above code, we’ve used the file() function. This file() function can get the file data in array type, so that you can loop over it, and read the lines one by one.
Uploading a file is also easy.

This type of form is special. We need to mention the type, method and the action-destination in the first line.
And then in the “file-process.php” file we catch the file data as an array.


/* 
 * to get the file data
 */

/*
$handle = fopen($_FILES['userfile'] ['tmp_name'], "r");

while (!feof($handle)) {
    $file = fgets($handle);
    echo $file;
}
fclose($handle);
*/

$handle = file_get_contents($_FILES['userfile'] ['tmp_name'], "r");

$full_text = str_replace("\n", "br", $handle);

echo $full_text;

We can catch them either way. By using the while loop, which is commented out here. Or we can catch the file data by superglobal array $_FILE[‘input-name’] using file_get_contents() function.
Reading files in one go, is always important.
There are functions that might come to our help.

/* 
 * reading a whole file at once
 * 
 */
$handle = file_get_contents("file.txt");
$full_text = str_replace("\n" , "br", $handle);
echo $full_text;

In the above code we get the contents of the file “file.txt” in one go. And after that, we have used str_replace() php-built-in function to format it properly; so that line breaks and we can read the file in our web page.
Suppose, you want to work with a file, that doesn’t exist at all. In such cases, an unnecessary error page will show up. We don’t want this in our production server.
To prevent this, you need to check if a file exists with the file_exists() function.
If a file doesn’t exist, you can display a message to that effect. It is better than an ugly error page!


$filename = "file.txt";
if (file_exists($filename)){
    $data = file($filename);
    foreach ($data as $key => $value) {
        echo "Line number : {$key} : " . $value;
        echo "The file size is " . filesize($filename) . " bytes long.";
    }
}
else{
    throw new Exception($filename . " does not exist");
}

You can run the code and see the result yourself.
So far you have seen that the files have been handled as text files. You can handle them in a binary way as well using a function like fread().
But there is one thing, that you have to understand. When you are going to read a file binary way, you need to determine the file-size also.
You can always know the file size of any file by filesize() function. And at the same time you can use this function to read any file binary way.


$handle = fopen($filename, "rb");
$text = fread($handle, filesize($filename));
$full_text = str_replace("\n", "br", $text);
echo $full_text;
fclose($handle);

Remember, the mode is “rb”, that is read binary.
The file handling power of php is limitless. You can do so many things with simple commands.
Suppose you have a list of names in a text file. You can read the first-name and second-name in an array type or any format that suits you.
The function fscanf($handle, string $format); comes handy when you want to format a string of same type. If the names are separated by tabs, you can easily get the output by this function.


$handle1 = fopen($filename, "r");
while ($file = fscanf($handle1, "%s\t%s\n")) {
    list($word1, $word2) = $file;    
    echo $word1, " ", $word2;
}
fclose($handle1);

Parsing file is also important when you want to parse ‘ini’ files. The ‘ini’ files refer to the initialization files that Windows OS and other operating systems require. Installing php also comes with a ‘php.ini’ file. Don’t try to parse it this way.
Also remember, there are lots of reserved keywords for php. You cannot use them as keys for ‘ini’ files.
We use parse_ini_file() function to get the contents in an associative array. If you set the ‘process_sections’ parameter true, you get a multidimensional array.
We’ll again come to the ‘parsing section’, but before that knowing file information is important.
Getting file information becomes easier with the stat( $filename ) function.
Consider this code before proceeding further.


$filename = "file.txt";
$array = stat($filename);
echo "The file device number is :" . $array['dev'];
echo "The file Inode number is :" . $array['ino'] ";
echo "The file userID of owner is :" . $array['uid'];
echo "The file group ID of owner is :" . $array['gid'];
echo "The file size is :" . $array['size'];
echo "The file time of last access is :" . $array['atime'];
echo "The file time of last modification is :" . $array['mtime'];

Using stat() function we have got an array of values. We have used array[$key] to get the value. Let’s clarify one after another. $array[‘dev’] stands for device name. The second one $array[‘ino’] is Inode number. You could have also known Inode protection mode by using $array[‘mode’].
The ‘uid’ and ‘gid’ is user ID and group ID of the owner. Now, it makes sense for the Unix machines. You can get the file-size by ‘size’ key. You can also know the time of last access and last modification by ‘atime’ and ‘mtime’.
Now let’s come to the parsing ‘ini’ file again. Before parsing the file we need to create an ‘ini’ file. Suppose it is ‘sample.ini’ file.

; last modified 1 April 2018 by Sanjib Sinha
[owner]
name=Sanjib Sinha
LastLocated=Las Vegas.

[book]
; use git to get code
file="/usr/local/bin/book.code"
URL="http://www.sanjibsinha.com"

Here we have started with a comment. Next part – ‘book’ and ‘owner’ are the sections.


echo '
How to parse .ini file';

$filename = "sample.ini";
$array = parse_ini_file($filename);
foreach ($array as $key => $value) {
    echo "
 {$key} = {$value}";
}

And here is the output.

name = Sanjib Sinha 
 LastLocated = Las Vegas. 
 file = /usr/local/bin/book.code 
 URL = http://www.sanjibsinha.com 
The output recovers the values as we have gone through a loop and read the array key one by one. The keys and values are displayed one after another.
You can also delete this ‘sample.ini’ file or any file by a simple function unlink( $filename ). Using if-else logic, you can get a nice output of your result. 
Copying any file is extremely easy. The function copy($filename, $dest, $context); means you need a source file. The second parameter stands for the destination file. The third parameter is optional. If you want to copy any file to a URL, the copy operation may fail. It depends on one thing. If the wrapper does not support overwriting the existing file, it will fail. If it allows, then the existing file is overwritten. 
In our code, we copy a file to a local folder.
$filename = "file.txt";
$copy = "copy.txt";

if(copy($filename, $copy)){
    echo 'Copied ' . $filename;
}
else{
    echo 'Could not copy ' . $filename;
}

We copy ‘file.txt’ and the new file is automatically saved as ‘copy.txt’.
So far we have seen many functions that involve mainly file reading. File writing in php is also super easy. You need to set up your system before you want to write files. In Windows you can right-click the folder and click the Web-Sharing tab. In Linux based system you can open the terminal and type this command:

sudo chmod +w file.txt 

You can even make it executable by issuing this command:

sudo chmod 777 file.txt