Session in php

Tags

, ,

To get Books of Sanjib Sinha…

About the Author….

Web pages hold temporary data. To make it dynamic, we can store
our data on the server. We can use session to achieve this special
feat.
To work with session, we can store and retrieve data by its
name.
We start with a simple session_start() function.

Consider someone has logged in by filling out a form. We can
keep or store that name just by starting session. It is something like
– you have issued a ticket to someone who can now enter your
application and stay there for some time. When his or her session
ends, the user has to leave.
Continue reading

Advertisements

vmware mouse click not working

Tags

, , , , ,

Sometimes you try to run metasploitable in your Virtual Machine or vmware, and you find that your mouse click is not working any more.
What can you do?

vmware-mouse-click-not-working

vmware-mouse-click-not-working


In the above image similar things are seen.
Once you click your mouse on the metasploitable terminal to type username and password, your mouse click just vanishes into blue!
There are several solutions described on the Internet, including uninstalling software like audio driver etc.
You don’t have to uninstall anything from your host machine.
Just press “Ctrl+Alt+Esc” and your mouse click will start acting again.

How to use metasploitable linux

Tags

, , , , , ,

To get Books of Sanjib Sinha…

To know more about Author….

metasploitable-installed

metasploitable-installed

Metaspoiltable is an intentionally vulnerable Linux machine. It can be downloaded from “SOURCEFORGE”. Search on the Internet and you’ll get the required link.
Now Metaspoiltable has been downloaded to your host machine. When you’ll unzip the folder, it may take some time. It will be going to have few files. Among those files, we need one file, in particular, to install Metaspoiltable in your VirtualBox.
Continue reading

Dynamic website templates in php

Tags

, , , , ,

To get Books of Sanjib Sinha…

To know more about the Author….

The concept of this dynamic website is not very critical. Usually when we type any URL like http://sanjibsinha.com/about.php, we get a response. The ‘about.php’ page opens up. We could send some data dynamically to that page whatsoever. However, this URL is not considered to be search engine friendly. It would be definitely good if the URL was something like this: http://sanjibsinha.com/about.php?query=about-sanjib-sinha. It has more clarity and the search bots will find it friendly to index.

OOP-PHP

Our challenge is, can we make something like this?
If someone types or click a link such as shown above, the ‘about.php’ page will automatically open up in the background.
You can always do it procedurally, but our challenge is different. We want to make it in Object Oriented Way.

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.

Let us think about a ‘page’ object that will redirect us to a new URL from the entry point. The ‘index.php’ page of the application could be a good candidate for being the entry point. So, we will write this code on the top of the ‘index.php’ page.

require 'vendor/autoload.php';

$page = new Sanjib\PageRequest();
$page->redirect();
/*
* This is our entry point
*/

After that, we need some links from this page so that our ‘page’ object should redirect us to the desired URL. Here is the code so that we could go to ‘about.inc.php’ and ‘contact.inc.php’.

  • About
  • Contact

  • We have created a directory called ‘Google’. We have created a directory called ‘lib’. In our ‘composer.json’ file we have written this code so that any file saved in the ‘lib’ folder can be accessed through the namespace ‘Sanjib’.
    {
    "autoload": {
    "psr-4": {
    "Acme\\": "library/",
    "Sanjib\\": "lib/",
    "Myapp\\": "mylib/"
    }
    }
    }

    After setting our composer file, we run the necessary commands in our respective terminals. Whether you are using Windows, Linux or MAC, go to the application folder, and type – ‘composer dump-autoload’. This will set your namespace.
    In the ‘lib’ folder, we have kept our ‘page’ object class – ‘PageRequest.php’.
    Here is the code.

    namespace Sanjib;

    class PageRequest {

    protected $pageDirectory = "Google";
    protected $pageFolder = [];
    protected $SanjibSinha;

    function __construct() {

    }

    function redirect() {

    if(!empty($_REQUEST['Google'])){

    $$this->SanjibSinha = $_REQUEST['Google'];

    $$this->pageFolder = scandir($$this->pageDirectory, 0);
    unset($$this->pageFolder[0], $$this->pageFolder[1]);

    if(in_array($$this->SanjibSinha . ".inc.php", $$this->pageFolder)){

    require $$this->pageDirectory . "/" . $$this->SanjibSinha . ".inc.php";

    } else {

    echo 'Page not found.';

    }
    } else {
    return FALSE;
    }

    }

    }

    The logic is simple. If the page request is not empty, then the ‘request’ property will be pointed to the directory we mentioned earlier. Here it is ‘Google’. You can name your directory. It’s your choice.
    Open your ‘about.inc.php’ page and write this code:


    if ($_REQUEST['Google'] != "author-technologist-sanjib-sinha"){
    header("Location: http://localhost/dashboard/test/Google/bad.inc.php");
    }

    It assures that if someone wants to type something else it’ll automatically redirect it to a ‘Bad Request’ page. The ‘contact.inc.php’ page code will be similar.

    if ($_REQUEST['Google'] != "contact-sanjib-sinha"){
    header("Location: http://localhost/dashboard/test/Google/bad.inc.php");
    }


    Now you can create as many pages as you wish and you can set the URL dynamically. Your ‘page’ object will handle the whole request cycle now.

    MySQL or NoSQL

    Tags

    , , ,

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

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

    Edgar F Codd had invented it. Later it became exceptionally popular. The relational database management system (RDBMS) is a database management system based on the relational model. Today most databases use it.
    MySQL is one of them. Along with PHP, we need to know about MySQL for one reason. MySQL is a central component of the LAMP open-source web application software stack. The LAMP is an acronym for “Linux, Apache, MySQL and Perl/PHP/Python”.

    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.

    How important MySQL is? Well, it really needs no introduction. Many popular applications, such as WordPress, Drupal or Joomla use it. Many high scale websites including Google, Facebook, Twitter, Flickr and YouTube draw on it.
    Since the 1980s it has been a common practice for storage of information in databases used for different types of applications. From financial records to personal data – it’s much easier to implement and administer. RDBMS like MySQL maintain a clearer division between the database model and the application. RDBMS as MySQL received challenges, mainly, from two sectors – one is Object Database Management Systems ODBMS or OODBMS and the second one is XML database management system. However, they were unsuccessful.
    As time passes by and the horizontal scaling of the computer clusters become popular, NoSQL is one of the most serious challenges RDBMS faces now.
    Relational databases use tabular relations. The NoSQL databases use a data structure that consists of key-value, wide column graph or document. It is not only different from RDMS, but sometimes it is also faster. Sometimes people view it as more flexible.

    File in PHP Example

    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 

    Classes in php

    Tags

    , , ,

     

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

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

    PHP 7 has a full object model and now we consider it as fully object oriented programming (OOP) language.
    For a small website, where four, five pages represent a simple profile, you don’t need OOP. Object Oriented Programming is targeted at larger applications. In addition, I hope, one day, you’ll definitely build a large web application with other team members. For that purpose and to master PHP, you need to learn and adapt to OOP style.
    For that reason, OOP was created – to break up large applications when long function did not work.
    In the beginning, programming started in a linear fashion. Programmers wrote code, line after line. It took time to debug. Then came the concept of functions. We started encapsulating our data into a function.

    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.

    However, it had limitations. It broke up the code but the code would not run until called.
    As time passed by, we had badly needed a change. Web applications started becoming larger in volume. The solution was to use objects. To start a car you need to start the engine, accelerate, use break and steering, and switch on AC, and so on. Lot of functions to be written. Lot of variables to be declared and assigned. How about wrap them all into a single conceptualized object – a car.
    Now all the internal workings are hidden and as a car owner or a driver, you do not want to know how the internal workings play their roles. You know your car moves. It stops. It honks. You are happy.
    4.1.1 Classes
    When we describe someone as good, we actually refer to a “type”.
    Classes are the type of objects. Like integer is a type of a variable. This conception is particularly important. A class is a type of an object and many things depend on that. The main purpose of object is to create a class first. Without a car class, you cannot create a car object.
    If class is the type of an object, then the object is the instance of a class.
    Let’s see an example first.

    
                    
                    // let us create a house building App
                    // we need to create a type 
                    // and we want to create different types of house objects
                    
                    class House {
                        
                        // each house has doors
                        // they could have different colors
    
                        public $door;
    
                        function __construct($door) {
                            
                            $this->door = $door;
                        }
    
                    }
                    
                    $house1 = new House("Red");
                    
                    echo "We have just created a house with " . $house1->door . " door.";
                    
                    $house2 = new House("Blue");
                    
                    echo "We have just created a house with " . $house2->door . " door.";
    
    

    Now we would like to see the similar output in the old procedural style. Consider this code:

    
                    
                    // let us assume we want to create the same functionality 
                    // procedurally
                    //$door = "RED";
                    
                    function House1($door) {
                        
                        //global $door;
                        $door = "Red";
                         echo "We have just created a house with " . $door . " door.";
                         
                    }
                    function House2($door) {
                        
                        //global $door;
                        $door = "Blue";
                         echo "We have just created a house with " . $door . " door.";
                         
                    }
                    
                    House1("Red");
                    House2("Blue");
                    
                    // for different houses we need to create different functions
                    // no reusability
                    // no separation of codes
    

    The main problem is – for different houses, you need to create different functions. The whole process becomes cumbersome.
    In the first scenario, we created one type of the house object. It was “class House”. In that type, we mentioned the “door” property so that each new house might have different colors. We did not have to write separate functions for each house. One class. One type. In addition, that was enough to create many houses.
    Consider another example where in a “buying app” we set a minimum price. No one can buy a product paying less than 2 dollar.

    
    
                    
                    // imagine a buying app
                   // where we set a price ranging between two values
                    // 2 to 10 dollars
                    
                    class BuyMe {
                        
                        public $product;
                        
                        public $price;
    
                        function __construct($product) {
                            
                            $this->product = $product;
                        }
                        
                        public function setPrice($price) {
                            
                                $this->price = $price;
                                $minimumPrice = 2;
                                if($this->price price;}
                                
                        }
                        
                        public function getPrice() {
                            
                            return $this->price;
                            
                        }
    
                    }
                    
                    $mobile = new BuyMe("Mobile");
                    
                    $mobile->setPrice(10);
                    
                    echo $mobile->getPrice();
    

    We need to clarify a few things.
    First, to create a class, we need a class keyword. Next, it is not mandatory that we should always write the __construct() method. Although, whenever an object is instantiated, this constructor method is called first. If you want to pass any data in the beginning, you can pass through it.
    In the second example, we have used set() and get() methods. These setter and getter methods are extremely handy when we need some validation. Here the price is set so you get the price. If it were not, it would throw an exception.
    Nothing is mandatory here. If you don’t want, just don’t write it.

    Types of flow control in PHP

    Tags

    , , ,

    wp1//embedr.flickr.com/assets/client-code.js
    Flow control is the point where you start making decisions in your code. Next, you execute further code depending on those decisions.
    In human language, “if” is a conjunction. Here, in programming, it is a statement.

    If(expression){
    statement
    }

    Here, expression is a php expression that evaluates TRUE or FALSE value. If your expression is TRUE, the statement that follows is executed. If it’s FALSE, it’s not executed.
    Before moving forward, I’d suggest you to consult any beginner’s PHP book where you can learn about operators – conditional and logical, both. You also need to know about operator precedence.
    Let us see one quick example.

    //if there is two possibilities
    $low = 10;
    $high = 30;
    $temp = 20;

    if ($temp $high){
    echo 'Stay inside';
    }
    else{
    echo 'Nice temperature out.';
    }

    Here we have checked the temperature outside. We have assigned a value (20) to the $temp variable. It is neither lower than the low temperature (10) nor it is higher than the high temperature (30). So our output is obvious. The php expression is FALSE. So the output will be “Nice temperature out.”
    Now, we can also write the same code in a different way. It is called ‘Ternary Operator’. This is a built-in operator that acts like an if statement. However, it has an unusual form.

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

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


    Here is the example where we are trying to test the same code through ternary operator. I give the full code, so that you can compare it with the if statement.


    //if there are two possibilities
    $low = 10;
    $high = 30;
    $temp = 20;

    if ($temp $high){
    echo 'Stay inside';
    }
    else{
    echo 'Nice temperature out.';
    }

    echo '
    ';

    //we can also write it using ternary operator
    $ter = ($temp $high) ? "Stay in" : "Go out";
    echo $ter;

    In the ternary operator, we put the expression part within first bracket. After that, we have used a question mark. We keep two possibilities. In addition, to differentiate two possibilities we put a colon between them.

    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.

    Now, consider a third possibility. To solve that problem, we introduce “elseif” between “if and else”.

    if ($temp > $high)
    {
    echo "Don’t go out.";
    }
    elseif ($temp < $low)
    {
    echo " Don’t go out.";
    }
    else
    {
    echo " It is good outside.";
    }

    You can continue using “elseif” as long as you wish. You can test many possibilities.
    To test many possibilities, you can use “switch” statement.


    // Example of switch statement

    $variable = 45;

    switch ($variable) {
    case 5:
    case 10:
    case 14:
    echo 'Too cold.';
    break;
    case 15:
    case 20:
    case 22:
    echo 'Moderate.';
    break;
    case 30:
    case 35:
    case 40:
    echo 'Too hot.';
    break;

    default:
    echo 'If all cases fail, this will be the final value: it is not good out.';
    break;
    }

    Here a temperature is given and we test that temperature against many possibilities. We can write as many “cases” as possible, it is just like “elseif”.
    Now comes the best part of flow control.
    Loop.
    You know that computers are great at doing repetitive tasks. Moreover, we are happy knowing that, because we don’t like doing repetitive tasks. That makes computer strong and popular. Like other programming languages, php also comes with standard loops that help computer doing the repetitive tasks easily.
    Here is an example of “for loop”.

    //$index = 1;

    for ($index = 0; $index < 3; $index++) {

    if ($index == 0){continue;}
    echo "1/$index : " . 1/$index . "
    ";
    //$index++;

    }

    While loop statement is slightly different in nature and you should handle it carefully. As a beginner, one may make a mess in the code if he or she cannot write while loop properly.
    It is very good in calculating few typical applications like gross salaries of 200 different persons. Or you may want to take a list of highest and lowest temperatures of a definite month or a year.
    Although the while statement is simple, people may make mistake. It happens because while loop executes the statement repeatedly as long as the condition is true.

    $num=1;
    while ($num <=10)
    {
    echo "Increment Number : $num
    ";>
    $num = $num + 1;
    }

    Forgetfully if you wrote the opposite way, that is, if you wanted to check whether $num is greater than 10, suddenly there would be a lot of confusion. The infinite loop traps the code in such cases and it continues until the end.
    On the other hand, foreach loop statement works only on arrays. It is easy to handle. For manipulating and working on array, it is extremely essential.
    We write it in this way:
    foreach ($array as $key => $value) {

    }
    Suppose we want to find total numbers of a given array. The code will be like this:
    $array = [10, 25, 123654, 7854];
    foreach ($array as $value) {

    //the total of the numbers
    $TotalOfTheNumbers = $TotalOfTheNumbers + $value;

    }
    Sometimes, you can ignore the key for the numbers as the key starts from 0. In the above code, the values are important.

    how to make your own php framework

    Tags

    , , , , , ,

    php7 copy//embedr.flickr.com/assets/client-code.js
    Your framework should be specific. It should not call a lot of other functions and drag them along with single request making your application slow.
    The first step could be a simple Router.
    This Router object will show you how you can pass a URI and find the desired page.
    Let’s go and make it.

    
    $router = [
                        
                        "/" => "index.php",
                        "/about" => "about.php"
                        
                    ];
                    
                    class Router {
                        
                        public $array = [];
                        public $url;
                        public $destination;
    
                        function __construct($array) {
                            $this->array = $array;
                        }
                        
                        function redirect($url, $destination) {
                            $this->url = $url;
                            $this->destination = $destination;
                            
                            if(array_key_exists($this->url, $this->array)){
                                
                                return $this->array["{$this->url}"];
                                
                            }
                            else{
                                
                                return FALSE;
                                
                            }
                        }
    
                    }
                    
                    $route = new Router($router);
                    
                    echo $route->redirect("/", "index.php");
    
    
    
    
    

    Don’t forget to add the PHP tag.

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

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


    We can try the same thing in a different way using PHP overloading methods.

    
    class OverloadingClass {
                        
                        protected $uri;
                        protected $response;
    
                        function __construct() {
                            
                            echo 'This is overloading constructor.
    '; } function getResponse() { return "Here is the URI = " . $this->uri . " and here is the Response = " . $this->response . "
    "; } function setResponse($response) { $this->response = $response; } //we are overloading the uri and response at the same time function __call($name, $arguments) { if($name == "setURI"){ if(count($arguments) == 1){ $this->uri = $arguments[0]; } if(count($arguments) == 2){ $this->uri = $arguments[0]; $this->response = $arguments[1]; } } } } echo 'CReating our new router...
    '; $router = new OverloadingClass(); $router->setURI("/about"); $router->setResponse("about.php"); echo $router->getResponse(); $router->setURI("/contact", "contact.php"); echo $router->getResponse();

    The output is nteresting.

    CReating our new router…
    This is overloading constructor.
    Here is the URI = /about and here is the Response = about.php
    Here is the URI = /contact and here is the Response = contact.php

    Now the possibility is endless.

    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.

    php functions example

    Tags

    , , , , ,

    test1//embedr.flickr.com/assets/client-code.js

    Creating your own functions in PHP is our next big step in web programming. You’ve already seen a few built-in PHP functions already.
    What are functions? The functions are the callable sections of your code where you can pass data and it returns data to you. Do you have some parts of code to run multiple times in your code? Put them into a function. Got some code that shouldn’t run automatically when the page loads? Put it into a function. Is there a too long code that is difficult to debug? Break it into several functions so that you can pinpoint the error easily.
    Now, let’s try to understand it from a different point of view.

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

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

    In any language, “Noun, Adjective, Adverb, Pronoun, Articles” do not do anything. They definitely take part in the action. But without the verb an action remains incomplete. Functions in PHP play the same role. This is the action part. You pass some data and the functions return you some data. Try to imagine a simple function where you pass two integers and the function adds it and gives you back the result.
    I hope it helps.
    By putting code into a function, you actually convert it into action-verb. Such as, you’re putting some air in a function and when you call it, it generates electricity. Think this way; you pass ‘air’ data into a function and it returns ‘electricity’ data.
    So we learn a very important thing. If I pass data to a function, it returns data. You’ll find this concept in every programming language. But PHP has some unique features.

    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.

    Remember, it’s just the beginning of an interesting journey. You are going to learn how to divide up your code. Learning functions is the precursor to the next big thing – object oriented programming (OOP). In the next chapter we’ll learn how OOP lets you wrap both functions and data into classes and objects, so that the coding becomes easier.

    BASIC FUNCTIONS WHERE WE PASS SOME DATA

    How do you build your own function?
    It’s very easy. The structure is like this:
    function function_name ([argument_list_to_pass_data]){
    “””Some statements, works to be done”””
    return Returning_data
    }
    If you’re complete new, this example really doesn’t make sense. So let’s see some real-world-examples. Imagine a situation, where a user visits your website. The user logs in, so that your website automatically knows that username and greets him or her.
    You need to write several functions until you reach the end. But we can, at least, write a very simple function to understand the core conception. Suppose the user’s name is Sanjib.

    
    function GreetingsDisplay($message, $username) {
        
        return $message . " " . $username;
        
    }
    
    
    

    echo GreetingsDisplay(“Hello”, “Sanjib”);
    The function greets you with the message – Hello Sanjib.
    People describe science as the greatest adventure in this world. I think learning php is no less. Let’s be more adventurous and build a little bit more complex application.
    In this application, we pass an array of numbers through a function and get the average of that number.
    Remember, if you don’t pass any number, it’ll give you an output like this – “No Input”.
    Here is the example code:

    
    
                    // suppose we have some numbers in array
                    $numbers = [];
                    
                    echo averager($numbers);
                    
                    function averager($array) {
                        
                        $TotalOfTheNumbers = 0;
                        $average = 0;
                        $NumberOfNUmbers = 0;
                    
                        foreach ($array as $value) {
    
                            //the total of the numbers
                            $TotalOfTheNumbers = $TotalOfTheNumbers + $value;
    
                        }
                        //how many numbers ar there
                        $NumberOfNUmbers = count($array);
                        
                        //if there is no input
                        
                        if(count($array) > 0){
                            
                            //we'll get some verage value
                            $average = $TotalOfTheNumbers/$NumberOfNUmbers;
                            return $average;
                            
                        }
                        else{
                            
                            echo 'No input';
                            
                        }  
                        
                    } 
                    
    

    Functions are integral parts of your web application. The basic duty of a function is – it gets data inside and gives an output. This output may become inputs of another function; and your application grows.
    PASSING BIG DATA THROUGH FUNCTIONS
    Now the time has come to take the stage for the big moment.

    
                    
                    $num = 4;
                    
                    //we want to square the value in a variable
                    //will that change the original value?
                    //the answer is NO
    
                    function squarer($number) {
                        
                        $number *= $number;
                        return $number;
                        
                    }
                    //before the function call
                    echo "The original value - " . $num;
                    
                    squarer($num);
                    
                    //after the function call
                    echo "After the function call, the original value remains same - " . $num;
                    
                    
                    /*
                     * our conclusion:
                     * the function could not change the original value
                     * a copy of that value was passed and the original value remained unchanged
                     * But, if we pass the value by reference, the original value is also changed
                     */
                    
                    function passByRef(&$param) {
                        
                        $param *= $param;
                        return $param;
                        
                    }
                    
                    passByRef($num);
                    //after the new function call
                    echo "After passing data by reference, the original value takes the new value - " . $num;
    
                    
    

    This function is a big deal. Why? It’s because, you have learned how to pass data by reference and thereby change the actual value.
    We have declared a number and assign a value – 4 to it. Now, we have passed that number through a function that multiplies that number by itself making it 16. But the number has not changed. Why it happens? It happens, because, generally, when we pass any value through any function, a copy passes through it. Not the original one. The original one remains unchanged.
    Now look at the second part of the above code.

    
    function passByRef(&$param) {
                        
                        $param *= $param;
                        return $param;
                        
                    }
                    
                    passByRef($num);
                    //after the new function call
                    echo "After passing data by reference, the original value takes the new value - " . $num;
    
    
    

    This time we have passed the value by reference and the original value changes. The original value was 4. Now it is 16.