Wednesday, December 24, 2014

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.