Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Tag: PHP

PHP

  • Database

    Database Basics

    MySQL Commands

    MySQL is a widely-used open-source relational database management system. Here are some essential MySQL commands for database management:

    • Establishing a connection:
    • 
      $link = mysql_connect("host", "username", "password");
      $db = mysql_select_db("database", $link);
              
    • Executing queries:
    • 
      $rs = mysql_query("query", $link); // Retrieve data
      $rs = mysql_query("query", $link); // Execute commands
              
    • Fetching data:
    • 
      $row = mysql_fetch_array($rs); // Retrieve data as an index array
      $row = mysql_fetch_assoc($rs); // Retrieve data as an associative array
              
    • Managing connections:
    • 
      mysql_close($link); // Close connection
              
    • Additional functions:
    • 
      mysql_insert_id($rs); // Get ID of the last inserted record
      mysql_error($link); // Retrieve the last error
      $output = mysql_real_escape_string("unescaped_string", $link); // Secure data
              

    Creating New Links with MySQL

    To create a new link with additional security in MySQL, set the newlink parameter to true:

    
    $link = mysql_connect("host", "username", "password", true);
        

    MySQLi (MySQL Improved)

    MySQLi is an enhanced extension of MySQL in PHP, providing improved features and security. Key features of MySQLi and PHP Data Objects (PDO) include:

    • Connection versatility
    • Enhanced security through prepared statements
    • Support for atomic transactions with beginTransaction, commit, and rollBack
    
    try {
        $dsn = 'mysql:host=localhost;dbname=library';
        $dbh = new PDO($dsn, 'dbuser', 'dbpass');
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $dbh->beginTransaction();
        $affected = $dbh->exec("sql"); // Execute SQL query
        $dbh->commit(); // Commit transaction
        $dbh->rollBack(); // Roll back transaction
    
        $sql = "SELECT * FROM table WHERE id = :param1";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':param1', $param1);
        $stmt->execute();
        $results = $stmt->fetchAll();
    
        foreach ($results as $row) {
            // Process each row
        }
    } catch (PDOException $e) {
        echo "Failed: " . $e->getMessage();
    }
        

    Persistent Connections

    Persistent connections in databases maintain their state even after executing a script. Various ways to establish persistent connections based on the database extension used include:

    • In MySQL:
    • 
      mysql_pconnect();
              
    • In MySQLi:
    • 
      mysqli_connect("p:host", "username", "password");
              
    • Using PDO:
    • 
      $dsn = 'mysql:host=localhost;dbname=example_db';
      $options = array(PDO::ATTR_PERSISTENT => true);
      $dbh = new PDO($dsn, 'dbuser', 'dbpass', $options);
              
  • Web Service

    Web Service

    Introduction

    Web Service is a standard way of interoperating between different software applications running on a variety of platforms and/or frameworks. It allows for seamless communication and data exchange between disparate systems.

    Types of Web Services

    • SOAP: Stands for Simple Object Access Protocol. It is a protocol for exchanging structured information in the implementation of web services in computer networks.
    • RPC: Remote Procedure Call is the most common messaging pattern used in web services where a client invokes a procedure on a remote server.
    • REST: Representational State Transfer is an architectural style that uses a stateless, client-server communication protocol. Resources are identified by global identifiers (URIs) and accessed via HTTP methods.

    RESTful services do not have a WSDL (Web Services Description Language) and are commonly used by websites that provide RSS and RDF feeds. Services like Delicious offer XML data that can be consumed by clients using SimpleXML.

    Key Terminologies

    • WSDL: Web Services Description Language is an XML format for describing network services as a set of endpoints operating on messages.
    • UDDI: Universal Description Discovery and Integration is a directory service where web services can be registered and discovered.

    PHP and Web Services

    In PHP, NuSOAP is a popular SOAP library used to create and consume SOAP-based web services. PHP provides built-in tools like SoapServer and SoapClient for implementing web services.

    Server-side Implementation

    
    // Define the SOAP server
    $options = array('uri' => 'http://example.org/soap/server/');
    $server = new SoapServer(NULL, $options);
    $server->setClass('MySoapServer');
    $server->handle();
    

    Client-side Implementation

    
    try {
        $options = array(
            'location' => 'http://example.org/soap/server/server.php',
            'uri' => 'http://example.org/soap/server/',
            'trace' => 1
        );
        $client = new SoapClient(NULL, $options);
        
        // Call the method on the server
        $results = $client->method(param);
        
        // Debugging information
        echo $client->__getLastRequestHeaders(); // Display request headers
        echo $client->__getLastRequest(); // Display request XML body
    } catch (SoapFault $e) {
        echo $e->getMessage();
    }
    
  • XML


    XML

    XML stands for Extended Markup Language. It is a markup language that defines rules for encoding documents in a format that is both human-readable and machine-readable.

    • DTD or Document Type Definition provides information about the structure and content of a particular XML document.
    • An entity in XML is a named storage unit, similar to a tag, used to define reusable content.
    • An element in XML typically consists of attributes and text content.
    • The content or value of an entity in XML refers to the actual data stored within the entity.

    SimpleXML

    SimpleXML is a PHP 5 library specifically designed for working with XML data. It simplifies the process of parsing and manipulating XML documents.

    
    $library = new SimpleXMLElement($xmlstr); // Load XML from a string.
    $library = new SimpleXMLElement('library.xml', null, true); // Load XML from a file.
    
    foreach ($library->book as $book) {
        echo $book['isbn'] . "n"; // Accessing an attribute.
        echo $book->title . "n"; // Accessing a child element.
    }
    
    foreach ($library->children() as $child => $valuechild) {
        echo $child->getName() . "=" . $child;
        echo $child . "=" . $valuechild;
        foreach ($child->attributes() as $attr => $valueattr) {
            echo $attr->getName() . "=" . $attr;
            echo $attr . "=" . $valueattr;
        }
    }
        

    XPATH

    XPath (XML Path Language) is a query language used for navigating through and selecting nodes in an XML document.

    
    $results = $library->xpath('/library/book/title'); // Returns the XML object defined by the XPath expression.
    
    $newbook = $book->addChild('title', 'Enders Game'); // Adding a child element with a specified value.
    $book->addAttribute('isbn', 0812550706); // Adding an attribute to an element.
    
    header('Content-type: text/xml'); // Setting the header for XML content.
    echo $library->asXML(); // Output the XML content.
    
    // Additional operations such as removing elements and working with namespaces can also be performed using XPath.
        

    DOM

    DOM (Document Object Model) in PHP provides a way to represent and interact with structured documents like XML and HTML.

    
    $dom = new DomDocument();
    
    $dom->load('library.xml'); // Load XML content from a file.
    $dom->loadXML($xml); // Load XML content from a string.
    
    $dom->loadHTMLFile('library.html'); // Load HTML content from a file.
    $dom->loadHTML($html); // Load HTML content from a string.
    
    $dom->saveXML(); // Save the document as XML.
    $dom->saveHTML(); // Save the document as HTML.
    
    $element = $dom->createElement('a', 'This is a link!'); // Create a new element.
    $element = $dom->getAttribute('target'); // Get the value of an attribute.
    $element = $dom->hasAttribute('target'); // Check if an attribute exists.
    $element = $dom->setAttribute('target', '_blank'); // Set a new attribute.
    $element = $dom->removeAttribute('target'); // Remove an attribute.
        
  • Design Pattern

    Design Patterns in PHP

    Introduction to Design Patterns

    Design patterns are proven solutions to common software design problems that have been implemented and refined over time. They offer a structured approach to addressing recurring design challenges, enhancing code reusability, maintainability, and scalability. Design patterns can be applied in various programming paradigms, including procedural programming and Object-Oriented Programming (OOP).

    Singleton Pattern

    The Singleton Pattern ensures that a class has only one instance globally accessible across the application. It is useful when you want to control the instantiation of a class and restrict it to a single object. In PHP, the Singleton Pattern typically involves a private constructor to prevent direct instantiation and a static method to provide access to the single instance.

    An example of applying the Singleton Pattern in PHP is in managing a database connection. By enforcing a single database connection instance, you can avoid unnecessary overhead and ensure data consistency throughout the application.

    Factory Pattern

    The Factory Pattern is a creational design pattern that delegates the responsibility of object creation to a separate factory class. This pattern enables the creation of objects without specifying their concrete classes, promoting flexibility and decoupling. By centralizing object creation logic, the Factory Pattern simplifies the process of adding new object types without modifying existing code.

    For instance, a system handling data storage can utilize the Factory Pattern to instantiate different storage classes based on user preferences. By adhering to a common interface, such as a storage interface, the factory can create diverse storage objects like INI, DB, or XML without exposing the instantiation details to the client code.

    Registry Pattern

    The Registry Pattern serves as a global store for sharing objects and data across different components of an application. It acts as a centralized repository for resources, offering a convenient way to access and manage shared objects. By utilizing the Registry Pattern, developers can simplify resource handling and enhance the accessibility of commonly used objects.

    In PHP, the Registry Pattern can be implemented to store instances of classes or configuration settings in a key-value store, facilitating easy retrieval and modification of shared resources throughout the application’s execution.

    MVC (Model-View-Controller) Pattern

    The MVC pattern is a widely adopted architectural pattern in web development for structuring applications into three interconnected components: Model, View, and Controller. The Model represents the application’s data and business logic, the View presents the data to the user, and the Controller manages user input and orchestrates interactions between the Model and View.

    Active Record Pattern

    The Active Record Pattern is an architectural pattern that links database records to objects in an object-oriented manner. It encapsulates database operations within the object itself, enabling developers to interact with the database using object-oriented methods rather than raw SQL queries. By integrating the Active Record Pattern, developers can streamline CRUD operations (Create, Read, Update, Delete) on database records, simplifying data manipulation and retrieval tasks.

    By following the Active Record Pattern, each object instance corresponds to a row in the database table, allowing developers to manipulate data directly through the object’s methods, enhancing code readability and maintainability.

  • OO PHP

    Understanding Object-Oriented PHP

    Introduction

    Object-Oriented PHP, predominantly version 5, offers a powerful way to structure and organize code for better maintainability and reusability.

    Basic Class Structure

    
    class ClassName {
        // Class properties
        public $variable;
    
        // Class methods
        public function method() {}
    }
    
    $obj = new ClassName();
    $obj->method();
    

    The $this variable always refers to the current object being worked on.

    Access Control Modifiers

    PHP supports access control modifiers like public, private, protected, abstract, and final for defining the visibility of properties and methods within a class.

    Inheritance and Constructors

    PHP uses the extends keyword for inheritance. Constructors are defined using __construct() and destructors using __destruct(). The parent:: keyword is used to access parent class methods.

    Object Manipulation

    • Use unset() to destroy objects and trigger the destructor.
    • Cloning an object is done using clone. The process involves copying all members and calling the __clone() method.

    Polymorphism and Binding

    Polymorphism in PHP allows one interface to control access to a general class of actions. It can be achieved through compile-time polymorphism (function overloading) and run-time polymorphism (inheritance and virtual functions).

    Early binding determines the execution path at compile time, while late binding allows for dynamic execution at runtime.

    Magic Methods

    • __sleep() and __wakeup() for serialization and deserialization.
    • __autoload(classname) for autoloading classes.
    • __get(propname) and __set(key, value) for handling unknown properties.
    • __call() for handling unknown methods.
    • __toString() for converting objects to strings.

    Static Methods and Properties

    Static method calls are compiled at compile time and accessed using classname::method(). Static properties can only be accessed within static functions.

    Advanced Concepts

    • PHP provides functions like class_exists(), get_class(), and get_declared_classes() for class manipulation.
    • Overloading and overriding allow for dynamic creation of properties and methods, as well as method redefinition in derived classes.
    • Interfaces facilitate multiple inheritance and ensure implementation of all defined methods in implementing classes.
    • Traits enable code reuse across classes by grouping functions together.
    • Reflection API allows for introspection of classes, interfaces, functions, and methods, including retrieval of doc comments.

    Dereferencing and Lazy Loading

    Dereferencing in PHP involves accessing return values without assigning them to intermediate variables first. Lazy loading refers to loading classes only when needed, enhancing performance.

    Conclusion

    Object-Oriented PHP offers a robust way of structuring code, promoting reusability and maintainability through concepts like classes, inheritance, polymorphism, and advanced features like magic methods and reflection.

  • Functions

    Functions in PHP

    Function Overloading in PHP

    PHP does not directly support function overloading. However, you can simulate function overloading using the __call__ magic method. This is possible because PHP functions can accept variable-length argument lists. To handle variable arguments, functions like func_num_args(), func_get_arg(), and func_get_args() can be used.

    Default Parameters

    PHP allows you to set default parameters for functions. These parameters are used when no argument is provided for that parameter during a function call.

    Global Variables

    The $GLOBALS array in PHP contains references to all variables available in the global scope. By using the global keyword, you can access global variables within a function by importing them into the local variable table.

    Variable Variables

    PHP supports variable variables, denoted by $$var. This feature enables you to dynamically create variable names and access their values.

    Super Globals in PHP

    PHP provides various superglobal arrays such as $GLOBALS, $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUEST, $_SERVER, and $_ENV. These arrays are accessible from anywhere in your PHP scripts.

    Passing Arguments by Reference

    In PHP, when passing arguments by reference, you use the ampersand (&) operator. Similarly, you can return values by reference using the ampersand operator.

    Anonymous Functions (Closures)

    Anonymous functions, also known as closures, are functions without a specified name. They can be assigned to variables and passed as arguments to other functions. In PHP, anonymous functions yield objects of the closure class.

    $area = function ($side) {
        return $side * $side;
    };
    
    echo $area(5);

    Constants in PHP

    Constants in PHP can be defined using the define() function. The syntax is define("constantname", value, true/false), where setting the third parameter to true makes the constant case-insensitive.

    • To check if a constant is defined, you can use the defined("constantname") function.
    • To retrieve the value of a constant stored in a variable or a function, you can use constant($var), where $var holds the constant name.
  • Strings

    Exploring PHP String Functions

    Serialization and URL Encoding

    In PHP, serialization is the process of converting a data structure or object into a format that can be stored or transmitted. The serialize() function accomplishes this, while unserialize() reverses the process. On the other hand, urlencode() is used to encode a string by replacing special characters with their ASCII values, and urldecode() decodes the URL-encoded string back to its original form.

    Operator Rules and Reference Parameters

    • When using the % operator, the result will have the same sign as the first operand.
    • The reference operator =& can be used to create references in PHP. Additionally, reference parameters like ¶m in a function signature allow a function to modify the variable passed to it.

    Control Flow with Functions

    Understanding how control flows with functions in PHP is crucial. For example, when using the expression $f = func1() or func2();, the second function (func2()) will only execute if func1() returns false. Similarly, $f = func1() and func2(); ensures that func2() is executed only if func1() returns true.

    Other Useful String Functions

    • The Execution Operator ` allows the output of shell commands to be used in PHP scripts.
    • Variable functions in PHP enable dynamic function calls based on the value of a variable.
    • Functions like mb_strpos can be used when multibyte string overloading is enabled in the PHP configuration.
    • Various functions like call_user_func() and call_user_func_array() provide ways to invoke callback functions.
    • The function escapeshellcmd() helps prevent risks associated with executing shell commands through PHP.
    • Functions such as string exec() and bool function_exists() serve different purposes in handling strings and functions.

    Additional PHP String Functions

    • ignore_user_abort(true) ensures that a script continues to run even if the user aborts the execution.
    • The nl2br() function inserts HTML line breaks before all newlines in a string.
    • Utilize string number_format() to format numbers with specified decimal points and thousand separators.
    • For handling query parameters, combining QUERY_STRING and parse_str() can be useful.

    Security and Formatting Functions

    • Functions like sha1() provide secure hash algorithms for generating checksums.
    • string strip_tags() helps remove HTML tags from a string to prevent cross-site scripting attacks.
    • The wordwrap() function wraps a string to a given number of characters, with options to break at a specific character and cut long words if needed.

    Wrapping Up

    Understanding these PHP string functions and their applications can greatly enhance your programming skills and efficiency in handling various tasks related to string manipulation, encoding, and security.

  • Arrays

    Arrays in PHP

    Array Construction

    Arrays in PHP can be constructed using different methods:

    • array() construct: This is a language construct to create an array in PHP.
    • Array operator []: Using square brackets to define and initialize an array.

    Array Printing

    Printing arrays in PHP can be done using various functions:

    • print_r(): This function is used to display human-readable information about a variable, especially useful for arrays.
    • var_dump(): A debugging function that displays structured information about variables, including type and value.
    • var_export(): Outputs or returns a parsable string representation of a variable, mainly used for debugging arrays.

    Array Operations

    Performing operations on arrays in PHP involves various functions and methods:

    • array(key = value) and array[key]=value: Ways to define key-value pairs in an array in PHP.
    • Merging arrays: Using the + operator to merge two arrays into a new array.
    • extract($arr, EXTR_PREFIX_ALL): Imports variables into the current symbol table from an array.
    • count($arr, 1): Counts the number of elements in an array recursively, with the second argument to count elements in sub-arrays.

    Array Cursors

    PHP provides array cursor functions for easy navigation and manipulation:

    • reset(): Resets the internal array pointer to the first element of the array.
    • end(): Moves the internal array pointer to the last element of the array.
    • next(): Advances the array pointer to the next element and returns its value.
    • prev(): Moves the array pointer to the previous element and returns its value.