Author: Saim Khalid

  • PHP Constants

    What is Constant in PHP

    A constant is a name or an identifier for a fixed value. Constant are like variables, except that once they are defined, they cannot be undefined or changed (except magic constants).

    Constants are very useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings such as database username and password, website’s base URL, company name, etc.

    Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a simple example:

    Example

    <?php
    // Defining constant
    define("SITE_URL", "https://www.tutorialrepublic.com/");
     
    // Using constant
    echo 'Thank you for visiting - ' . SITE_URL;
    ?>

    The output of the above code will be:

    The PHP echo statement is often used to display or output data to the web browser. We will learn more about this statement in the next chapter.

    Tip: By storing the value in a constant instead of a variable, you can make sure that the value won’t get changed accidentally when your application runs.


    Naming Conventions for PHP Constants

    Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $ prefix is not required for constant names.

  • PHP Constants

    What is Constant in PHP

    A constant is a name or an identifier for a fixed value. Constant are like variables, except that once they are defined, they cannot be undefined or changed (except magic constants).

    Constants are very useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings such as database username and password, website’s base URL, company name, etc.

    Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a simple example:

    Example

    <?php
    // Defining constant
    define("SITE_URL", "https://www.tutorialrepublic.com/");
     
    // Using constant
    echo 'Thank you for visiting - ' . SITE_URL;
    ?>

    The output of the above code will be:

    The PHP echo statement is often used to display or output data to the web browser. We will learn more about this statement in the next chapter.

    Tip: By storing the value in a constant instead of a variable, you can make sure that the value won’t get changed accidentally when your application runs.


    Naming Conventions for PHP Constants

    Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $ prefix is not required for constant names.

  • PHP Variables

    What is Variable in PHP

    Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script. Here’re some important things to know about variables:

    • In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
    • After declaring a variable it can be reused throughout the code.
    • The assignment operator (=) used to assign value to a variable.

    In PHP variable can be declared as: $var_name = value;

    Example

    <?php
    // Declaring variables
    $txt = "Hello World!";
    $number = 10;
     
    // Displaying variables value
    echo $txt;  // Output: Hello World!
    echo $number; // Output: 10
    ?>

    In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number. Later we’ve displayed the variables values in the browser using the echo statement. The PHP echo statement is often used to output data to the browser. We will learn more about this in upcoming chapter.

    Naming Conventions for PHP Variables

    These are the following rules for naming a PHP variable:

    • All variables in PHP start with a $ sign, followed by the name of the variable.
    • A variable name must start with a letter or the underscore character _.
    • A variable name cannot start with a number.
    • A variable name in PHP can only contain alpha-numeric characters and    underscores (A-z0-9, and _).
    • A variable name cannot contain spaces.
  • PHP Syntax

    Standard PHP Syntax

    A PHP script starts with the <?php and ends with the ?> tag.

    The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed code block as PHP code, rather than simple HTML.

    Example

    <?php
    // Some code to be executed
    echo "Hello, world!";
    ?>

    Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current statement has been reached.


    Embedding PHP within HTML

    PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like you do in regular HTML pages as well as embed PHP codes for server side execution.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>A Simple PHP File</title>
    </head>
    <body>
        <h1><?php echo "Hello, world!"; ?></h1>
    </body>
    </html>

    The above example shows how you can embed PHP codes within HTML to create well-formed dynamic web pages. If you view the source code of the resulting web page in your browser, the only difference you will see is the PHP code <?php echo "Hello, world!"; ?> has been replaced with the output “Hello, world!”.

    What happend here is? when you run this code the PHP engine exacuted the instructions between the <?php … ?> tags and leave rest of the thing as it is. At the end the web server send the final output back to your browser which is completely in HTML.


    PHP Comments

    A comment is simply text that is ignored by the PHP engine. The purpose of comments is to make the code more readable. It may help other developer (or you in the future when you edit the source code) to understand what you were trying to do with the PHP.

    PHP support single-line as well as multi-line comments. To write a single-line comment either start the line with either two slashes (//) or a hash symbol (#). For example:

    Example

    <?php
    // This is a single line comment
    # This is also a single line comment
    echo "Hello, world!";
    ?>

    However to write multi-line comments, start the comment with a slash followed by an asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like this:

    Example

    <?php
    /*
    This is a multiple line comment block
    that spans across more than
    one line
    */
    echo "Hello, world!";
    ?>

    Case Sensitivity in PHP

    Variable names in PHP are case-sensitive. As a result the variables $color$Color and $COLOR are treated as three different variables.

    Example

    <?php
    // Assign value to variable
    $color = "blue";
     
    // Try to print variable value
    echo "The color of the sky is " . $color . "<br>";
    echo "The color of the sky is " . $Color . "<br>";
    echo "The color of the sky is " . $COLOR . "<br>";
    ?>

    If you try to run the above example code it will only display the value of the variable $color and produce the “Undefined variable” warning for the variable $Color and $COLOR.

    However the keywords, function and classes names are case-insensitive. As a result calling the gettype() or GETTYPE() produce the same result.

    Example

    <?php
    // Assign value to variable
    $color = "blue";
     
    // Get the type of a variable
    echo gettype($color) . "<br>";
    echo GETTYPE($color) . "<br>";
    ?>

    If you try to run the above example code both the functions gettype() and GETTYPE() gives the same output, which is: string.

  • PHP Getting Started

    Getting Started with PHP

    Here, you will learn how easy it is to create dynamic web pages using PHP. Before begin, be sure to have a code editor and some working knowledge of HTML and CSS.

    If you’re just starting out in web development, start learning from here »

    Well, let’s get straight into it.

    Setting Up a Local Web Server

    PHP script execute on a web server running PHP. So before you start writing any PHP program you need the following program installed on your computer.

    • The Apache Web server
    • The PHP engine
    • The MySQL database server

    You can either install them individually or choose a pre-configured package for your operating system like Linux and Windows. Popular pre-configured package are XAMPP and WampServer.

    WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP and a MySQL database. It will also provide the MySQL administrative tool PhpMyAdmin to easily manage your databases using a web browser.

    The official website for downloading and installation instructions for the WampServer: http://www.wampserver.com/en/


    Creating Your First PHP Script

    Now that you have successfully installed WampServer on your computer. In this section we will create a very simple PHP script that displays the text “Hello, world!” in the browser window.

    Ok, click on the WampServer icon somewhere on your Windows task bar and select the “www directory”. Alternatively, you can access the “www” directory through navigating the C:\wamp\www. Create a subdirectory in “www” directory let’s say “project”.

    Now open up your favorite code editor and create a new PHP file then type the following code:

    Example

    <?php
    // Display greeting message
    echo "Hello, world!";
    ?>

    Now save this file as “hello.php” in your project folder (located at C:\wamp\www\project), and view the result in your browser through visiting this URL: http://localhost/project/hello.php.

    Alternatively, you can access the “hello.php” file through selecting the localhost option and then select the project folder from the WampSever menu on the taskbar.

    PHP can be embedded within a normal HTML web page. That means inside your HTML document you can write the PHP statements, as demonstrated in the follwoing example:

    Example

    <!DOCTYPE HTML>
    <html>
    <head>
        <title>PHP Application</title>
    </head>
    <body>
    <?php
    // Display greeting message
    echo 'Hello World!';
    ?>
    </body>
    </html>

    You will learn what each of these statements means in upcoming chapters.

  • PHP Tutorial

    PHP stands for Hypertext Preprocessor. PHP is a very popular and widely-used open source server-side scripting language to write dynamically generated web pages. PHP was originally created by Rasmus Lerdorf in 1994. It was initially known as Personal Home Page.

    PHP scripts are executed on the server and the result is sent to the web browser as plain HTML. PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, Sybase, and so on. The current major version of PHP is 7. All of the code in this tutorial has been tested and validated against the most recent release of PHP 7.

    PHP is very powerful language yet easy to learn and use. So bookmark this website and continued on.

    Tip: Our PHP tutorial will help you to learn the fundamentals of the PHP scripting language, from the basic to advanced topics step-by-step. If you’re a beginner, start with the basics and gradually move forward by learning a little bit every day.


    What You Can Do with PHP

    There are lot more things you can do with PHP.

    • You can generate pages and files dynamically.
    • You can create, open, read, write and close files on the server.
    • You can collect data from a web form such as user information, email, phone no, etc.
    • You can send emails to the users of your website.
    • You can send and receive cookies to track the visitor of your website.
    • You can store, delete, and modify information in your database.
    • You can restrict unauthorized access to your website.
    • You can encrypt data for safe transmission over internet.

    The list does not end here, there are many other interesting things that you can do with PHP. You will learn about all of them in detail in upcoming chapters.


    Advantages of PHP over Other Languages

    If you’re familiar with other server-side languages like ASP.NET or Java, you might be wondering what makes PHP so special. There are several advantages why one should choose PHP.

    • Easy to learn: PHP is easy to learn and use. For beginner programmers who just started out in web development, PHP is often considered as the preferable choice of language to learn.
    • Open source: PHP is an open-source project. It is developed and maintained by a worldwide community of developers who make its source code freely available to download and use.
    • Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac OS, etc. and it is compatible with almost all servers used today such Apache, IIS, etc.
    • Fast Performance: Scripts written in PHP usually execute or runs faster than those written in other scripting languages like ASP, Ruby, Python, Java, etc.
    • Vast Community: Since PHP is supported by the worldwide community, finding help or documentation related to PHP online is extremely easy.

    Tip: Do you know some huge websites like Facebook, Yahoo, Flickr, and Wikipedia are built using PHP. Most of the major content management systems (CMS), such as WordPress, Drupal, Joomla and Magento are also built in PHP.


    What This Tutorial Covers

    This PHP tutorial series covers all the fundamental programming concepts, including data types, operators, creating and using variables, generating outputs, structuring your code to make decisions in your programs or to loop over the same block of code multiple times, creating and manipulating strings and arrays, defining and calling functions, and so on.

    Once you’re comfortable with the basics, you’ll move on to next level that explains the concept file system, sessions and cookies, dates and times, as well as how to send email from your script, handling and validating forms, perform data filtration and handling errors in PHP.

    Finally, you’ll explore some advanced concepts like classes and objects, parsing JSON data, pattern matching with regular expressions, exception handling as well as how to use PHP to manipulate data in MySQL database and create useful features like user login system, Ajax search, etc.

    Tip: Every chapter in this tutorial contains lots of real-world examples that you can try and test using an online editor. These examples will help you to better understand the concept or topic. It also contains smart workarounds as well as useful tips and important notes.

  • Ruby XPath and XSLT

    Ruby XPath

    Ruby XPath is a language to find information in an XML file. It is an alternative to view XML file. It is used to navigate through elements and attributes in an XML document, treating that document as a logical ordered tree.

    Ruby XPath is very useful to get relevant information and attributes from XML file. It takes tree-based parsing.

    Example:

    
    
    1. #!/usr/bin/ruby -w   
    2.   
    3. require 'rexml/document'   
    4. include REXML   
    5.   
    6. xmlfile = File.new("trial.xml")   
    7. xmldoc = Document.new(xmlfile)   
    8.   
    9. # Info for the first cloth found   
    10. clothing = XPath.first(xmldoc, "//clothing")   
    11. p clothing   
    12.   
    13. # Print out all the cloth types   
    14. XPath.each(xmldoc, "//type") { |e| puts e.text }   
    15.   
    16. # Get an array of all of the cloth brands.   
    17. names = XPath.match(xmldoc, "//brand").map {|x| x.text }   
    18. p names 

    Output:

    Ruby Xpath and xslt 1

    Ruby XSLT

    Ruby XSLT is a simple class based on libxml and libxslt. There are two XSLT parsers available for Ruby.

    • Ruby-Sablotron
    • XSLT4R

    It is freely distributable according to the terms of GNU. This program is distributed without any warranty.

    Ruby-Sablotron

    It is mainly written for Linux operating system and is written by Masayoshi Takahashi.

    It requires the following libraries:

    • Sablot
    • Iconv
    • Expat

    XSLT4R

    It is written by Michael Neumann. It uses a simple command line interface and it can be alternatively used within a third-party application to transform an XML document.

    XSLT4R needs XMLScan to operate, which is included within the XSLT4R archieve. These modules need to be installed using standard Ruby installation method.

    Syntax:

    1. ruby xslt.rb stylesheet.xsl document.xml [arguments]  

    To use XSLT4R within an application, you need to include XSLT and input the parameters you need.


  • Ruby XML (REXML)

    XML is eXtensible Markup Language like HTML. It allows programmers to develop applications that can be read by other applications irrespective of operating system and developmental language used.

    It keeps track of small to medium amounts of data without any SQL based technique in backend.

    REXML is a pure Ruby XML processor. It represents a full XML document including PIs, doctype, etc. An XML document has a single child that can be accessed by root(). If you want to have an XML declaration for a created document, you must add one. REXML documents do not write a default declaration for you.

    REXML was inspired by Electric XML library for Java. Its API is easy to use, small size and have followed the Ruby methodology for method naming and code flow.

    It supports both tree and stream document parsing. Steam parsing is 1.5 times faster than tree parsing. However, in stream parsing you don’t get access to some features like XPath.


    REXML features:

    • It is written 100 percent in Ruby.
    • It contains less than 2000 lines of code, hence, lighter in weight.
    • Its methods and classes are easy to understand.
    • It is shipped with Ruby installation. No need to install it separately.
    • It is used for both DOM and SAX parsing.

    Parsing XML and accessing elements

    Let’s start with parsing an XML document:

    
    
    1. require "rexml/document"  
    2. file = File.new( "trial.xml" )  
    3. doc = REXML::Document.new file 

    In the above code, line 3 parses the supplied file.

    Example:

    require 'rexml/document'   
    
      
    
    include REXML   
    
      
    
    file = File.new("trial.xml")   
    
    doc = Document.new(file)   
    
    puts docs

    In the above code, the require statement loads the REXML library. Then include REXML indicates that we don’t have to use names like REXML::Document. We have created trial.xml file. Document is shown on the screen.

    Output:

    Ruby XML 1

    The Document.new method takes IO, String object or Document as its argument. This argument specifies the source from which XML document has to be read.

    If a Document constructor takes a Document as argument, all its element nodes are cloned to new Document object. If the constructor takes a String argument, string will be expected to contain an XML document.


    XML with “Here Document”

    A here Document is a way to specify a text block, preserving line breaks, whitespaces or identation with text.

    A here Document is constructed using a command followed by “<<” followed by a token string.

    In Ruby, there should be no space between “<<” and token string.

    Example:

    #!/usr/bin/env ruby   
    
      
    
    require 'rexml/document'   
    
    include REXML   
    
      
    
    info = <<XML   
    
    <info>   
    
     <name>Caroline</name>   
    
     <street>9820 St.</street>   
    
     <city>Seattle</city>   
    
     <contact>9854126575</contact>   
    
     <country>USA</country>   
    
    </info>   
    
    XML   
    
      
    
    document = Document.new( info )   
    
    puts document

    Here, we use here Document info. All the characters including newlines between <<EOF and EOF are part of info.

    For XML parsing examples, we will use following XML file code as input:

    file trial.xml

    
    
    1. #!/usr/bin/ruby -w   
    2.   
    3. require 'rexml/document'   
    4. include REXML   
    5. xmlfile = File.new("trial.xml")   
    6. xmldoc = Document.new(xmlfile)   
    7.   
    8. # Now get the root element   
    9. root = xmldoc.root   
    10. puts "Root element : " + root.attributes["shelf"]   
    11.   
    12. # This will output all the cloth titles.   
    13. xmldoc.elements.each("collection/clothing"){   
    14.    |e| puts "cloth Title : " + e.attributes["title"]   
    15. }   
    16.   
    17. # This will output all the cloth types.   
    18. xmldoc.elements.each("collection/clothing/type") {   
    19.    |e| puts "cloth Type : " + e.text   
    20. }   
    21.   
    22. # This will output all the cloth description.   
    23. xmldoc.elements.each("collection/clothing/description") {   
    24.    |e| puts "cloth Description : " + e.text   
    25. }  

    Ruby XML DOM-Like Parsing

    We will parse our XML data in tree fashion. The above file trial.xml code is taken as input.

    
    
    1. #!/usr/bin/ruby -w   
    2.   
    3. require 'rexml/document'   
    4. include REXML   
    5.   
    6. xmlfile = File.new("trial.xml")   
    7. xmldoc = Document.new(xmlfile)   
    8.   
    9. # Now get the root element   
    10. root = xmldoc.root   
    11. puts "Root element : " + root.attributes["shelf"]   
    12.   
    13. # This will output all the cloth titles.   
    14. xmldoc.elements.each("collection/clothing"){   
    15.    |e| puts "cloth Title : " + e.attributes["title"]   
    16. }   
    17.   
    18. # This will output all the cloth types.   
    19. xmldoc.elements.each("collection/clothing/type") {   
    20.    |e| puts "cloth Type : " + e.text   
    21. }   
    22.   
    23. # This will output all the cloth description.   
    24. xmldoc.elements.each("collection/clothing/description") {   
    25.    |e| puts "cloth Description : " + e.text   

    Output:

    Ruby XML 2

    Ruby XML SAX-Like Parsing

    We will parse our XML data in stream fashion. The above file trial.xml code is taken as input. Here, we will define a listener class whose methods will be targeted for callbacks from the parser.

    It is advisable that do not use SAX-like parsing for a small file.

    #!/usr/bin/ruby -w   
    
      
    
    require 'rexml/document'   
    
    require 'rexml/streamlistener'   
    
    include REXML   
    
      
    
    class MyListener   
    
      include REXML::StreamListener   
    
      def tag_start(*args)   
    
        puts "tag_start: #{args.map {|x| x.inspect}.join(', ')}"   
    
      end   
    
      
    
      def text(data)   
    
        return if data =~ /^\w*$/     # whitespace only   
    
        abbrev = data[0..40] + (data.length > 40 ? "..." : "")   
    
        puts "  text   :   #{abbrev.inspect}"   
    
      end   
    
    end   
    
      
    
    list = MyListener.new   
    
    xmlfile = File.new("trial.xml")   
    
    Document.parse_stream(xmlfile, list)

    Output:

    Ruby XML 3
  • Ruby LDAP

    Net::LDAP for Ruby is also written as net::ldap. It stands for Lightweight Directory Access Protocol. It is an internet standard protocol used to access directory servers. Its basic search unit is the entity, which corresponds to a person or other domain-specific object. A directory which supports LDAP protocol, typically stores information about a number of entities.

    Ruby LDAP Principals

    The LDAP servers are generally used to access information about people, but sometimes it is also used for items such as computers, printers and other resources.


    Ruby LDAP Distinguished Names

    In LDAP servers, an entity is uniquely identified by a globally-unique text string called as Distinguished name. It is like a DNS hostname, a DN is a “flattened” text representation of a string of tree nodes.

    You can query an LDAP-enabled directory for information about the entity if you know the DN of a person or other entity. Otherwise, you can also see the list of DNs matching a set of criteria that you supply.


    Ruby LDAP Attributes

    In LDAP, information about the entity is stored as a set of Attributes. An attribute is a text string which is associated with zero or more values. Most LDAP-enabled directories contain a well standardized range of attributes and constrain their values according to standard values.

    An example for attribute is sn. It stands for “surname”. This attribute is generally used to store a person’s surname. Most of the directories follow standard convention that an entity sn attribute will have exactly one value.


    Ruby LDAP Tree-Base

    Just like DNS, LDAP assumes that each directory server contains authoritative attribute data for a set of DNs corresponding to a specific sub-tree of global directory tree. This subtree is configured into directory server when it is created. You can’t query in most of the servers as they will not allow, unless you specify a correct tree-base.


    Ruby LDAP Versions

    Ruby LDAP veraions are stub, discuss v2 and v3.


    Ruby LDAP Operations

    Ruby LDAP operations are:

    • #bind : The #bind operation provides a user’s authentication credentials to a server. They can provide different credentials for authentication but most of the directories ask for username and password only.
    • #add : The #add operation specifies a new DN and an innitial set of attribute values. On the success of operation, a new entity with the corresponding DN and attributes is added to directory.
    • #delete : The #delete operation specifies an entity DN. On the success of operation, the entity and all its attributes is removed from directory.
    • #rename : The #rename operation is also called #modify_rdn. In earlier LDAP versions the only way to change DN of an entity was to delete the whole entity and add it again with a different DN. But with the introduction of #rename operation in version 3, you can change the DN without discarding its attribute values.
    • #search : The #search operation is called to identify a directory by specifying a treebase, search filters and list of attribute values. Multiple filters can be joined together with NOT, AND and OR operators.
    • #modify : The #modify operation specifies an entity DN and a list of attribute operations. It is used to change the attribute values stored in directory for a particular entity. It may add or delete attributes or change attributes by adding or deleting from their values. There are three methods to modify attribute values: #add_attribute, #delete_attribute and #replace_attreibute.

    Installing Net::LDAP

    The net::LDAP is a pure Ruby library. It does not require any external library. RubyGems version of Net::LDAP can be installed from usual sources.

    Requirements

    The Net::LDAP requires Ruby 2.0.0 interpreter or better.

    To install RubyGems version of Net::LDAP, write the following command:

    gem install net-ldap  

    Using Ruby net::LDAP

    The Net::LDAP functionality start by requiring the library.

    require 'net/ldap'  

    If you have installed Gem version, then you need following library.

    require 'rubygems'

    Credentials for LDAP connection

    The Net::LDAP connection is a two step process.

    Step 1 : Instantiating Net:LDAP object

    Most of the Net:LDAP operations start by instantiating Net:LDAP object. The constructor takes arguments specifying address and port of LDAP server.

    Syntax:

    LDAP::Conn.new(host='localhost', port=LDAP_PORT)  

    Step 1 : Authentication (binding)

    Here we need to specify username and password which we will use for the rest of the session.

    Syntax:

      
      
      1. conn.bind(dn=nil, password=nil, method=LDAP::LDAP_AUTH_SIMPLE)do  
      2. ....  
      3. end

      Now we can perform different operations like search, modify or delete inside block of bind method with proper permissions.


      Adding a new LDAP entry

      The following method adds a new entry to remote LDAP server.

      add(args) => object  

      Step 1: Creating LDAP::Mod object

      The LDAP::Mod object need to be passed to conn.add method to create an entry.

      Syntax:

      Mod.new(mod_type, attr, vals)  
      
      

      mod_type : You can add one or more option here like LDAP_MOD_ADD, LDAP_MOD_DELETE, LDAP_MOD_REPLACE.

      attr : It is the name of the attribute.

      vals : It is an array of values.

      Step 2: Calling conn.add Method

      After creating LDAP::Mod object, we need to call conn.add method

      Syntax:

      conn.add(dn, attrs)  

      Example:

      #/usr/bin/ruby -w   
      
        
      
      require 'rubygems'   
      
      require 'net/ldap'   
      
        
      
      $HOST =    'localhost'   
      
      $PORT =    LDAP::LDAP_PORT   
      
      $SSLPORT = LDAP::LDAPS_PORT   
      
        
      
      conn = LDAP::Conn.new($HOST, $PORT)   
      
      conn.bind('cn=root, dc=localhost, dc=localdomain','secret')   
      
        
      
      conn.perror("bind")   
      
      entry1 = [   
      
        LDAP.mod(LDAP::LDAP_MOD_REPLACE, 'sn', ['Steele']),   
      
      ]   
      
        
      
      begin   
      
        conn.modify("cn=Anna williams, dc=localhost, dc=localdomain", entry1)   
      
      rescue LDAP::ResultError   
      
        conn.perror("modify")   
      
        exit   
      
      end   
      
      conn.perror("modify")   
      
      conn.unbind

      The above example will modify the surname in the previous example.


      Deleting an LDAP entry

      The delete method will delete an entry.

      Syntax:

      conn.delete(dn)  
      #/usr/bin/ruby -w   
      
        
      
      require 'rubygems'   
      
      require 'net/ldap'   
      
        
      
      $HOST =   'localhost'   
      
      $PORT =   LDAP::LDAP_PORT   
      
      $SSLPORT = LDAP::LDAPS_PORT   
      
        
      
      conn = LDAP::Conn.new($HOST, $PORT)   
      
      conn.bind('cn=root, dc=localhost, dc=localdomain','secret')   
      
        
      
      conn.perror("bind")   
      
      begin   
      
        conn.delete("cn=Anna Steele, dc=localhost, dc=localdomain")   
      
      rescue LDAP::ResultError   
      
        conn.perror("delete")   
      
        exit   
      
      end   
      
      conn.perror("delete")   
      
      conn.unbind

      Search in LDAP

      There are three different modes to perform search with search method.

      • LDAP_SCORE_BASEM : It will search only the base mode.
      • LDAP_SCOPE_ONLEVEL : It will search all children of the base mode.
      • LDAP_SCOPE_SUBTREE : It will search whole subtree including the base node.

      Example:

      #/usr/bin/ruby -w   
      
        
      
      require 'rubygems'   
      
      require 'net/ldap'   
      
        
      
      $HOST =    'localhost'   
      
      $PORT =    LDAP::LDAP_PORT   
      
      $SSLPORT = LDAP::LDAPS_PORT   
      
        
      
      base = 'dc=localhost,dc=localdomain'   
      
      scope = LDAP::LDAP_SCOPE_SUBTREE   
      
      filter = '(objectclass=java)'   
      
      attrs = ['sn', 'cn']   
      
        
      
      conn = LDAP::Conn.new($HOST, $PORT)   
      
      conn.bind('cn=root, dc=localhost, dc=localdomain','secret')   
      
        
      
      conn.perror("bind")   
      
      begin   
      
        conn.search(base, scope, filter, attrs) { |entry|   
      
           # print distinguished name   
      
           p entry.dn   
      
           # print all attribute names   
      
           p entry.attrs   
      
           # print values of attribute 'sn'   
      
           p entry.vals('sn')   
      
           # print entry as Hash   
      
           p entry.to_hash   
      
        }   
      
      rescue LDAP::ResultError   
      
        conn.perror("search")   
      
        exit   
      
      end   
      
      conn.perror("search")   
      
      conn.unbind

      In this example, we will search the whole subtree of entry.

      In the last parameter of search, you can specify any attributes. If nil is passed, all attributes are returned same as “SELECT∗” in relational database.

    1. Ruby Thread

      Thread means lightweight sub-process. It is a separate path of execution. In Ruby, different parts of a program can run at the same time by either splitting tasks within a program using multiple threading or splitting tasks between different programs using multiple process.

      Threads are the Ruby implementation for a concurrent programming model.


      Ruby Multithreading

      A normal program has single thread of execution. All the statements in the program are executed sequentially.

      A multi thread program has more than one thread of execution in it. It uses less memory space and share same address space. Multithreading is used to perform more than one task at once.

      A new thread is created using thread.new call. It is different from the main thread’s execution.


      Thread Initialization

      To create a new thread Ruby provides three keywords namely, ::new, ::start and ::fork.

      To start a new thread, associate a block of code with a call to Thread.new, Thread.start or Thread.fork. Thread will be created. The new thread exits when the block exit.

      Syntax:

      # Original thread runs  
      
      Thread.new {  
      
        # New thread is created.  
      
      }  
      
      # Original thread runs

      Thread Termination

      There are different ways to terminate a thread in Ruby. To exit a given thread, class ::kill is used.

      Syntax:

      
      
      1. thr = Thread.new { ... }  
      2. Thread.kill(thr)  

      Ruby Thread Example

      #!/usr/bin/ruby   
      
      th = Thread.new do #Here we start a new thread   
      
        Thread.current['counter']=0   
      
        5.times do |i| #loop starts and increases i each time   
      
          Thread.current['counter']=i   
      
          sleep 1   
      
        end   
      
        return nil   
      
      end   
      
      while th['counter'].to_i < 4  do   
      
      =begin   
      
      th is the long running thread   
      
      and we can access the same variable   
      
      from inside the thread here   
      
      =end   
      
        puts "Counter is #{th['counter']}"   
      
        sleep 0.5   
      
      end   
      
      puts "Long running process finished!"

      Output:

      Ruby Thread 1

      Thread Lifecycle

      Once a thread is created, there is no need to start it. It automatically runs when it gets proper CPU resources. The last expression in a block is the value of the thread. If thread has run completely, value method returns the thread value, otherwise value method blocks it and returns when the thread has completed. A number of methods are defined by thread class while running query and manipulate the thread.

      By calling a thread’s Thread.join method, you can wait for a particular thread to finish.


      Thread Exception Handling

      Threads may have some exceptions in them. If exception arises in any thread other than main thread, it depends upon abort_on_exception. By default this option is always false. It means unhandled exception will silently terminate the thread. This can be changed by setting either abort_on_exception = true or $DEBUG to true.

      To handle exception, you can use class method ::handle_interrupt. It will handle exceptions asynchronously with threads.


      Thread Variables and Scope

      Threads are created with blocks. A local variable created within a block is accessible to only thread in which this block is present.

      Ruby thread class allows thread-local variables to be created and accessed by name. Thread object is treated like a hash, writing elements using []= and reading them back using [].


      Thread Scheduling

      Ruby supports scheduling threads by using ::stop and ::pass methods in a program.

      The ::stop class method put the current running thread to sleep and schedule the execution of another thread. Once the thread is asleep, instance method wakeup is used to mark thread as eligible for scheduling.

      The ::pass class method tries to pass execution to another thread. It depends upon the operating system whether the running thread will switch or not.

      Thread priority gives a hint to schedule threads according to their priority. The high priority thread is scheduled first. It also depends upon the operating system. A thread can increase or decrease its own priority as the first action it takes.


      Thread Exclusion

      Ruby thread exclusion states that, when two threads share the same data and one of the thread modifies that data, then we need to ensure that no thread should see each others data in an inconsistent state. For example, banking server. Where one thread operates money transfer in accounts and other thread is generating monthly report for the customers.


      Public Class Methods

      MethodDescription
      abort_on_exceptionIt returns the status of global “abort on exception” condition. The default is true. When it is set to true, all threads will abort if an exception is raised in any thread.
      abort_on_exception=When it is set to true, all threads will abort if an exception is raised. It returns the new state.
      currentIt returns the currently executing thread.
      exclusive{block}It wraps the block in a single, returning the value of the block.
      exitIt terminates the currently running thread and schedules another thread tro run.
      kill(thread)It causes the given thread to exit.
      fork([args]*){|args| block}It is basically same as ::new method.
      handle_interrupt(hash){…}Changes asynchronous interrupt timing.
      listReturns an array of thread objects for all threads that are either runnable or stopped.
      mainReturns the main thread.
      new{…}/ new(*args, &proc)/ new(*args){|args|…}It creates a new thread executing the given block.
      passIt gives the thread scheduler a hint to pass execution to another thread. A running thread may or may not switch depending upon the OS.
      pending_interrupt?(error = nil)It returns whether or not the asynchronous queue is empty.
      start([args]*){|args|block}It is basically same as ::new method.
      stopIt stops execution of the current thread, putting it into ‘sleep’ state and schedules execution of another thread.

      Public Instance Methods

      MethodDescription
      thr[sym]It returns the value of a fiber-local variable using either a string or symbol name.
      thr[sym]=It creates the value of a fiber-local variable using either a string or symbol name.
      abort_on_exceptionIt returns status of “abort on exception” for thr.
      abort_on_exception=When set to true, all threads will abort if an exception is raised in this thr.
      add_trace_func(proc)Adds proc as a handler for tracing.
      alive?It returns true if thr is running or sleeping.
      backtraceIt returns current backtrace of target ahead.
      backtrace_locations(*args)It returns the execution stack for the target ahead.
      exit/kill/terminateIt terminates thr and executes another thread to run.
      groupIt returns the ThreadGroup which contains the given thread or returns nil.
      inspectIt dumps the name, id and status of thr to a string.
      joinThe calling thread will suspend execution and run this thr.
      key?(sym)It returns true if the given string exists as a fiber-local variable.
      keysIt returns an array of the name of the fiber-local variables.
      pending_interrupt?(error=nil)Returns whether or not the asynchronous queue is empty for the target thread.
      priorityIt returns the priority of thr.
      priority=It sets the priority of thr to integer.
      killIt works same as exit.
      raiseIt raises an exception from the given thread.
      runIt wakes up thr, making it eligible for scheduling.
      safe_levelIt returns the safe level in effect for thr.
      set_trace_func(proc)It establishes proc on thr as the handler.
      statusIt returns the status of thr.
      stop?It returns true if thr is sleeping or dead.
      terminateIt terminates thr and schedules another thread to run.
      thread_variable?(key)It returns true if the given string exists as a thread local variable.
      thread_variable_get(key)It returns the value of a thread local variable that has been set.
      thread_variable_set(key, value)Set a thread local with key to value.
      thread_variableIt returns an array of the thread-local variables.
      valueIt waits for thr to complete, using join and returns its value.
      wakeupMakes a given thread eligible for scheduling, although it may still remained block on I/O.