Wednesday, 7 August 2013

9 Useful PHP Functions and Features You Need to Know

Even after using PHP for years, we stumble upon functions and features that we did not know about. Some of these can be quite useful, yet underused. With that in mind, I’ve compiled a list of nine incredibly useful PHP functions and features that you should be familiar with.

1. Functions with Arbitrary Number of Arguments

You may already know that PHP allows you to define functions with optional arguments. But there is also a method for allowing completely arbitrary number of function arguments.
First, here is an example with just optional arguments:
  1. // function with 2 optional arguments  
  2. function foo($arg1 = ''$arg2 = '') {  
  3.   
  4.     echo "arg1: $arg1\n";  
  5.     echo "arg2: $arg2\n";  
  6.   
  7. }  
  8. foo('hello','world');  
  9. /* prints: 
  10. arg1: hello 
  11. arg2: world 
  12. */  
  13.   
  14. foo();  
  15. /* prints: 
  16. arg1: 
  17. arg2: 
  18. */  
Now, let’s see how we can build a function that accepts any number of arguments. This time we are going to utilize func_get_args():
  1. // yes, the argument list can be empty  
  2. function foo() {  
  3.   
  4.     // returns an array of all passed arguments  
  5.     $args = func_get_args();  
  6.   
  7.     foreach ($args as $k => $v) {  
  8.         echo "arg".($k+1).": $v\n";  
  9.     }  
  10.   
  11. }  
  12.   
  13. foo();  
  14. /* prints nothing */  
  15.   
  16. foo('hello');  
  17. /* prints 
  18. arg1: hello 
  19. */  
  20.   
  21. foo('hello''world''again');  
  22. /* prints 
  23. arg1: hello 
  24. arg2: world 
  25. arg3: again 
  26. */  

2. Using Glob() to Find Files

Many PHP functions have long and descriptive names. However it may be hard to tell what a function named glob() does unless you are already familiar with that term from elsewhere.
Think of it like a more capable version of the scandir() function. It can let you search for files by using patterns.
  1. // get all php files  
  2. $files = glob('*.php');  
  3.   
  4. print_r($files);  
  5. /* output looks like: 
  6. Array 
  7. ( 
  8.     [0] => phptest.php 
  9.     [1] => pi.php 
  10.     [2] => post_output.php 
  11.     [3] => test.php 
  12. ) 
  13. */  
You can fetch multiple file types like this:
  1. // get all php files AND txt files  
  2. $files = glob('*.{php,txt}', GLOB_BRACE);  
  3.   
  4. print_r($files);  
  5. /* output looks like: 
  6. Array 
  7. ( 
  8.     [0] => phptest.php 
  9.     [1] => pi.php 
  10.     [2] => post_output.php 
  11.     [3] => test.php 
  12.     [4] => log.txt 
  13.     [5] => test.txt 
  14. ) 
  15. */  
Note that the files can actually be returned with a path, depending on your query:
  1. $files = glob('../images/a*.jpg');  
  2.   
  3. print_r($files);  
  4. /* output looks like: 
  5. Array 
  6. ( 
  7.     [0] => ../images/apple.jpg 
  8.     [1] => ../images/art.jpg 
  9. ) 
  10. */  
If you want to get the full path to each file, you can just call the realpath() function on the returned values:
  1. $files = glob('../images/a*.jpg');  
  2.   
  3. // applies the function to each array element  
  4. $files = array_map('realpath',$files);  
  5.   
  6. print_r($files);  
  7. /* output looks like: 
  8. Array 
  9. ( 
  10.     [0] => C:\wamp\www\images\apple.jpg 
  11.     [1] => C:\wamp\www\images\art.jpg 
  12. ) 
  13. */  

3. Memory Usage Information

By observing the memory usage of your scripts, you may be able optimize your code better.
PHP has a garbage collector and a pretty complex memory manager. The amount of memory being used by your script. can go up and down during the execution of a script. To get the current memory usage, we can use the memory_get_usage() function, and to get the highest amount of memory used at any point, we can use the memory_get_peak_usage() function.
  1. echo "Initial: ".memory_get_usage()." bytes \n";  
  2. /* prints 
  3. Initial: 361400 bytes 
  4. */  
  5.   
  6. // let's use up some memory  
  7. for ($i = 0; $i < 100000; $i++) {  
  8.     $array []= md5($i);  
  9. }  
  10.   
  11. // let's remove half of the array  
  12. for ($i = 0; $i < 100000; $i++) {  
  13.     unset($array[$i]);  
  14. }  
  15.   
  16. echo "Final: ".memory_get_usage()." bytes \n";  
  17. /* prints 
  18. Final: 885912 bytes 
  19. */  
  20.   
  21. echo "Peak: ".memory_get_peak_usage()." bytes \n";  
  22. /* prints 
  23. Peak: 13687072 bytes 
  24. */  

4. CPU Usage Information

For this, we are going to utilize the getrusage() function. Keep in mind that this is not available on Windows platforms.
  1. print_r(getrusage());  
  2. /* prints 
  3. Array 
  4. ( 
  5.     [ru_oublock] => 0 
  6.     [ru_inblock] => 0 
  7.     [ru_msgsnd] => 2 
  8.     [ru_msgrcv] => 3 
  9.     [ru_maxrss] => 12692 
  10.     [ru_ixrss] => 764 
  11.     [ru_idrss] => 3864 
  12.     [ru_minflt] => 94 
  13.     [ru_majflt] => 0 
  14.     [ru_nsignals] => 1 
  15.     [ru_nvcsw] => 67 
  16.     [ru_nivcsw] => 4 
  17.     [ru_nswap] => 0 
  18.     [ru_utime.tv_usec] => 0 
  19.     [ru_utime.tv_sec] => 0 
  20.     [ru_stime.tv_usec] => 6269 
  21.     [ru_stime.tv_sec] => 0 
  22. ) 
  23.  
  24. */  
That may look a bit cryptic unless you already have a system administration background. Here is the explanation of each value (you don't need to memorize these):
  • ru_oublock: block output operations
  • ru_inblock: block input operations
  • ru_msgsnd: messages sent
  • ru_msgrcv: messages received
  • ru_maxrss: maximum resident set size
  • ru_ixrss: integral shared memory size
  • ru_idrss: integral unshared data size
  • ru_minflt: page reclaims
  • ru_majflt: page faults
  • ru_nsignals: signals received
  • ru_nvcsw: voluntary context switches
  • ru_nivcsw: involuntary context switches
  • ru_nswap: swaps
  • ru_utime.tv_usec: user time used (microseconds)
  • ru_utime.tv_sec: user time used (seconds)
  • ru_stime.tv_usec: system time used (microseconds)
  • ru_stime.tv_sec: system time used (seconds)
To see how much CPU power the script has consumed, we need to look at the 'user time' and 'system time' values. The seconds and microseconds portions are provided separately by default. You can divide the microseconds value by 1 million, and add it to the seconds value, to get the total seconds as a decimal number.
Let's see an example:
  1. // sleep for 3 seconds (non-busy)  
  2. sleep(3);  
  3.   
  4. $data = getrusage();  
  5. echo "User time: ".  
  6.     ($data['ru_utime.tv_sec'] +  
  7.     $data['ru_utime.tv_usec'] / 1000000);  
  8. echo "System time: ".  
  9.     ($data['ru_stime.tv_sec'] +  
  10.     $data['ru_stime.tv_usec'] / 1000000);  
  11.   
  12. /* prints 
  13. User time: 0.011552 
  14. System time: 0 
  15. */  
Even though the script took about 3 seconds to run, the CPU usage was very very low. Because during the sleep operation, the script actually does not consume CPU resources. There are many other tasks that may take real time, but may not use CPU time, like waiting for disk operations. So as you see, the CPU usage and the actual length of the runtime are not always the same.
Here is another example:
  1. // loop 10 million times (busy)  
  2. for($i=0;$i<10000000;$i++) {  
  3.   
  4. }  
  5.   
  6. $data = getrusage();  
  7. echo "User time: ".  
  8.     ($data['ru_utime.tv_sec'] +  
  9.     $data['ru_utime.tv_usec'] / 1000000);  
  10. echo "System time: ".  
  11.     ($data['ru_stime.tv_sec'] +  
  12.     $data['ru_stime.tv_usec'] / 1000000);  
  13.   
  14. /* prints 
  15. User time: 1.424592 
  16. System time: 0.004204 
  17. */  
That took about 1.4 seconds of CPU time, almost all of which was user time, since there were no system calls.
System Time is the amount of time the CPU spends performing system calls for the kernel on the program's behalf. Here is an example of that:
  1. $start = microtime(true);  
  2. // keep calling microtime for about 3 seconds  
  3. while(microtime(true) - $start < 3) {  
  4.   
  5. }  
  6.   
  7. $data = getrusage();  
  8. echo "User time: ".  
  9.     ($data['ru_utime.tv_sec'] +  
  10.     $data['ru_utime.tv_usec'] / 1000000);  
  11. echo "System time: ".  
  12.     ($data['ru_stime.tv_sec'] +  
  13.     $data['ru_stime.tv_usec'] / 1000000);  
  14.   
  15. /* prints 
  16. User time: 1.088171 
  17. System time: 1.675315 
  18. */  
Now we have quite a bit of system time usage. This is because the script calls the microtime() function many times, which performs a request through the operating system to fetch the time.
Also you may notice the numbers do not quite add up to 3 seconds. This is because there were probably other processes on the server as well, and the script was not using 100% CPU for the whole duration of the 3 seconds.

5. Magic Constants

PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__).
We are not going to cover each one of these in this article, but I will show you a few use cases.
When including other scripts, it is a good idea to utilize the __FILE__ constant (or also __DIR__ , as of PHP 5.3):
  1. // this is relative to the loaded script's path  
  2. // it may cause problems when running scripts from different directories  
  3. require_once('config/database.php'); 
  4.  
  5. // this is always relative to this file's path  
  6. // no matter where it was included from  
  7. require_once(dirname(__FILE__) . '/config/database.php');  
Using __LINE__ makes debugging easier. You can track down the line numbers:
  1. // some code  
  2. // ...  
  3. my_debug("some debug message"__LINE__);  
  4. /* prints 
  5. Line 4: some debug message 
  6. */  
  7.   
  8. // some more code  
  9. // ...  
  10. my_debug("another debug message"__LINE__);  
  11. /* prints 
  12. Line 11: another debug message 
  13. */  
  14.   
  15. function my_debug($msg$line) {  
  16.     echo "Line $line: $msg\n";  
  17. }  

6. Generating Unique ID's

There may be situations where you need to generate a unique string. I have seen many people use the md5() function for this, even though it's not exactly meant for this purpose:
  1. // generate unique string  
  2. echo md5(time() . mt_rand(1,1000000));  
There is actually a PHP function named uniqid() that is meant to be used for this.
  1. // generate unique string  
  2. echo uniqid();  
  3. /* prints 
  4. 4bd67c947233e 
  5. */  
  6.   
  7. // generate another unique string  
  8. echo uniqid();  
  9. /* prints 
  10. 4bd67c9472340 
  11. */  
You may notice that even though the strings are unique, they seem similar for the first several characters. This is because the generated string is related to the server time. This actually has a nice side effect, as every new generated id comes later in alphabetical order, so they can be sorted.
To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy:
  1. // with prefix  
  2. echo uniqid('foo_');  
  3. /* prints 
  4. foo_4bd67d6cd8b8f 
  5. */  
  6.   
  7. // with more entropy  
  8. echo uniqid('',true);  
  9. /* prints 
  10. 4bd67d6cd8b926.12135106 
  11. */  
  12.   
  13. // both  
  14. echo uniqid('bar_',true);  
  15. /* prints 
  16. bar_4bd67da367b650.43684647 
  17. */  
This function will generate shorter strings than md5(), which will also save you some space.

7. Serialization

Have you ever needed to store a complex variable in a database or a text file? You do not have to come up with a fancy solution to convert your arrays or objects into formatted strings, as PHP already has functions for this purpose.
There are two popular methods of serializing variables. Here is an example that uses the serialize() and unserialize():
  1. // a complex array  
  2. $myvar = array(  
  3.     'hello',  
  4.     42,  
  5.     array(1,'two'),  
  6.     'apple'  
  7. );  
  8.   
  9. // convert to a string  
  10. $string = serialize($myvar);  
  11.   
  12. echo $string;  
  13. /* prints 
  14. a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";} 
  15. */  
  16.   
  17. // you can reproduce the original variable  
  18. $newvar = unserialize($string);  
  19.   
  20. print_r($newvar);  
  21. /* prints 
  22. Array 
  23. ( 
  24.     [0] => hello 
  25.     [1] => 42 
  26.     [2] => Array 
  27.         ( 
  28.             [0] => 1 
  29.             [1] => two 
  30.         ) 
  31.  
  32.     [3] => apple 
  33. ) 
  34. */  
This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode() functions as well:
  1. // a complex array  
  2. $myvar = array(  
  3.     'hello',  
  4.     42,  
  5.     array(1,'two'),  
  6.     'apple'  
  7. );  
  8.   
  9. // convert to a string  
  10. $string = json_encode($myvar);  
  11.   
  12. echo $string;  
  13. /* prints 
  14. ["hello",42,[1,"two"],"apple"] 
  15. */  
  16.   
  17. // you can reproduce the original variable  
  18. $newvar = json_decode($string);  
  19.   
  20. print_r($newvar);  
  21. /* prints 
  22. Array 
  23. ( 
  24.     [0] => hello 
  25.     [1] => 42 
  26.     [2] => Array 
  27.         ( 
  28.             [0] => 1 
  29.             [1] => two 
  30.         ) 
  31.  
  32.     [3] => apple 
  33. ) 
  34. */  
It is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost.

8. Compressing Strings

When talking about compression, we usually think about files, such as ZIP archives. It is possible to compress long strings in PHP, without involving any archive files.
In the following example we are going to utilize the gzcompress() and gzuncompress() functions:
  1. $string =  
  2. "Lorem ipsum dolor sit amet, consectetur 
  3. adipiscing elit. Nunc ut elit id mi ultricies 
  4. adipiscing. Nulla facilisi. Praesent pulvinar, 
  5. sapien vel feugiat vestibulum, nulla dui pretium orci, 
  6. non ultricies elit lacus quis ante. Lorem ipsum dolor 
  7. sit amet, consectetur adipiscing elit. Aliquam 
  8. pretium ullamcorper urna quis iaculis. Etiam ac massa 
  9. sed turpis tempor luctus. Curabitur sed nibh eu elit 
  10. mollis congue. Praesent ipsum diam, consectetur vitae 
  11. ornare a, aliquam a nunc. In id magna pellentesque 
  12. tellus posuere adipiscing. Sed non mi metus, at lacinia 
  13. augue. Sed magna nisi, ornare in mollis in, mollis 
  14. sed nunc. Etiam at justo in leo congue mollis. 
  15. Nullam in neque eget metus hendrerit scelerisque 
  16. eu non enim. Ut malesuada lacus eu nulla bibendum 
  17. id euismod urna sodales. ";  
  18.   
  19. $compressed = gzcompress($string);  
  20.   
  21. echo "Original size: "strlen($string)."\n";  
  22. /* prints 
  23. Original size: 800 
  24. */  
  25. echo "Compressed size: "strlen($compressed)."\n";  
  26. /* prints 
  27. Compressed size: 418 
  28. */  
  29.   
  30. // getting it back  
  31. $original = gzuncompress($compressed);  
We were able to achive almost 50% size reduction. Also the functions gzencode() and gzdecode() achive similar results, by using a different compression algorithm.

9. Register Shutdown Function

There is a function called register_shutdown_function(), which will let you execute some code right before the script finishes running.
Imagine that you want to capture some benchmark statistics at the end of your script execution, such as how long it took to run:
  1. // capture the start time  
  2. $start_time = microtime(true);  
  3.   
  4. // do some stuff  
  5. // ...  
  6.   
  7. // display how long the script took  
  8. echo "execution took: ".  
  9.         (microtime(true) - $start_time).  
  10.         " seconds.";  
At first this may seem trivial. You just add the code to the very bottom of the script and it runs before it finishes. However, if you ever call the exit() function, that code will never run. Also, if there is a fatal error, or if the script is terminated by the user (by pressing the Stop button in the browser), again it may not run.
When you use register_shutdown_function(), your code will execute no matter why the script has stopped running:
  1. $start_time = microtime(true);  
  2.   
  3. register_shutdown_function('my_shutdown');  
  4.   
  5. // do some stuff  
  6. // ...  
  7. function my_shutdown() {  
  8.     global $start_time;  
  9.   
  10.     echo "execution took: ".  
  11.             (microtime(true) - $start_time).  
  12.             " seconds.";  
  13. }  

Conclusion

Are you aware of any other PHP features that are not widely known but can be quite useful? Please share with us in the comments. And thank you for reading!

20 Handy PHP String Functions

PHP is the widely used open source language especially for developing web applications. Strings in PHP play very important role. In this tutorial, You will find about 20 handy and most used PHP functions.

1. addcslashes()

This string function returns a string also with backslashes before characters and characters are listed as parameter.
Syntax:
1
<?php addcslashes($str, characters); ?>
Example:
1
2
3
4
<?php
$mystr = "How are you.";
echo addcslashes($mystr, 'r');
?>
Output:
1
How a\re you.

2. convert_uudecode()

This string function decodes a string that is uuencoded (in simple words it decodes a string which is encrypted by some security methods).
Syntax:
1
2
3
<?php
convert_uudecode($encrypted_string);
?>
Example:
1
2
3
4
5
<?php
$encrypted_string = "+2&]W($%R92!9;W4` `";

echo convert_uudecode($encrypted_string);
?>
Output:
1
How Are You

3. convert_uuencode()

This string function encodes a string.
Syntax:
1
2
3
<?php
convert_uuencode($encrypted_string);
?>
Example:
1
2
3
4
5
<?php
$encrypted_string = "How Are You";

echo convert_uuencode($encrypted_string);
?>
Output:
1
+2&]W($%R92!9;W4` `

4. count_chars()

This string function returns how many times a character (ASCII) appears in a string depending on the modes we specified.
By default, mode is 0 that returns an array with Key (ASCII Value) and Value (Number of Occurrences.
Mode 1 returns an array with same functionality as Mode 2, but it only lists appearance of characters which are greater than zero.
Mode 2 returns occurrence which are equal to zero.
Mode 3 returns string with difference characters used.
Mode 4 generates string of all unused characters.
Syntax:
1
count_chars($str, mode);
Example:
1
2
3
4
5
6
7
8
9
10
11
<?php
$mystr = "Hello Dear, How are you";

print_r(count_chars($mystr, 0));
print_r(count_chars($mystr, 1));
print_r(count_chars($mystr, 2));

echo count_chars($mystr, 3);
echo count_chars($mystr, 4);

?>

5. echo()

This function helps to output more than one strings. Parameters in this function are optional.
Syntax:
1
echo(string)

6. explode()

explode() explodes or break a string into an array. We can easily understand the functionality of this function by the name “explode”. explode() has three parameters, first 2 are required and third is optional.
Syntax:
1
explode(string_separator, $str, limit);
Example:
1
2
3
4
5
6
7
<?php

$mystr = "Hello Dear, How are you";

print_r(explode(" ", $mystr));

?>
Output:
1
Array ( [0] => Hello [1] => Dear, [2] => How [3] => are [4] => you )

7. implode()

implode() is a reverse of explode(), means it joins an array into a sring. It has two parameters, first one is optional and second one is required.
Syntax:
1
imlode(string_separator, array);
Example:
1
2
3
4
5
6
7
<?php

$arr = array("Hello", "Dear", "How", "Are", "You");

echo implode(" ", $arr);

?>
Output:
1
Hello Dear How Are You

8. md5()

md5() function calculates Message-Digest Algorithm (md5) hash of a string. It has two parameters, first one is required and second one is optional which was included in PHP 5.0.
Syntax:
1
md5($str, raw);
Example:
1
2
3
4
5
6
7
<?php

$mystr = "How Are You";

echo md5($mystr);

?>
Output:
1
9e227bb366c119c7f27a7115f0136f42

9. str_replace()

If you want to replace some specified characters with other characters in PHP, str_replace() is the best choice. It has many rules like:
  1. If we want to search a string in an array, it returns as an array.
  2. Find and Replace is performed with each array element as we want to search a string in an array.
  3. If we are finding an array and also replacing with it with an array, an empty string will be used as replace.
  4. In case, replace is a string and find is an array, then it uses replace sting as find value.
Syntax:
1
str_replace(find, replace, string, count);
Example:
1
2
3
<?php
echo str_replace("How", "Dear", "How Di");
?>
Output:
1
How Dear

10. str_split()

str_split() works like explode() in some manner, it is used for splitting a string into an array.
Syntax:
1
str_split($mystring, length);
Example:
1
2
3
<?php
print_r(str_split("What"));
?>
Output:
1
2
3
4
5
6
7
Array
(
[0] => W
[1] => h
[2] => a
[3] => T
)

11. str_word_count()

This function is used for counting the words in a string.
Syntax:
1
str_word_count(string, return, char);
Example:
1
2
3
<?php
echo str_word_count("What are you doing");
?>
Output:
1
4

12. strcmp()

This case-sensitive string function is used for comparing two strings. It returns “0″ if both strings are equal, “<0″ if first string is less than second string and “>0″ if first string is greater than second string.
Syntax:
1
strcmp(first string, second string);
Example:
1
2
3
<?php
echo strcmp("What Are You Doing", "What I Should Do");
?>
Output:
1
-1

13. strlen()

strlen() calculates the length of string based on extra spaces and characters used in a string.
Syntax:
1
strlen($str);
Example:
1
2
3
<?php
echo strlen("Oh, No!");
?>
Output:
1
7

14. strrpos()

strrpos() is used to find the position of the last occurrence string inside another string.
Syntax:
1
strrpos(strong, find, start)
Example:
1
2
3
4
5
6
7
8
<?php
echo strrpos("Where are you going?", "go");
?>
[code]

<strong>Output:</strong>

[code type="php"]14

15. strstr()

strstr() finds the first occurrence of a string in a string, if found it returns at the matching point else it returns 0.
Syntax:
1
strstr();
Example:
1
2
3
<?php
echo strstr('Hi What', 'Hi');
?>
Output:
1
Hi What

16. strtolower()

This function converts a string to lowercase (It converts only letters from A-Z or a-z).
Syntax:
1
strtolower($str);
Example:
1
2
3
<?php
echo strtolower("Now WhaT are");
?>
Output:
1
now what are

17. strtoupper()

This function converts a string to uppercase letters.
Syntax:
1
strtoupper($str)
Example:
1
2
3
<?php
echo strtoupper("Yes");
?>
Output:
1
YES

18. substr()

This function split up a part from a string according to given criteria specified in the parameters.
Syntax:
1
substr($str, start, length)
Example:
1
2
3
<?php
echo substr("Where I Can Find You", 7);
?>
Output:
1
Can Find You

19. trim()

This function erases predefined characters and whitespaces from every side of a string. Predefined characters are like: \0, \t, \n, \xob, \r etc.
Syntax:
1
trim($str, chars)
Example:
1
2
3
4
<?php
$mystr = "Hey dude, I'm going with you";
echo trim($mystr);
?>

20. wordwrap()

If you want to cut a string after it reaches to a specific length, wordwrap() is the best choice for achieving this.
Syntax:
1
wordwrap($str, width, break, cut)
Example:
1
2
3
4
5
6
<?php

$str = "Check the example: Supercalifragulistic";

echo wordwrap($str,9);
?>
Output:
Browser will display out like this
1
Check the example: Supercalifragulistic
But after checking the page source, output will be something like below:
1
2
3
Check the
example:
Supercalifragulistic

Tuesday, 6 August 2013

most important php function

<?php
Top Most important Php 
function 

1.  empty(); // return true false 
$p='val';

if(!empty(
$p)){ // if $p is not empty 
echo 'variable is not empty ';
} else {
 echo 
'value is null';
}


2. unset();

use for 
unse session or variable values 
unset($a);

3. isset();

if(isset(
$a)){

echo 
'value is set ';
} else {  
echo 
'value is not set ';
}

4. trim()

use for 
removes the whitespaces from the left part of the string.
trim($a);

5. explode () ;

convert strin to array 
$str "Rajeev Dhar dwivedi"; $array explode(" ",$str); print_r($array);
outPut :

Array ( [
0] => Rajeev [1] => Dhar [2] => dwivedi )


6. implode(); convert array to string 

$array 
= array( 'Rajeev' ,'Dhar','Dwived') ;

echo 
implode(" ",$array);
Output Rajeev Dhar Dwived


7. date
() function 
this function use fot get date from system
echo date('Y-M-d');


8. time() 

this function use for get time from system in mili second 
echo time(); 

9. strip_tags();



use for remove html tags 


example :
$tag="<b><p>rajeev</p></b>";


  echo strip_tags($tag);  // output : rajeev

Monday, 5 August 2013

PHP htmlentities Function

Whenever you allow your users to submit text to your website, you need to be careful that you don't leave any security holes open for malicious users to exploit. If you are ever going to allow user submitted text to be visible by the public you should consider using the htmlentities function to prevent them from running html code and scripts that may be harmful to your visitors.

PHP - Converting HTML into Entities

The htmlentities function takes a string and returns the same string with HTML converted into HTML entities. For example, the string "<script>" would be converted to "&lt;script&gt;".
By converting the < and > into entities, it prevents the browser from using it as an HTML element and it prevents the code from running if you were to display some user's input on your website.
This may seem a little complicated, but if you think of the way a browser works, in separate stages, it becomes a little easier. Let's look at the way the function htmlentities changes the data at three different levels: in PHP, in raw HTML and in the web browser. The sample string is a bad script that will redirect visitors to the malicious user's own website.

PHP Code:

// An imaginary article submission from a bad user
//  it will redirect anyone to example.com if the code is run in a browser
$userInput = "I am going to hax0r your site, hahaha!
 <script type='text/javascript'>
 window.location = 'http://www.example.com/'
 </script>'";
 
//Lets make it safer before we use it
$userInputEntities = htmlentities($userInput);

//Now we can display it
echo $userInputEntities;
The HTML output of the above script would be as follows:

Safe Raw HTML Code:

I am going to hax0r your site, hahaha!
 &lt;script type='text/javascript'&gt;
 window.location = 'http://www.example.com/'
 &lt;/script&gt;'
If we had not used htmlentities to convert any HTML code into safe entities, this is what the raw HTML code would be and it would have redirect a visitor to example.com.

Dangerous Raw HTML Code:

I am going to hax0r your site, hahaha!
 <script type='text/javascript'>
 window.location = 'http://www.example.com/'
 </script>'
Those two HTML code examples are what you would see if you were to view source on the web page. However, if you were just viewing the output normally in your browser you would see the following.

Safe Display:

I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.example.com/' </script>'

Dangerous Display:

You'd see whatever spammer site that the malicious user had sent you to. Probably some herbal supplement site or weight loss pills would be displayed.

When Would You Use htmlentities?

Anytime you allow users to submit content to your website, that other visitors can see, you should consider removing the ability to let them use HTML. Although this will remove a lot of cool things that your users can do, like making heavily customized content, it will prevent your site from a lot of common attacks. With some custom coding you can just remove specific tags from running, but that is beyond the scope of this lesson.
Just remember, that when allowing users to submit content to your site you are also giving them access to your website. Be sure you take the proper precautions.

Object Oriented Programming in PHP

Object oriented programming (OOP) was first introduced in php4. Area for oop in php version 4 was not very vast. There were only few features  available in php4. Major concept of the object oriented programming in PHP is introduced from version 5(we commonly known as php5). Also php community has plan to modify its object model structure in more better manner in php6(not released yet). But still in php5 object model is designed nicely. If you have good understanding of OOP then you can create very good architecture of your php application.  You only need to know some of the basic principles of object oriented programming and how to implement that concept of oop in php. In whole series I will use abbreviation OOP for Object Oriented Programming.
This tutorial series is for both beginners and middle level programmer who want to learn advance concept of oop in php from basic . In this series we will explore all aspect of OOP in PHP from beginning. In every chapter we will covers some best practices. If you are completely beginner for oop please go through every topic of this tutorial series very carefully. If you have some knowledge about the concept of object oriented programming then you can directly go to section of your choice. In every section of tutorial you can download code used in example.

List of Topic/Chapter For OOP In PHP

TopicsDescription
Basics of OOP in PHPIn this part of tutorial you will learn about the very basic concept of OOP in php. This part will cover topic like what is object and class. How to implement class and object in php. Also here we will show you the very basic example for class. If you are beginner for OOP in PHP please you may enjoy this part. This is essential for the beginner for OOP.
Class and Object in OOPIn this part of tutorial you will lean about the basic and advance concept of class and object. It will cover topic like what is class, what is object, how to use implement class and object. This chapter will be started from very basic concept of class and object and will describe upto depth level. This part will cover the best practice of class and object implementation.
Magic Function in PHP  OOPAlthough this is slightly different topic of tutorial but it is included here because some of the magic method is used in object oriented programming. This chapter will cover basic magic methods/function of php which is used in OOP.
Visibility In PHP(Public,  Private and Protected)In this part of tutorial you can learn about the access modifier of OOP in PHP. This part will have complete coverage of what is public, private and protected. Also this will describe how to use these access modifier and best practices.
Static Method and Property in OOPIn this part you will learn about static method and property of the class. In this section you will learn what are the static method and properties, how to use them.
Inheritance in PHPIn this part of tutorial, you will learn basics of inharitance in oop.
Abstract class and Interface PHPIn this part you will learn about interface and class class in php. Here you will learn about what is abstract classes and how and when you should use abstract class and basic concept of interface, How behavior of one class passes to another class
Overloading and OverridingThis part will cover the implementation of overloading and overriding of methods in php. Here you will learn about how to overload method of class and how to override method of class.
Object Cloning PHPThis part will cover how to clone object of your class. In this chapter you will learn about the implementation of object cloning in PHP.
Method Chaining PHPIn this part of tutorial we will explore about method chaining feature of object.

Basics of OOP in PHP

Object oriented programming is nothing but a technique to design your application. Application could be any type like it could be web based application, windows based application. OOP is a design concept. In object oriented programming, everything will be around the objects and class. By using OOP in php you can create modular web application. By using OOP in php we can perform any activity in the object model structure. There are many benefit of using oop over the parallel or procedural programming. Further in this part we will cover some basic of object and class and its implementation in php.

What is Object?

If you want to see theoretical definition of object described  in the typical book of oop then following is the best definition of object is:
Any thing is the world is an object. Look around and you can find lots of object. Your laptop, pc, car every thing is an object. In this world every object has two thing properties and behaviors. Your car has property (color, brand name) and behavior(it can go forward and backward). If you are able to find properties and behaviors of real object. Then it will be very easy for you to work with Object Oriented Programming.
In real world different objects has different properties and behaviors. For example your television has property size, color, and has behavior turn on, turn off. If you observe carefully then you can find that every object has some property and behavior from other object. This phenomena is called inheritance. For example car object has property and behavior from engine object.
If you are able to understand what is object then good to go ahead. If not then please start visualizing properties and behavior of object around you. You will defiantly understand.
Object in programming is similar to real word object. Every programming object has some properties and behaviors. For example if you have object for interest calculator then it has property interest rate and capital and behavior simple interest calculation and compound interest calculation. Interest calculator has some property and method from calculator object like addition, multiplication etc.

What is Class ?

Class is something which defines your object. For example your class is Car. And your Honda car is object of car class. Like object explanation, here we will take an example of the real word and then we will move further in programming definition.
Blueprint of the object is class. Class represents all properties and behaviors of object. For example your car class will define that car should have color, number of door and your car which is an object will have color green and 2 doors. Your car is object of class car. Or in terms of programming we can say your car object is an instance of the car class. So structural representation (blueprint) of your object is class.
Now let us take an example of the programming. Your interest calculator object is instance of class interest calculator. Interest calculator class defines properties like capital rate, and behavior like simple interest calculation and compound interest calculation. Your interest calculator object has property rate as 3% and capital 300 USD. So you are describing your class definition of rate by giving rate value equals to 3% and capital 300USD in your interest calculator object. Now in your object when interest calculation behavior will be applied it will take your rate of interest and capital and provide you the result. Again your interest calculator class will inherit the definition of its property and behavior from calculator class.

Advantage of Object Oriented Programming

There are various advantage of using OOP over the procedural or parallel programming. Following are some of the basic advantages of using oop techniques.
  1. Re-Usability of your code: If you will use OOP technique for creating your application then it will gives you a greater re-usability. For example, if you have created calculator class at one place then you can use the same calculator class in your application.
  2. Easy to Maintain : Application develop using oop technique are easier to maintain than normal programming. Again let us take an example of your interest calculator class. Suppose your business need to change the calculation logic. They want to add some charges if your capital is less than 200 USD. Just think about your application is big and developed using normal programming techniques. So first you have to analyse that at how many places we have calculated interest, and then you will change. But just think of oop technique. You just need to change in your method of interest calculation at one place.
  3. Good Level of Abstraction: Abstraction means making something hidden. By using oop technique you are abstracting your business logic from implementation. It will provide you greater ease. Again let us take and example of interest calculator. If you have created class for interest calculation and your team is going to use that class. Now you are only concern about how interest calculation will be performed, because you have created that. Your team member is always have understanding that if they will set rate and capital property and apply interest calculation method then it will return interest.
  4. Molecularity: If are are creating separate class for your every problem then you are making it modular.So if someone need to change in the business logic part then he will always go to your business logic code part.
Now if you are clear with concept of class, object in oop and its advantages. Great!!!  Its time to move over the implementation of oop in php.

Implementation of OOP in PHP

In this section we will discuss about some basic aspect of oop in php. For every basic aspect we have separate chapter in this tutorial. If you will say basic aspect of oop in php then it is all about classes, objects. For the further detail of oop topic like interface, object cloning etc then you can go to specific chapter of this tutorial. Refer table of contents for the complete list of chapter and its navigation. So let us discuss about basic concept of class, object inheritance here.
Class in PHP:
Class is a blueprint of any object in oop. So class is the first alphabet of oop. In php you can creation of class is very simple. You can create class using tag class. In class block you can define your properties as class variable and function as class behavior. So let us create a class for interest calculator and define its properties like rate, capital, duration and behavior like calculate interest.

class interestCalculator
{
var $rate;
var $duration;
var $capital;
function calculateInterest()
{
return ($this->rate*$this->duration*$->capital)/100;
}
}


Above is a very simple and basic class to calculate interest. Let us explore all basic aspect of this class.
You can create class in php by using class keyword. here class interestCalculator{ } is class block. You can define all of your properties and methods(behavior of class, we will use method or function instead of behavior) of your class inside of your class block. All variable started with var keyword is property of your class. Commonalty we can say these are variable of class also. And the function are methods of this class. You can design your own class with your won variable and function.
Object in PHP:
As we have already discussed that object is an instance of any class. So we will take our interestCalculator class as an example. Creating object of the class is very easy in php. You can create object of class with the help of new keyword. Following is very basic example of creation of object of your class interest calculator:
$calculator = new interestCalculator()
In above declaration you are creating object of your class interestCalculator in variable $calculator. Now your variable $calculator is an object of class interestCalculator. Next step is to set property or variable of object calculator and perform calculation of interest.

$calculator = new InterestCalculator()
$calculator->rate = 3;
$calculator->duration =2;
$calculator->capital = 300;
echo $calculator->calculateInterest();


Here object of your class interestCalculator is your php variable $calculator. In next 3 lines of above code you are setting properties of class. You can access property of class with ->. So in above code rate property is set using $calculator->rate = 3;. Finally after setting all reaqired properties you have called method calculateInterest.
Hope you have clear understanding of oop in php. Download the basic code and run at your machine.
For Indepth Coverage on OOP theory your can further read on wikipedia:
http://en.wikipedia.org/wiki/Object-oriented_programming
original link :- http://www.techflirt.com/tutorials/oop-in-php/index.html#comments