Ayo Softech

PHP

  1. Joomla
  2. Wordpress
  3. zen-cart
  4. Mojento
  5. OpenCart 

 Create user login in PHP

example:1

Create members pages on your website within minutes with Member Login script.
PHP is a good alternative when you decide to add a password protected web pages on your web site. You can also use htaccess password protection but with PHP you can create a lot more complex and configurable protection. In this example I will use SESSION variables for login verification.
Lets start with building a configuration file for setting up all the username/password combinations. Create a new passwords.php file and add the following code in it.
<?php 
$USERS["username1"] = "password1"; 
$USERS["username2"] = "password2"; 
$USERS["username3"] = "password3"; 
 
function check_logged(){ 
     global $_SESSION, $USERS; 
     if (!array_key_exists($_SESSION["logged"],$USERS)) { 
          header("Location: login.php"); 
     }; 
}; 
?>
Above code creates an $USER array with 3 username/password combinations. We also did a function which will be used later to check if an user is logged in or not. What we need now is a login page (called login.php) where users will enter their username and password and will login.
<?php 
session_start(); 
include("passwords.php"); 
if ($_POST["ac"]=="log") { /// do after login form is submitted  
     if ($USERS[$_POST["username"]]==$_POST["password"]) { 
  username and password exist in $USERS array  
          $_SESSION["logged"]=$_POST["username"]; 
     } else { 
          echo 'Incorrect username/password. Please, try again.'; 
     }; 
}; 
if (array_key_exists($_SESSION["logged"],$USERS)) {check if user is logged or 
     echo "You are logged in."; //// if user is logged show a message  
} else { 
echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';       
     echo 'Username: <input type="text" name="username" /><br />'; 
     echo 'Password: <input type="password" name="password" /><br />'; 
     echo '<input type="submit" value="Login" />'; 
     echo '</form>'; 
}; 
?>
In order to use the user login feature for your PHP files you need to put that code at the very top of each of your PHP files that need to be protected.
<?php 
session_start(); /// initialize session 
include("passwords.php"); 
check_logged(); /// function checks if visitor is logged. 
If user is not logged the user is redirected to login.php page  
?> 
 
your page code goes here

 

Example:2

Create table "members"
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
--
-- Dumping data for table `members`
--
INSERT INTO `members` VALUES (1, 'john', '1234');


Create file main_login.php
View In Browser

############### Code
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

Create file checklogin.php

############### Code
<?php
$host="localhost";
// Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");

header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

Create file login_success.php
############### Code
// Check if session is not registered , redirect back to main page.
// Put this code in first line of web page.
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>

<html>
<body>
Login Successful
</body>
</html>

Logout.php
If you want to logout, create this file

// Put this code in first line of web page.
<?
session_start();
session_destroy();
?>



For PHP5 User - checklogin.php
############### Code
<?php
ob_start();
$host="localhost";
// Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");

header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}

ob_end_flush();
?>




Encrypting Password - Make your Login More Secure

What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a server-side scripting language, like ASP
  • PHP scripts are executed on the server
  • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
  • PHP is an open source software
  • PHP is free to download and use
  • PHP files can contain text, HTML tags and scripts
  • PHP files are returned to the browser as plain HTML 
  • PHP files have a file extension of ".php", ".php3", or ".phtml".
  • PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)
  • PHP runs on different platforms (Windows, Linux, Unix, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP is FREE to download from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side.
  1. Basic PHP Syntax

    <html>
    <body>
    <?php
    echo "Hello World";
    ?>

    </body>
    </html> 
  2. Variables in PHP

    <?php
    $txt="Hello World!";
    $x=16;
  3. $txt="Hello World";//string variable
    echo $txt;
    ?> 
  4. <?php//concatenation operator
    $txt1="Hello World!";
    $txt2="What a nice day!";
    echo $txt1 . " " . $txt2;
    ?>
    The output of the code above will be:
    Hello World! What a nice day! 
     echo strlen("Hello world!");12
    echo strpos("Hello world!","world");6  


    <?php//IF CONDITION
    $d=date("D");
    if ($d=="Fri") echo "Have a nice weekend!";
    ?>

    <?php
    $d=date("D");
    if ($d=="Fri")
      echo "Have a nice weekend!";
    else
      echo "Have a nice day!";
    ?>
    <?php
    $d=date("D");
    if ($d=="Fri")
      echo "Have a nice weekend!";
    elseif ($d=="Sun")
      echo "Have a nice Sunday!";
    else
      echo "Have a nice day!";
    ?>
    <?php
    switch ($x)
    {
    case 1:
      echo "Number 1";
      break;
    case 2:
      echo "Number 2";
      break;
    case 3:
      echo "Number 3";
      break;
    default:
      echo "No number between 1 and 3";
    }
    ?>
    <?php//ARRAY
    $cars[0]="Saab";
    $cars[1]="Volvo";
    $cars[2]="BMW";
    $cars[3]="Toyota";
    echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
    ?>  Saab and Volvo are Swedish cars.
    <?php//LOOP
    $i=1;
    while($i<=5)
      {
      echo "The number is " . $i . "<br />";
      $i++;
      }
    ?>
    <?php
    $i=1;
    do
      {
      $i++;
      echo "The number is " . $i . "<br />";
      }
    while ($i<=5);
    ?>
    <?php
    for ($i=1; $i<=5; $i++)
      {
      echo "The number is " . $i . "<br />";
      }
    ?>
    <?php
    $x=array("one","two","three");
    foreach ($x as $value)
      {
      echo $value . "<br />";
      }
    ?>
    <?php//FUNCTION
    function writeName()
    {
    echo "Kai Jim Refsnes";
    }

    echo "My name is ";
    writeName();
    ?>

    <?php
    function writeName($fname,$punctuation)
    {
    echo $fname . " Refsnes" . $punctuation . "<br />";
    }

    echo "My name is ";
    writeName("Kai Jim",".");
    echo "My sister's name is ";
    writeName("Hege","!");
    echo "My brother's name is ";
    writeName("Ståle","?");
    ?>
    <?php
    function add($x,$y)
    {
    $total=$x+$y;
    return $total;
    }
    echo "1 + 16 = " . add(1,16);
    ?>1 + 16 = 17 
    <html>$_POST VARIABLE
    <body>
    <form action="welcome.php" method="post">
    Name: <input type="text" name="fname" />
    Age: <input type="text" name="age" />
    <input type="submit" />
    </form>
    </body>
    </html>
    <html>
    <body>
    Welcome <?php echo $_POST["fname"]; ?>!<br />
    You are <?php echo $_POST["age"]; ?> years old.
    </body>
    </html>
    Output could be something like this:
    Welcome John!
    You are 28 years old. 
    <html>//$_GET VARIABLE
    <body>
    <form action="welcome.php" method="get">
    Name: <input type="text" name="fname" />
    Age: <input type="text" name="age" />
    <input type="submit" />
    </form> 
    >>http://www.w3schools.com/welcome.php?fname=Peter&age=37 
    >>Welcome <?php echo $_GET["fname"]; ?>.<br />
    You are <?php echo $_GET["age"]; ?> years old!
    >>The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
    Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
    You are <?php echo $_REQUEST["age"]; ?> years old. 

    <?php//DATE
    echo date("Y/m/d") . "<br />";
    echo date("Y.m.d") . "<br />";
    echo date("Y-m-d");
    ?> 
    <?php
    $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
    echo "Tomorrow is ".date("Y/m/d", $tomorrow);
    ?>Tomorrow is 2009/05/12


    <?php include("header.php"); ?>//SERVER SIDE INCLUDE()==REQUIRED()Diff in error
    <h1>Welcome to my home page!</h1>
    <p>Some text.</p>

    <?php//FILE HANDLING
    $file=fopen("welcome.txt","r");
    ?>
    <?php
    $file = fopen("welcome.txt", "r") or exit("Unable to open file!");
    //Output a line of the file until the end is reached
    while(!feof($file))
      {
      echo fgets($file). "<br />";
      }
    fclose($file);
    ?> 
    >>
    r Read only. Starts at the beginning of the file
    r+ Read/Write. Starts at the beginning of the file
    w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
    w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
    a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
    a+ Read/Append. Preserves file content by writing to the end of the file
    x Write only. Creates a new file. Returns FALSE and an error if file already exists
    x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
    fclose($file);//FILE CLOSE
    if (feof($file)) echo "End of file"; // Check ENDOFFILE

    <html>FILE UPLOAD
    <body>

    <form action="upload_file.php" method="post"
    enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    </body>
    </html>
    >>CREATE
    <?php
    if ($_FILES["file"]["error"] > 0)
      {
      echo "Error: " . $_FILES["file"]["error"] . "<br />";
      }
    else
      {
      echo "Upload: " . $_FILES["file"]["name"] . "<br />";
      echo "Type: " . $_FILES["file"]["type"] . "<br />";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
      echo "Stored in: " . $_FILES["file"]["tmp_name"];
      }
    ?>
    >> RESTRICTION
    <?php
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 20000))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file"]["tmp_name"];
        }
      }
    else
      {
      echo "Invalid file";
      }
    ?>
    >>SAVING
    <?php
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 20000))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("upload/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
          }
        }
      }
    else
      {
      echo "Invalid file";
      }
    ?>

     <?php//CREATE COOCIE
    setcookie("user", "Alex Porter", time()+3600);
    ?>
    >>RETRIVED COOCIE
    <?php
    if (isset($_COOKIE["user"]))
      echo "Welcome " . $_COOKIE["user"] . "!<br />";
    else
      echo "Welcome guest!<br />";
    ?>
    >>DELETE COOCIE
    <?php
    // set the expiration date to one hour ago
    setcookie("user", "", time()-3600);
    ?>

    <?php//SESSION storing a $_Session Var
    session_start();
    // store session data
    $_SESSION['views']=1;
    ?>
    <html>
    <body>
    <?php
    //retrieve session data
    echo "Pageviews=". $_SESSION['views'];
    ?>
    </body>
    </html>
    Output:
    Pageviews=1

    <?php//Destroying session
    session_destroy();
    ?>

    PHP Mail Form

    <html>
    <body>
    <?php
    if (isset($_REQUEST['email']))
    //if "email" is filled out, send email
      {
      //send email
      $email = $_REQUEST['email'] ;
      $subject = $_REQUEST['subject'] ;
      $message = $_REQUEST['message'] ;
      mail("someone@example.com", "$subject",
      $message, "From:" . $email);
      echo "Thank you for using our mail form";
      }
    else
    //if "email" is not filled out, display the form
      {
      echo "<form method='post' action='mailform.php'>
      Email: <input name='email' type='text' /><br />
      Subject: <input name='subject' type='text' /><br />
      Message:<br />
      <textarea name='message' rows='15' cols='40'>
      </textarea><br />
      <input type='submit' />
      </form>";
      }
    ?>
    </body>
    </html>
    <?php//PHP Secure E-mail
    if (isset($_REQUEST['email']))
    //if "email" is filled out, send email
      {
      //send email
      $email = $_REQUEST['email'] ;
      $subject = $_REQUEST['subject'] ;
      $message = $_REQUEST['message'] ;
      mail("someone@example.com", "Subject: $subject",
      $message, "From: $email" );
      echo "Thank you for using our mail form";
      }
    else
    //if "email" is not filled out, display the form
      {
      echo "<form method='post' action='mailform.php'>
      Email: <input name='email' type='text' /><br />
      Subject: <input name='subject' type='text' /><br />
      Message:<br />
      <textarea name='message' rows='15' cols='40'>
      </textarea><br />
      <input type='submit' />
      </form>";
      }
    ?>
    <?php//PHP Exception
    //create function with an exception
    function checkNum($number)
      {
      if($number>1)
        {
        throw new Exception("Value must be 1 or below");
        }
      return true;
      }
    //trigger exception
    checkNum(2);
    ?>

    <?php//PHP Filter
    $filters = array
      (
      "name" => array
        (
        "filter"=>FILTER_SANITIZE_STRING
        ),
      "age" => array
        (
        "filter"=>FILTER_VALIDATE_INT,
        "options"=>array
          (
          "min_range"=>1,
          "max_range"=>120
          )
        ),
      "email"=> FILTER_VALIDATE_EMAIL,
      );

    $result = filter_input_array(INPUT_GET, $filters);

    if (!$result["age"])
      {
      echo("Age must be a number between 1 and 120.<br />");
      }
    elseif(!$result["email"])
      {
      echo("E-Mail is not valid.<br />");
      }
    else
      {
      echo("User input is valid");
      }
    ?>

    PHP MySQL Connect to a Database

    <?php//create DABABASE CONNECTION
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    // some code

    mysql_close($con);
    ?>

    <?php//CREATE DB
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    if (mysql_query("CREATE DATABASE my_db",$con))
      {
      echo "Database created";
      }
    else
      {
      echo "Error creating database: " . mysql_error();
      }

    mysql_close($con);
    ?>

    $sql = "CREATE TABLE Persons //CREATE TABLE
    (
    personID int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(personID),
    FirstName varchar(15),
    LastName varchar(15),
    Age int
    )";
    mysql_query($sql,$con);

    Insert Data From a Form Into a Database


    <html>
    <body>
    <form action="insert.php" method="post">
    Firstname: <input type="text" name="firstname" />
    Lastname: <input type="text" name="lastname" />
    Age: <input type="text" name="age" />
    <input type="submit" />
    </form>
    </body>
    </html> 
    >>PHP file
    <?php
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("my_db", $con);
    $sql="INSERT INTO Persons (FirstName, LastName, Age)
    VALUES
    ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";
    mysql_close($con)
    ?>

    <?php//RETRIVED DATA
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("my_db", $con);

    $result = mysql_query("SELECT * FROM Persons
    WHERE FirstName='Peter'");//MySQL Where

    $result = mysql_query("SELECT * FROM Persons ORDER BY age");//MySQL Order By

    mysql_query("UPDATE Persons SET Age = '36'
    WHERE FirstName = 'Peter' AND LastName = 'Griffin'");//MySQL Update

    mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");//MySQL Delete
    mysql_close($con);
    while($row = mysql_fetch_array($result))
      {
      echo $row['FirstName'];
      echo " " . $row['LastName'];
      echo " " . $row['Age'];
      echo "<br />";
      }
    mysql_close($con);
    $result = mysql_query("SELECT * FROM Persons");
    echo "<table border='1'>
    <
    tr>
    <th>Firstname</th>
    <th>Lastname</th>
    </tr>";
    while($row = mysql_fetch_array($result))
      {
      echo "<tr>";
      echo "<td>" . $row['FirstName'] . "</td>";
      echo "<td>" . $row['LastName'] . "</td>";
      echo "</tr>";
      }
    echo "</table>";
    mysql_close($con);
    ?> 

    Create an ODBC Connection

    With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available.
    Here is how to create an ODBC connection to a MS Access Database:
    1. Open the Administrative Tools icon in your Control Panel.
    2. Double-click on the Data Sources (ODBC) icon inside.
    3. Choose the System DSN tab.
    4. Click on Add in the System DSN tab.
    5. Select the Microsoft Access Driver. Click Finish.
    6. In the next screen, click Select to locate the database.
    7. Give the database a Data Source Name (DSN).
    8. Click OK.


    An ODBC Example

    <html>
    <body>
    <?php
    $conn=odbc_connect('northwind','','');
    if (!$conn)
      {exit("Connection Failed: " . $conn);}
    $sql="SELECT * FROM customers";
    $rs=odbc_exec($conn,$sql);
    if (!$rs)
      {exit("Error in SQL");}
    echo "<table><tr>";
    echo "<th>Companyname</th>";
    echo "<th>Contactname</th></tr>";
    while (odbc_fetch_row($rs))
      {
      $compname=odbc_result($rs,"CompanyName");
      $conname=odbc_result($rs,"ContactName");
      echo "<tr><td>$compname</td>";
      echo "<td>$conname</td></tr>";
      }
    odbc_close($conn);
    echo "</table>";
    ?>
    </body>
    </html>

    What is XML?

    XML is used to describe data and to focus on what data is. An XML file describes the structure of the data.
    In XML, no tags are predefined. You must define your own tags.
    If you want to learn more about XML

    An XML File

    The XML file below will be used in our example:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    </note>

    Example

    <?php
    //Initialize the XML parser
    $parser=xml_parser_create();

    //Function to use at the start of an element
    function start($parser,$element_name,$element_attrs)
      {
      switch($element_name)
        {
        case "NOTE":
        echo "-- Note --<br />";
        break;
        case "TO":
        echo "To: ";
        break;
        case "FROM":
        echo "From: ";
        break;
        case "HEADING":
        echo "Heading: ";
        break;
        case "BODY":
        echo "Message: ";
        }
      }

    //Function to use at the end of an element
    function stop($parser,$element_name)
      {
      echo "<br />";
      }

    //Function to use when finding character data
    function char($parser,$data)
      {
      echo $data;
      }

    //Specify element handler
    xml_set_element_handler($parser,"start","stop");

    //Specify data handler
    xml_set_character_data_handler($parser,"char");

    //Open XML file
    $fp=fopen("test.xml","r");

    //Read data
    while ($data=fread($fp,4096))
      {
      xml_parse($parser,$data,feof($fp)) or
      die (sprintf("XML Error: %s at line %d",
      xml_error_string(xml_get_error_code($parser)),
      xml_get_current_line_number($parser)));
      }

    //Free the XML parser
    xml_parser_free($parser);
    ?>
    The output of the code above will be:
    -- Note --
    To: Tove
    From: Jani
    Heading: Reminder
    Message: Don't forget me this weekend!

    How it works:
    1. Initialize the XML parser with the xml_parser_create() function
    2. Create functions to use with the different event handlers
    3. Add the xml_set_element_handler() function to specify which function will be executed when the parser encounters the opening and closing tags
    4. Add the xml_set_character_data_handler() function to specify which function will execute when the parser encounters character data
    5. Parse the file "test.xml" with the xml_parse() function
    6. In case of an error, add  xml_error_string() function to convert an XML error to a textual description
    7. Call the xml_parser_free() function to release the memory allocated with the xml_parser_create() function

    What is SimpleXML?

    SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout.
    Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.

    Using SimpleXML

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    </note>
    We want to output the element names and data from the XML file above.
    Here's what to do:
    1. Load the XML file
    2. Get the name of the first element
    3. Create a loop that will trigger on each child node, using the children() function
    4. Output the element name and data for each child node
    Example
    <?php
    $xml = simplexml_load_file("test.xml");

    echo $xml->getName() . "<br />";

    foreach($xml->children() as $child)
      {
      echo $child->getName() . ": " . $child . "<br />";
      }
    ?>
    The output of the code above will be:
    note
    to: Tove
    from: Jani
    heading: Reminder
    body: Don't forget me this weekend!

    What is AJAX?

    AJAX = Asynchronous JavaScript and XML.
    AJAX is about updating parts of a web page, without reloading the whole page.
    AJAX is a technique for creating fast and dynamic web pages.
    AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
    Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
    Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

    How AJAX Works

    AJAX

    AJAX is Based on Internet Standards

    AJAX is based on internet standards, and uses a combination of:
    • XMLHttpRequest object (to exchange data asynchronously with a server)
    • JavaScript/DOM (to display/interact with the information)
    • CSS (to style the data)
    • XML (often used as the format for transferring data)
    lamp  AJAX applications are browser- and platform-independent!

























1 comment: