Monday 2 March 2015

Some Advanced Php Programming Tips - Part I

Some Advanced Php Programming
  Tips - Part I

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. Now a day, we use PHP as part of our daily coding ritual. We all love to use many of the open source frameworks and code snippets to make our lives easier. However, we also feel it’s important that every developer has a full understanding of the core base PHP functions, classes and methods. Without knowledge of these, how can you begin to understand how all the frameworks out there operate?

We have compiled a selection of our top native functions, classes and features that we use on a daily basis. We know first-hand how invaluable these features are, so we hope you find them to be useful too.
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:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
// function with 2 optional arguments
function foo($arg1 = '', $arg2 = '') {

    echo "arg1: $arg1\n";
    echo "arg2: $arg2\n";

}


foo('hello','world');
/* prints:
arg1: hello
arg2: world
*/

foo();
/* prints:
arg1:
arg2:
*/

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():
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// yes, the argument list can be empty
function foo() {

    // returns an array of all passed arguments
    $args = func_get_args();

    foreach ($args as $k => $v) {
        echo "arg".($k+1).": $v\n";
    }

}

foo();
/* prints nothing */

foo('hello');
/* prints
arg1: hello
*/

foo('hello', 'world', 'again');
/* prints
arg1: hello
arg2: world
arg3: again
*/
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.
01
02
03
04
05
06
07
08
09
10
11
12
13
// get all php files
$files = glob('*.php');

print_r($files);
/* output looks like:
Array
(
    [0] => phptest.php
    [1] => pi.php
    [2] => post_output.php
    [3] => test.php
)
*/

You can fetch multiple file types like this:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// get all php files AND txt files
$files = glob('*.{php,txt}', GLOB_BRACE);

print_r($files);
/* output looks like:
Array
(
    [0] => phptest.php
    [1] => pi.php
    [2] => post_output.php
    [3] => test.php
    [4] => log.txt
    [5] => test.txt
)
*/
Note that the files can actually be returned with a path, depending on your query:
01
02
03
04
05
06
07
08
09
10

If you want to get the full path to each file, you can just call the real path()_function on the returned values:
01
02
03
04
05
06
07
08
09
10
11
12
   13
$files = glob('../images/a*.jpg');

// applies the function to each array element
$files = array_map('realpath',$files);

print_r($files);
/* output looks like:
Array
(
    [0] => C:\wamp\www\images\apple.jpg
    [1] => C:\wamp\www\images\art.jpg
)
*/

 

DataBase Connectivity using Php (there are three functions to connect php with database)

1.    mysql_connect, it is the oldest one but deprecated.

Syntax: mysql_connect (host, user, password)
2.    mysqli_connect, it is the improved version of database connectivity.
Syntax: mysqli_connect (host, user, password, database)

This function is widely being used in top Php frameworks. But last, not least this also has possibility to become deprecated in near future, so we have another solution which will last long. It is mentioned below, these are PDO (PHP DATA OBJECT) Classes.





1.        PDO Class  

We use the PDO (PHP Data Object) exclusively for connecting to our MySQL databases. PDO provides a nice abstraction layer around a set of database drivers such as MySQL, PostgreSQL and MS SQL. This means that whichever database you are using, as long as PDO supports it, you can use the same functions to perform the same actions on the database. This makes your code more portable for your web application to be used on a whole range of databases with no extra development time.
The PDO Class provides many standardised functions such as creating transactions, creating prepared statements and allowing you to escape your variables if you need to. Used in the correct way, PDO can help protect your web application from SQL injection attacks.
The PDO class can be used directly, but we like to use our own layer over the top to give us more control over things like data entry formatting and validation, which the PDO class does not provide. RedBeanPHP ORM is a good open source solution that provides some nice functionality that's built on top of PDO.
The example below shows a connection to a MySQL database that selects the name, colour and calories from each row in fruit table. By using a prepared statement, PDO converts the placeholders to match the array that is parsed in the execute function. By using the prepared statement, all the values are escaped to protect from SQL injection. The whole piece of code has been added to a try block, which can be used to catch any exceptions.
<?phptry{    /* Connect to Database */    
$dsn = 'mysql:dbname=test;host=localhost';    
$dbh = new PDO(dsn,'username','password');    
/* Create SQL String with parameters */    
$sql = 'SELECT name, colour, calories    FROM fruit    WHERE calories < :calories AND colour = :colour';    $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));  

 /* add values and execute request on database */  
 $sth->execute(array(':calories' => 150, ':colour' => 'red'));    
/* Get the returned Data */    
$dataSet = $sth->fetchAll();  
 /* Print Results */    
print_r($dataSet);}
catch (PDOException $e){    echo 'PDO Error: '.$e->getMessage();}catch(Exception $e){    echo 'A Unknown Error Occurred: '.$e->getMessage();}


How to deal with JSON Data


1.        json_encode & json_decode


With the rollout of PHP5.2 came two very useful functions that allow you to parse JSON (JavaScript Object Notation) strings. JSON is a text-based standard that is generally used to send and receive data with a simple structure that was designed to be easily read, both by a computer and by a human.
PHP provides two functions that allow you to manipulate your data both to and from JSON. json_encode is utilised by setting the first argument as your data. Be that a simple string or a multi dimensional array, PHP will try to return a string of your data that has been converted to a JSON formatted string. This string can then be used to output on an API or included in your HTML template to be read by your JavaScript code on the front end.
There are some caveats to using json_encode. For example, only basic data types can be used. Strings, numbers and Booleans are the main types along with associative and non-associative arrays. PHP will also try to convert class objects but will only encode public properties. UTF8 is also used to encode the resulting string of JSON.
The example below shows an array of animals that is converted to a JSON string then sent to the user. You could call this script from an Ajax request via a JavaScript framework which will then return a JavaScript object ready for you to iterate over.
<?php/* Set Content Encoding Header */header('Content-type: application/json; charset=utf-8');/* Array of animals*/&#36;myArray = array(    array('type'=>'cat','name'=>'Alfie','age'=>2),    array('type'=>'dog','name'=>'Bella','age'=>6));/* Encode to JSON */&#36;jsonString = json_encode(&#36;myArray);echo &#36;jsonString;
json_decode is the opposite of json_encode. The function takes the JSON string as the first argument and tries to parse the string into a PHP variable. There is an optional second argument to convert the string to an object or an associative array. By parsing ‘true’ as the second argument (as shown below) you can return an array.
<?php/* Set Content Encoding Header */&#36;json = '[{"type":"cat","name":"Alfie","age":2},{"type":"dog","name":"Bella","age":6}]';/* Parse JSON to Object */&#36;object = json_decode(&#36;json);/* Parse JSON to Array */&#36;array = json_decode(&#36;json,true);/* Print Object */var_dump(&#36;object);/* Print Array */var_dump(&#36;array);
The advantage of using JSON over XML is its simplicity; with only a few data types PHP makes it very easy to parse simple data. JSON may not be as fast as the XML parsing in the majority of cases, but json_decode provides you with direct access to your data in an array or object format. This is unlike simpleXML, which returns a simpleXML object which you then have to process further to gain access to your data. Consequently, json_decode can be considered to be just as fast.


No comments:

Post a Comment