Thursday, December 25, 2014

PHP predefined variables

There is large number of predefined variables in PHP to any script which it runs. PHP also provides extra sets of predefined arrays containing variables. These new arrays are called superglobals.

PHP Superglobals:


Variable
Declaration
$GLOBALS
They contains the reference of every variables which can be currently available with the scope of script.
$_SERVER
In this array the contents of information like headers, paths, and script locations are created by the web server.
$_GET
An associative array of variables passed to the current script via URL parameters.
$_POST
An associative array of variables passed to the current script via URL parameters.
$_FILES
An associative array of items uploaded to the current script via the HTTP POST method.
$_REQUEST
An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.

$_COOKIE
An associative array of variables passed to the current script via HTTP cookies.
$_SESSION
An associative array containing session variables available to the current script.
$_PHP_SELF
A string containing PHP script file name in which it is called.
$php_errormsg
$php_errormsg is a variable containing the text of the last error message generated by PHP.

PHP $GLOBALS Example:

PHP Script (global.php)

 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8"/>  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <?php  
 $val1 = 100;  
 $val2 = 50;  
 function subtraction() {  
   $GLOBALS['sub'] = $GLOBALS['val1'] - $GLOBALS['val2'];  
 }  
 subtraction();  
 echo "Subtraction of 2 numbers= ".$sub;  
 ?>  
 </body>  
 </html> 


PHP $_SERVER Variables:

 $_SERVER is an array containing the information of the page or site such as header, paths, and scripts location. All entries in this array is created by web server.

Variable
Description
$_SERVER['PHP_SELF']
The filename of the currently executing script, relative to the document root
$_SERVER['argv']
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
$_SERVER['argc']
Contains the number of command line parameters passed to the script if run on the command line.
$_SERVER['GATEWAY_INTERFACE']
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
$_SERVER['SERVER_ADDR']
The IP address of the server under which the current script is executing.
$_SERVER['SERVER_NAME']
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
$_SERVER['SERVER_SOFTWARE']
Server identification string, given in the headers when responding to requests.
$_SERVER['SERVER_PROTOCOL']
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
$_SERVER['REQUEST_METHOD']
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
$_SERVER['REQUEST_TIME']
The timestamp of the start of the request. Available since PHP 5.1.0.
$_SERVER['QUERY_STRING']
The query string, if any, via which the page was accessed.
$_SERVER['DOCUMENT_ROOT']
The document root directory under which the current script is executing, as defined in the server's configuration file.
$_SERVER['HTTP_ACCEPT']
Contents of the Accept: header from the current request, if there is one.
$_SERVER['HTTP_ACCEPT_CHARSET']
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
$_SERVER['HTTP_ACCEPT_ENCODING']
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
$_SERVER['HTTP_ACCEPT_LANGUAGE']
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
$_SERVER['HTTP_CONNECTION']
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
$_SERVER['HTTP_HOST']
Contents of the Host: header from the current request, if there is one.
$_SERVER['HTTP_REFERER']
The address of the page (if any) which referred the user agent to the current page.
$_SERVER['HTTP_USER_AGENT']
This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).
$_SERVER['HTTPS']
Set to a non-empty value if the script was queried through the HTTPS protocol.
$_SERVER['REMOTE_ADDR']
The IP address from which the user is viewing the current page.
$_SERVER['REMOTE_HOST']
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.
$_SERVER['REMOTE_PORT']
The port being used on the user's machine to communicate with the web server.
$_SERVER['SCRIPT_FILENAME']
The absolute pathname of the currently executing script.
$_SERVER['SERVER_ADMIN']
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file.
$_SERVER['SERVER_PORT']
The port on the server machine being used by the web server for communication. For default setups, this will be '80'.
$_SERVER['SERVER_SIGNATURE']
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
$_SERVER['PATH_TRANSLATED']
Filesystem based path to the current script.
$_SERVER['SCRIPT_NAME']
Contains the current script's path. This is useful for pages which need to point to themselves.
$_SERVER['REQUEST_URI']
The URI which was given in order to access this page; for instance, '/index.html'.
$_SERVER['PHP_AUTH_DIGEST']
When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client.
$_SERVER['PHP_AUTH_USER']
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
$_SERVER['PHP_AUTH_PW']
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
$_SERVER['AUTH_TYPE']
When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.
Example: 

PHP Script (server.php)

 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8"/>  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <?php  
 echo "PHP_SELF: ".$_SERVER['PHP_SELF'];  
 echo "<br>";  
 echo "GATEWAY_INTERFACE: ".$_SERVER['GATEWAY_INTERFACE'];  
 echo "<br>";  
 echo "SERVER_ADDR: ".$_SERVER['SERVER_ADDR'];  
 echo "<br>";  
 echo "SERVER_NAME: ".$_SERVER['SERVER_NAME'];  
 echo "<br>";  
 echo "SERVER_SOFTWARE: ".$_SERVER['SERVER_SOFTWARE'];  
 echo "<br>";  
 echo "SERVER_PROTOCOL: ".$_SERVER['SERVER_PROTOCOL'];  
 echo "<br>";  
 echo "REQUEST_METHOD: ".$_SERVER['REQUEST_METHOD'];  
 echo "<br>";  
 echo "REQUEST_TIME: ".$_SERVER['REQUEST_TIME'];  
 echo "<br>";  
 echo "QUERY_STRING: ".$_SERVER['QUERY_STRING'];  
 echo "<br>";  
 echo "HTTP_ACCEPT: ".$_SERVER['HTTP_ACCEPT'];  
 echo "<br>";  
 echo "HTTP_HOST: ".$_SERVER['HTTP_HOST'];  
 echo "<br>";  
 echo "SCRIPT_FILENAME: ".$_SERVER['SCRIPT_FILENAME'];  
 echo "<br>";  
 ?>  
 </body>  
 </html>  

PHP $_POST:

Example:

PHP Script (post.php)

 <?php  
 if(isset($_POST['name']) and isset($_POST['food']))  
 {  
   if(!empty($_POST['name'])){  
     echo "Welcome ". $_POST['name']. ",<br />";  
     echo "Do you have ". $_POST['food'].".";  
   }else{  
     echo "Name can't be blank!";  
   }  
 }else  
 {  
   echo "Please write name and food Name.";  
 }  
 ?>  
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8"/>  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <form action ="<?phpecho $_SERVER['PHP_SELF']; ?>" method = "POST">  
   Name:<input type = "text" name ="name" />  
   Food Name:<input type = "text" name = "food"/>  
 <input type ="submit" value = "Submit!" />  
 </form>  
 </body>  
 </html>  

PHP $_GET:

Example:

PHP Script (get.php)

 <?php  
 if(isset($_GET['name']) || isset($_GET['website']))  
 {  
   echo "Welcome ". $_GET['name']. ",<br />";  
   echo "I am from ". $_GET['place'].".";  
 }else  
 {  
   echo "Please write name and place.";  
 }  
 ?>  
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8"/>  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <form action ="<?phpecho $_SERVER['PHP_SELF'];?>" method = "GET">  
   Name:<input type = "text" name ="name" />  
   Place:<input type = "text" name = "place"/>  
 <input type ="submit" value = "Submit!" />  
 </form>  
 </body>  
 </html>  

GET and POST in PHP

GET and POST  are the basic way how a browser sends information to the web server while working with PHP.

The Get Method:
It is used to send encoded user information appended to the page request. On using GET method  the page and the encoded information are separated by the "?" character. This method has restriction to send only up to 1024 characters. This method isn't used if you are processing sensitive information for sending it to the server. $_GET associative array is used by PHP to  access all the sent information.


Example:

PHP Script (get.php)

 <?php  
 if(isset($_GET['name']) || isset($_GET['website']))  
  {  
    echo "Welcome ". $_GET['name']. ",<br />";  
    echo "I am from ". $_GET['website'].".";  
  }else  
  {  
   echo "Please write name and website.";  
  }  
 ?>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <form action ="<?php $_PHP_SELF; ?>" method = "GET">  
 Name:<input type = "text" name ="name" />  
 Website:<input type = "text" name = "website"/>  
 <input type ="submit" value = "Submit!" />  
 </form>  
 </body>  
 </html> 

The POST Method:

This method transfers information via HTTP headers. POST information is encoded as like same as in GET method and put into a header called QUERY_STRING. This method do not have any restriction in data size. Any kind of data can be sent using this method. Information sent using this method is more secure but it also depends on used HTTP protocol.

Example:

PHP Script (post.php)
<?php  
 if(isset($_POST['name']) and isset($_POST['website']))  
  {  
   if(!empty($_POST['name'])){  
    echo "Welcome ". $_POST['name']. ",<br />";  
    echo "I am from ". $_POST['website'].".";  
   }else{  
    echo "Name can't be blank!";  
   }  
  }else  
  {  
   echo "Please write name and website Name.";  
  }  
 ?>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <form action ="<?php $_PHP_SELF; ?>" method = "POST">  
 Name:<input type = "text" name ="name" />  
 Website Name:<input type = "text" name = "website"/>  
 <input type ="submit" value = "Submit!" />  
 </form>  
 </body>  
 </html>  

How to Include files in PHP ?

A PHP file can also be included in other PHP file using file include method. There are two PHP functions which can be used for including one PHP file into another PHP file.
The include() Function /[include_once()]
The require() Function/ [require_once()]

Note:Including file has two functions include() and require() ,however include_once and require_once are also practiced as per requirements.

Syntax:
 include 'filename.php';  
 include_once'filename.php';  
 require'filename.php';  
 require_once'filename.php';  

Example:

PHP Script (demo.php)

 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8">  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <?php  
 echo "<h3>It comes from included file</h3>";  
 ?>  
 </body>  
 </html>  


PHP Script (include.php)
 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8">  
 <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <?php  
 include "demo.php";  
 echo "See what is includeed";  
 ?>  
 </body>  
 </html> 




What are PHP Data Types ?


PHP supports several data types, they are listed below :

String: A string is sequence of characters it may be any text inside quotes.

Example:

PHP Script (string.php)
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>Nirajan Ghimirey's Workshop</title>  
 </head>  
 <body>  
 <h3>Example of String</h3>  
 <?php  
 $var1 = "Hello Joe..!!";  
 echo $var1;  
 ?>  
 </body>  
 </html>


Integer: An integer is a whole number which does not have decimals. There are several rules for integers :-

  1. An integer must have at least one digit and this may be from 0 to 9.
  2. An integer should not contain comma or blanks otherwise it won’t be called an integer.
  3. An integer should not have a decimal point.
  4. An integer can be positive or negative.
  5. Integers can be in three formats and they are hexadecimal, decimal and octal. 

Exampe:
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Example of Integer</h3>  
 <?php  
 $var1 = 5;  
 $var2 = 4;  
 echo $var1 + $var2;  
 ?>  
 </body>  
 </html>

Float: A float can be defined as a number which has a decimal point or it might also have a number in exponential form.  

Example:
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Example of Float</h3>  
 <?php  
 $var1 = 5.4;  
 $var2 = 4.6;  
 echo $var1 + $var2;  
 ?>  
 </body>  
 </html> 
 Boolean: Two states are represented by Boolean and those possible states are TRUE or FALSE.
$x = true;     
$Y= false;
The use of Booleans is done in conditional testing.

Example:
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Example of Boolean</h3>  
 <?php  
 $var1 = true;  
 $var2 = false;  
 echo "var1 = " . $var1;  
 echo "<br/>";  
 echo "var2 = " . $var2;  
 ?>  
 </body>  
 </html> 

Array: Multiple values are stored in an array and in one single variable.

Example:

PHP Script (array.php)

 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Example of Array</h3>  
 <?php  
 $arr = array("HTML", "CSS", "PHP");  
 foreach ($arr as $value) {  
   echo $value . "<br/>";  
 }  
 ?>  
 </body>  
 </html> 



Object: Object scan only be called a data type if it tends to store data and information which describes how to process that data.Object is explicitly declared in PHP.
 First the class of object must be declared and for doing so the class keyword is used. A class can be defined as a structure which can contain properties and methods.

Example:

 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Example of Object</h3>  
 <?php  
 class Food{  
   function cook() {  
     return "mo-mo";  
   }  
 }  
 /*create an object*/  
 $course = new Food();  
 echo $food->mo-mo();  
 ?>  
 </body>  
 </html> 



Null Value:Null is a special data type that can have only one value: NULL.
A variable of data type NULL has functionality and that is it has no value assigned to it.

Example:
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Example of NULL</h3>  
 <?php  
 $var1 = null;  
 var_dump($var1);  
 ?>  
 </body>  
 </html>

Resource :
Example:
 <?php  
 $conn = mysqli_connect("localhost","root","admin","password");  
 ?> 

Wednesday, December 24, 2014

Restful webservice Application in PHP

Firstly let me be clear about the environment and requirements for the project. The required materials for the project are:

  1. IDE fully supportive for PHP
  2. A local Web Server (WAMP,XAMPP etc.) as per your O/S and easiness. 
  3. Google Chrome web browser with an extinction Advance rest Client.
Now if we have all this things with us we are ready to start. The basic functioning that our "Restfull Web Service " will be registering a user, loging a user along with some other functionalities that shall be brodened later.



Now lets create a database as per our requirement . Create a database "rest". Inside SQL insert the below code :

USE rest;
CREATE TABLE rest (username varchar(15) , password varchar (15), email varchar (50), status varchar (80));


The first thing we need to do is; create a folder "rest"  inside your web server after that lets create a file"DB_Config" that will enable us to connect to our database.

(DB_Config.php)

 <?php  
 /**  
  * Created by PhpStorm.  
  * User: wao  
  * Date: 1/26/2015  
  * Time: 4:28 PM  
  */  
 $mysql_hostname = "localhost"; /* replace it with your host [In most case the host name is same "localhost"] */  
 $mysql_user = "root"; /*It is a default username in your MySQL if you have set manual users please replace "root"*/  
 $mysql_password = "";/*It is a default password in your MySQL if you have set manual password please replace ""*/  
 $mysql_database = "rest"; /* insert your database name here*/  
 $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)  
 or die("Opps some thing went wrong, couldnot connect to the database");  
 mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong, cannot select database");  
 ?> 


After we are done with DB_Config.php file we will now create a next file namely "signup.php" 


 <?php  
 // Include confi.php  
 include_once('DB_Config.php');  
 if($_SERVER['REQUEST_METHOD'] == "POST"){  
  // This code gets data  
  $username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : "";  
  $email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";  
  $password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";  
  $status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";  
  // Below script inserts data into data base  
  $sql = "INSERT INTO `rest`.`users` (`ID`, `username`, `email`, `password`, `status`) VALUES (NULL, '$username', '$email', '$password', '$status');";  
  $qur = mysql_query($sql);  
  if($qur){  
  $json = array("status" => 1, "msg" => "Done User created!");  
  }else{  
  $json = array("status" => 0, "msg" => "Error creating user!");  
  }  
 }else{  
  $json = array("status" => 0, "msg" => "Request method not accepted");  
 }  
 @mysql_close($conn);  
 /* Output header */  
  header('Content-type: application/json');  
  echo json_encode($json);  
  ?>  

After finishing with "signup.php" we wil now create another file "login.php"


 <?PHP  
 include_once('DB_Config.php');  
 if($_SERVER['REQUEST_METHOD'] == "POST"){  
  // Get data  
  $username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : "";  
  $password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";  
  // Insert data into data base  
  $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";  
  $qur = mysql_query($sql);  
  $count=mysql_num_rows($qur);  
  if($count == 1)  
  {  
  $json=array("status"=>1, "msg"=>"user logged in");  
  }else{  
  $json=array("status"=>0, "msg"=>"user not loggedin!either password doesnot match or u have other error");  
  }  
 }else{  
  $json = array("status" => 0, "msg" => "Request method not accepted");  
  }  
 @mysql_close($conn);  
 /* Output header */  
  header('Content-type: application/json');  
  echo json_encode($json);  
  ?> 

     Open Google Chrome and run Advance Rest Client , and please refer to the snapshot for checking your webservice restfull application.


Download Source Code
    
restful web service php

MySQL Database Connection using PDO

 $name = 'root'; # user-supplied data  
 try {  
 $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);  
 #note: mysql:host=localhost(replace it by your hostname) , mysql:dbname:myDatabase (replace it by your database name), insert username and password for database at the end of this line  
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
 $data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));  
 foreach($data as $row) {  
 print_r($row);  
 }  
 } catch(PDOException $e) {  
 echo 'ERROR: ' . $e->getMessage();  
 }  

MySQL database connection script for PHP

This is a very useful piece of script, somehow these days MySQL gives depreciating error  as PDO has replaced it.Though it hasn't been officially deprecated - due to widespread use - in terms of best practice and education, it might as well be. Please search for PDO DB connection script in this blog under Project and Script.


 <?php  
 /**  
  * Created by PhpStorm.  
  * User: wao  
  * Date: 1/26/2015  
  * Time: 4:28 PM  
  */  
 $mysql_hostname = "localhost"; /* replace it with your host [In most case the host name is same "localhost"] */  
 $mysql_user = "root"; /*It is a default username in your MySQL if you have set manual users please replace "root"*/  
 $mysql_password = "";/*It is a default password in your MySQL if you have set manual password please replace ""*/  
 $mysql_database = "blog"; /* insert your database name here*/  
 $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)  
 or die("Opps some thing went wrong, couldnot connect to the database");  
 mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong, cannot select database");  
 ?>  

cURL Login to Facebook

Running this cURL script you can anonymously log into your Facebook account for  some penny amount of time. For more details please comment and give feedback or ask questions .


 <?php  
 $post_data['username'] = '###'; /*insert your facebook username/phone number*/  
 $post_data['password'] = '###'; /* your facebook password*/  
 //traverse array and prepare data for posting (key1=value1)  
 foreach ( $post_data as $key => $value) {  
   $post_items[] = $key . '=' . $value;  
 }  
 //create the final string to be posted using implode()  
 $post_string = implode ('&', $post_items);  
 //create cURL connection  
 $curl_connection = curl_init('https://www.facebook.com/login.php');  
 //set options  
 curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);  
 curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");  
 curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);  
 curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);  
 curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);  
 //set data to be posted  
 curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);  
 //perform our request  
 $result = curl_exec($curl_connection);  
 if (stristr($result, "loginerrors"))  
 {  
   echo "There was an error. You were not logged in!";  
 }else{  
   echo "Succes! You were logged in!";  
 }  
 //close the connection  
 curl_close($curl_connection);  
 ?>

Encoding and Decoding JSON data

JSON is a  kind of data exchanging format ,encoding and decoding  can be done in various web programming languages using JSON like PHP, ASP.NET etc. Here is a basic example on PHP about  encoding and decoding .

Encoding JSON data in PHP :




Example: 

PHP File (encode.php)
 <?PHP  
 header('Content-type: application/json');  
 $json = array('PHP' => 1, 'JSON' => 2, 'HTML' => 3, 'JavaScript' => 4, 'jQuery' => 5);  
 echo json_encode($json);  
 ?>  

PHP File (decode.php)
 <?PHP  
 $json='{"PHP":1,"JSON":2,"HTML":3,"CSS":4,"JavaScript":5,"jQuery":6}';  
 echo "<pre>";  
 var_dump(json_decode($json));  
 var_dump(json_decode($json,true));  
 echo "</pre>";  
 ?> 

File Uploading in PHP

Files can be upload using PHP in an HTML form.Firstly the files are uploaded in initial/ temporary folder and later it is relocated to the target defined by PHP script. There are certain criteria for uploading files in PHP like upload_max_filesize. You can find information in the phpinfo.php about file uploads.

Here the example is divided in two parts please carefully go through it to have a proper formulation.
[NOTE : Please create a folder "upload" in your server directory]


PHP Script (upload.php)

 <?php  
 $name = $_FILES['file']['name'];  
 $tmp_name = $_FILES['file']['tmp_name'];  
 if (isset($name)) {  
   if (!empty($name)) {  
     $location = 'upload/';  
     $target_file = $location . $name;  
     if (!file_exists($target_file)) {  
       if (move_uploaded_file($tmp_name, $location . $name)) {  
         echo('uploaded');  
       }  
     }else{  
       echo 'File already exist.';  
     }  
   } else {  
     echo 'please choose a file';  
   }  
 }  
 ?> 


PHP Script (index.php)

 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>File Upload:</h3>  
 <form action="upload.php" method="POST" enctype="multipart/form-data">  
   Select file to upload: <input type="file" name="file"><br>  
   <input type="submit" value="Submit">  
 </form>  
 </body>  
 </html> 

Tuesday, December 23, 2014

PDO in PHP

PHP Data Object is what PDO stands for, PDO defines a lightweight, consistent interface that is used for accessing database in PHP. No data functions can be performed or brought in use only using PDO but a database specific PDO driver should be used instead to access a database server. PDO is latest and it is only available  after PHP 5.1 version. PDO makes it easier and convenient and provides a data-access abstraction layer this helps using multiple database  with same function query to fetch the data.

Databases supported by PDO :

Driver name
Supported databases
PDO_CUBRID
Cubrid
PDO_DBLIB
FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD
Firebird
PDO_IBM
IBM DB2
PDO_INFORMIX
IBM Informix Dynamic Server
PDO_MYSQL
MySQL 3.x/4.x/5.x
PDO_OCI
Oracle Call Interface
PDO_ODBC
ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL
PostgreSQL
PDO_SQLITE
SQLite 3 and SQLite 2
PDO_SQLSRV
Microsoft SQL Server / SQL Azure
PDO_4D
4D


Below here is a simple example of PDO :

Example:

PHP Code(connection.php)

 <?php  
 $dsn = 'mysql:dbname=ft;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
   if ($db) {  
     echo "Successfully connected to database.";  
   }  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 ?>  
 PHP PDO Insert:  
 PHP Script (insert.php):  
 <?php  
 $dsn = 'mysql:dbname=try;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 //PDO Class  
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);  
 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);  
 //PDO Statement Class  
 $sth = $db->prepare("INSERT INTO test(id, message) VALUES (:id, :mgs)");  
 $data = array(  
   ':id' => 'first',  
   ':msg' => 'this is first message'  
 );  
 echo $sth->execute($data);  
 ?> 
File to get or fetch records ( PHP PDO getting record):

PHP Script (records.php)
 <?php  
 $dsn = 'mysql:dbname=try;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 //PDO Class  
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);  
 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);  
 //PDO Statement Class  
 $sth = $db->query("SELECT * FROM test");  
 print_r($sth->fetch());  
 ?> 

Captcha in PHP

Captcha are viral these days either it be PHP or any other languages. Years before from now,  users were prompted to do simple mathematical equations and then the code checked if the user is a human or a bot but these days it has truly been replaced by captcha system which is more reliable and dynamic. Captcha is used to verify whether the reactor is a human being or it's just another bot. Captcha in PHP does not only facilates us with  visual way for security but also audio based verification. Captcha are used for saving brute force attacks and different other purposes.

Now, for example I have three files (captcha.html,captcha.php and image.php for image generation) the first is HTML file captcha.html


 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
 <meta charset="UTF-8"/>  
 <title>NGWorkshop</title>  
 </head>  
 <body>  
 <h3>Please Login:</h3>  
 <form action="picture.php" method="post">  
 <fieldset>  
 <legend>Login Form</legend>  
     Email: <input type="text" name="name"/><br/><br/>  
     Password: <input type="text" name="password"/><br/><br/>  
     Enter Code: <imgsrc="captcha.php"/><input type="text" name="captcha_code"/><br/><br/>  
 <input type="submit" name="Submit" value="Submit"/>  
 </fieldset>  
 </form>  
 </body>  
 </html> 

The next is captcha.php ,

 <?php  
 session_start();  
 $text = rand(10000,99999);  
 $_SESSION["captcha_code"] = $text;  
 $height = 40;  
 $width = 80;  
 $image_p = imagecreate($width, $height);  
 $black = imagecolorallocate($image_p, 100, 125, 140);  
 $white = imagecolorallocate($image_p, 255, 255, 255);  
 $font_size = 14;  
 imagestring($image_p, $font_size, 5, 5, $text, $white);  
 imagejpeg($image_p, null, 80);  
 ?>

Finally here goes image.php file that generates the image with the help of logic provided in captcha.php

 <?php  
 session_start();  
 if ($_POST["captcha_code"] != $_SESSION["captcha_code"] OR $_SESSION["captcha_code"]=='') {  
   echo '<strong>Incorrect Input!!!!!</strong>';  
 } else {  
   // add form data processing code here  
 echo '<strong>Verification Successful </strong>';  
 };  
 ?>

copy these files with the respective file name and put it into your servers and BOOM ! everything should work fine. If not please let me know leaving a comment ;)

Serialization and its meaning in JSON

Serialization and its meaning in JSON:


Serialization in JSON is similar to parsing; serialization of JSON can be done in almost all modern programming languages like PHP, ASP.NET etc. Serialization procedure of JSON differs to languages used. JSONpickle is a python library for serialization and Deserialization of complex python objects to and from JSON. Similarly ASP.NET, PHP etc. has their own libraries and methods for serialization of data/objects in JSON.
Syntax:
Example:
PHP Script (json.php)
 <?PHP   
  if($_SERVER['REQUEST_METHOD'] == "POST") {   
   // Gets data from form   
   $name = $_POST['username'];   
   $password = $_POST['password'];   
   // checks if condition matches or not   
   if ($name == $password) {   
    $json = array("status" => 200, "msg" => "Sucessfully logged in");   
   } else {   
    $json = array("status" => 400, "msg" => "Username and Password do not match");   
   }   
  }else {   
   $json = array("status" => 404, "msg" => "Request method not accepted");   
  }   
  /* Output header */   
  header('Content-type: application/json');   
  echo json_encode($json);   
  //echo json_last_error() ; this gievs the last error found by json and 0 value count if not found   
  ?> 

HTML Document (serialization.html)
  <!DOCTYPE html>   
  <html lang="en">   
  <head>   
  <meta charset="utf-8"/>   
  <title>Nirajan Ghimirey's Workshop</title>   
  </head>   
  <body>   
  <div align="center">   
  <h2>Please insert the data to see the encoded JSON message</h2>   
  <form method="post" action="json.php">   
  <input type="text" name="username" placeholder="Username"><br/><br/>   
  <input type="password" name="password" placeholder="Password"><br/><br/>   
  <input type="submit" value="Login">   
  </form>   
  </div>   
  </body>   
  </html>


Monday, December 22, 2014

A brief History in PHP

Introduction on PHP
In this rapid world of Information and Technology PHP is one of the most used server-side scripting and programming language, almost 50% of web programmers uses PHP for their server side. This language is easy to learn and yet developed for purpose of web development. Though it also has some general usage. In the year 2013 PHP was found to be installed in more than 240 million websites which is more than 39 percent. Rasmus Lerdorf  Developed this dynamic language in 1994, its latest version was lately released in 18 December 2014 and it’s 5.6.4 version. PHP can be used along with HTML  for various operations in web applications that makes it robust  and popular. All codes coded in PHP are interpreted by PHP interpreter.

History of PHP
In the year 1994 PHP development was started by Rasmus Lerdorf, he started writing a series of CGI (Common Gateway Interface) binaries in the programming language called C. After working it for some time he added the ability to work with web forms feature and he also added the feature to communicate with databases. Several PHP versions have been released till now with different added features. In year 1995 on 8th of June PHP version 1.0 was released, this came out to be the popular version and on 1997 the second version was released and introduced to market , this version contained more features compared to version 1.0. Version 3.0 on 20th October 2000 was released after and so and so today we have version 5.6.4 of PHP. Version 4.1 in 2002 had a feature in it called SuperGlobals , and in the same year version 4.3 introduced command-line interface for the purpose of supplementing the CGI.

Features of PHP that make it so popular and robust language are listed below:

·        HTTP authentication with PHP: It is possible to use the header () function to send an Authentication required.
Cookies: PHP supports HTTP cookies; these are the mechanism for storing data in browser for tracking purpose.

Sessions: PHP supports session to preserve certain data who has frequent access; it enables more customized applications with best security.

Dealing with XForms:  XForms are used in wide variety of platform and browsers or even non-traditional media such as PDF documents, PHP deals with this variation of web forms.

Handling file uploads: PHP handles file uploads in wide range, single, multiple etc. mostly post and put methods are used in file handling.

Using remote files:  You can use HTTP and FTP URLs with most of the functions that tae a filename as a parameter as long as allow_url_fopen is enabled in php.ini.

Connection handling: In PHP always connection status is maintained, there are 4 possible states 0=Normal , 1=Aborted , 2=Timeout , 3= Aborted and Timeout.

Persistent Database Connections: These connections are those links which do not close when the execution of your scripts ends.

Safe Mode: PHP safe mode troubleshoots the shared-server security problem.

Command line uses:  The main focus of Command line uses is to enable developing shell application with PHP.

Garbage Collection: PHP keeps reference count for all variables and destroy them(in most cpnditions) as soon as this reference counts to zero.

DTrace Dynamic Tracing: DTrace can trace operating system behavior and user program execution.