Monday 24 November 2014

Expire Header | Cache-Control Header | Best Practice to Speed up your website

There are two aspects to this rule:
  • For static components: implement “Never expire” policy by setting far future Expires header
  • For dynamic components: use an appropriate Cache-Control header to help the browser with conditional requests
For rich interface websites for first-time visitor to your page may have to make several HTTP requests, but by using the Expires header you make those components cacheable. This avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often used with images, but they should be used on all components including scripts, stylesheets, and Flash components.
Browsers user cache to reduce the number and size of the HTTP requests and making the page loads faster. A we server uses expire header in HTTP request to tell the client ( Browser ) how long a component can be cached.
Expires: Thu, 15 Apr 2010 20:00:00 GMT

Above line will tell browser to cache the component in the HTTP request to until 15 April 2010.
If your server is Apache, use the ExpiresDefault directive to set an expiration date relative to the current date. This example of the ExpiresDefault directive sets the Expires date 10 years out from the time of the request.
ExpiresDefault "access plus 10 years"

This trick works only if user have already visited your site once. This has no effect in performance if the user if visiting your website for first time using empty cache.
By using a far future Expires header, you increase the number of components that are cached by the browser and re-used on subsequent page views without sending a single byte over the user’s Internet connection.

PHP array search

Search in array



Somtimes you have a quite big array which is filled up from a file or code. In this case you don't know whether a given value exists in the array or not. And if it exists then it would be fine to get the key of this element. 

Let's suppose you have the following array: 
Code:
  1. $colorList = array("apple"=>"red",
  2. "grass"=>"green",
  3. "sky"=>"blue",
  4. "night"=>"black",
  5. "wall"=>"white");

Now if you want to know whether the value "blue" exists you can use the PHP built in functionarray_search(). With this you can easy get this information in the following way: 
Code:
  1. echo 'Blue is '.array_search("blue",$colorList);

PHP heredoc syntax

PHP heredoc syntax



Heredoc is a robust way to create string in PHP with more lines but without using quotations. Heredoc is rarely used as the day by day usage is more complicated as creating strings with quotes or double quotes. Besides this the not properly used heredoc can lead to problems in your code.
However if you want to use it you can do it in the following way:
Code:
  1. <?php
  2. $str = <<<DEMO
  3. This is a
  4. demo message
  5. with heredoc.
  6. DEMO;
  7.  
  8. echo $str;
  9. ?>
Output:
This is a demo message with heredoc.
As you see the heredoc starts with the <<< operator and an identifier. After it you can type your text in more lines as if it were a double quoted string. It means that you can use variables inside the heredoc. If you are ready with your text you only need to write the identifier again in a new line as follows:
Code:
  1. <?php
  2. $name = "Max";
  3. $str = <<<DEMO
  4. Hello $name! <br/>
  5. This is a
  6. demo message
  7. with heredoc.
  8. DEMO;
  9.  
  10. echo $str;
  11. ?>

PHP file write

Write into a file with PHP



In cases when you want to store some data, log user activity or anything else you may want to store this information in a file. To do this there are 3 basic steps you need to do:
  • Open the file
  • Write your data
  • Close the file

Step 1.
If you want to write into a file you need to open it for writing. You have 2 possibilities depending on what you need:
  • w - Truncate the file so all data will be lost. If the file does not exist, attempt to create it.  
  • a - Writes to the end of the existing file. If the file does not exist, attempt to create it.
If opening of the file was not success then fopen returns with FALSE

So the PHP code looks like this:
Code:
  1. $fileName = 'test.txt';
  2. $file = fopen($fileName,'w');
  3. if ($file === FALSE) {
  4.     echo "Can’t open file!";
  5. }
  6.  
If the filename is not only a simple file but contains a path as well then you should use the built in DIRECTORY_SEPARATOR constant to be cross platform compatible as follows:
Code:
  1. $fileName = 'log' . DIRECTORY_SEPARATOR . 'error' . DIRECTORY_SEPARATOR . 'error.log';
Don’t forget that if the file doesn’t exist then it will be created only if the path exists. So if you use the above example and the log/error directory doesn’t exists then you will get an error.
Step 2.
At this point we have a valid file resource and so we can use it to write some data into it.
To write into a file you need to use the fwrite() function.

The synatx:
Code:
  1. int fwrite ( resource $handle , string $string [, int $length ] )
Explanation:
  • resource $handle : This is the resource variable what was the return value of the fopen function. In our example it is the $file
  • string $string : This is the data what we want to write into the file. The data is simply a string.
  • int $length : This parameter is optional and limits the maximum number of characters written into the file. If you want to write “Hello World” but the length is set to 5 then only the word “Hello” will be written in the file.
Now try to write out a simple message:
Code:
  1. $text = "This is a simple message";
  2. fwrite($file, $text);
  3.  
Now if you want to write an other text you simply call fwrite again:
Code:
  1. fwrite($file, “Other text”);
If you checks the content of the file you will see the following:
Code:
  1. This is a simple messageOther text
Everything is in one line. If you want to write in separate lines then you need to write newline characters also. You can do this in a cross platform compatible way by using the built in constant PHP_EOL. So the code looks like this:
Code:
  1. $text = "This is a simple message" . PHP_EOL;
  2. fwrite($file, $text);
  3. fwrite($file, "Other text" . PHP_EOL);
  4.  
Step 3.
This is a very simple step, you simply need to close the file with fclose as here:
Code:
  1. fclose($file);
That's all about writing into a file with PHP.
The complete code looks like this:
Code:
  1. $fileName = 'test.txt';
  2. $file = fopen($fileName,'w');
  3. if ($file === FALSE) {
  4.     echo "Can’t open file!";
  5. }
  6.  
  7. $text = "This is a simple message" . PHP_EOL;
  8. fwrite($file, $text);
  9. fwrite($file, "Other text" . PHP_EOL);
  10.  
  11. fclose($file);

PHP file read

PHP file read methods


PHP file read
There are many different ways how you can read the content of a file. 

Step 1.
First of all you need to open the file for reading using the fopen function. You need to provide the filename as parameter and you also need to define to open mode which is in case of reading the 'r'. Before any real reading begins you also need to check if file opening was success.
Code:
  1. $fileName = 'test.txt';
  2. $fileRes = fopen($fileName,'r');
  3. if ($fileRes === FALSE) {
  4.     echo 'Can not open file!';
  5. }
  6.  
You can also check the file readability before trying to open it using theis_readable function as follows:
Code:
  1. $isReadable = is_readable($fileName);
Step 2.
So if the opening of the file was success then we can try to read some data from it. There are more solutions to do this:
  • Read the file at once into a string at once
  • Read the file at once into an array
  • Read the file line by line
  • Read the file block by block
Let's see them one by one. The most basic function to read a file is fread.

The syntax:
Code:
  1. string fread ( resource $handle , int $length )
Using fread you can read the complete file at once if you set the length parameter as big as the file size. You can use the filesize() function to do this and so you get the file content:
Code:
  1. $content = fread($fileRes, filesize($fileName));
You also can read the complete content by using the file_get_contents function like this:
Code:
  1. $content = file_get_contents($fileName);
Don’t forget that in this case you don’t need to open the file before reading. Thefile_get_contents do everything for you, you only need to provide the filename as parameter. Of course a readability check is recommended also in this way.

If the file is huge and/or you don’t want to read the complete content at once you can use fread to get the file content block by block in the following way:
Code:
  1. while (!feof($fileRes)) {
  2.   $block = fread($fileRes, 8192);
  3. }
You also can read the file content line by line using the fgets function. 
Code:
  1. while (!feof($fileRes)) {
  2.   $line = fgets($fileRes);
  3. }
It is also possible to read the complete file at once into an array using the filefunction. In this case every line of the file will be an element of the array. So if your file has 10 lines of text then you will get a string array with 10 elements. Thefile function similar to file_get_contents doesn’t require to use fopen. You need to provide the filename instead of file resource as parameter.
Code:
  1. $contentArray = file($fileName);
Step 3.
If you have used fopen to open a file you also need to close that file after you readed what you want. You can do this simple with fclose:
Code:
  1. fclose($fileRes);

As summary:
You need to use fopen, fclose and a file resource with fread and fgets.
You can simply use file and file_get_contents with a filename and no fopen, fclose is needed.

PHP in_array function usage examples

In cases when you want to check whether a value exists in an array you can use the in_array function. This function checks if a value exists in an array. You can use it from PHP version 4. The syntax is the following:
bool in_array ( mixed $what , array $where [, bool $strict = FALSE ] )
By default you simply use only the 2 mandatory parameters ($what and $where) as you can see in the following example:
Code:
  1. $myArray = array("Audi","BMW","Lexus","Mercedes");
  2.  
  3. var_dump($myArray);
  4.  
  5. if (in_array("Lexus", $myArray)) {
  6.     echo "Lexus was found in the array<br/>";
  7. }
  8.  
  9. if (in_array("opel", $myArray)) {
  10.     echo "Opel was found in the array<br/>";
  11. }
  12.  
The strict parameter:
If you want to force th in_array function to check also variable types then, you need to set the optional strict parameter to true as you can see in the next code example:
Code:
  1. $myArray = array(10,20,30,40,50);
  2.  
  3. var_dump($myArray);
  4.  
  5. if (in_array("10", $myArray)) {
  6.     echo "A - 10 was found as string in the array without strict<br/>";
  7. }
  8.  
  9. if (in_array("10", $myArray, TRUE)) {
  10.     echo "B - 10 was found as string in the array using strict<br/>";
  11. }
Using in_array to find key in an associative array. 
The in_array function only checks the values in the array and so if you want to check the keys in case of an associative array then you need to use the array_key_exists function as demonstrated below:
Code:
  1. $myArray = array("Audi"=>"A4","Audi"=>"A6","Lexus"=>"IS","Lexus"=>"LS");
  2.  
  3. var_dump($myArray);
  4.  
  5. if (in_array("Lexus", $myArray)) {
  6.     echo "Lexus was found in the array<br/>"; 
  7. }
  8.  
  9. if (array_key_exists("Lexus", $myArray)) {
  10.     echo "Lexus key was found in the array<br/>";
  11. }
  12.  
Using in_array to find values in a multidimensional array. 
The next general question is how to find a value in a multidimensional array. Unfortunately in_array is not able to handle multidimensional arrays so you need to create your own function to solve this problem. However with a simple recursive function you can do this as you can see in the next example code:
Code:
  1. function in_array_multi($needle, $haystack) {
  2.     foreach ($haystack as $item) {
  3.         if ($item === $needle || (is_array($item) && in_array_multi($needle, $item))) {
  4.             return true;
  5.         }
  6.     }
  7.  
  8.     return false;
  9. }
  10.  
  11. $myArray = array(array(10,20),array(11,22),array(111,222));
  12.  
  13. var_dump($myArray);
  14.  
  15. if (in_array(11, $myArray)) {
  16.     echo "11 was found";
  17. }
  18.  
  19. if (in_array_multi(11, $myArray)) {
  20.     echo "11 was found with multi";
  21. }