Monday 18 March 2013

Uploading file using in php

Welcome to my new post !!!!


In this post we will be seeing how can we upload files from client side to the server folder.
It is very common requirement but prople often find it a atough job..
I will try to explain it as possible as I can simultaneously keeping myself simple and consice.

So lets start with it.


PHP INI SETTINGS 

You need to check certain settings in php.ini file to make your upload successful
use phpinfo() to check the value of these settigs

  • file_uploads               : allow file upload or not
  • upload_max_filesize   : maximum size of file that can be uploaded      
  • memory_limit             : maxiumum memory limit that   can be allocated to script 
  • max_execution_time   : maximum time for which file can be executed
  • post_max_size           :  mamixmum post size

First of all we have to create a form that will be used to get the file from the client.

<html>

<head>

<title>Learn Image Uploading</title>

</head>

<body>

<form method='post' enctype='multipart/form-data' action='uploadFile.php'>

<label for='imgFile'>Choose Image</label>

<input name='imgFile' id='imgFile' type='file'/><br/>

<input type='submit' value='upload'>

</form>

</body>

</html>



Things to note:

The main difference in this form and other forms is  enctype  attribute. This attribute specifies the type of the content that is being submitted .Its default value of this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" is used whenever we are submitting or uploading any kind of file.

If we do not use it it will not populate $_FILES array at server side.
We will be learning about this later on ..

  •   Now create a folder on server which will be saving the images that are uploaded say "uploads"
  •   You will then require a php script  to handle the file uploads .


<?php
#---- ini settings (ini)----
ini_set('display_errors', '1');
#-------------(/ini)--------
$is_file_uploaded  = (!empty($_FILES))?true:false;
if($is_file_uploaded)
{
  $is_error = ($_FILES['imgFile']['error'] == 0)?false:true;
  if( ! $is_error)
   {
      $fileDetails = $_FILES['imgFile'];
      #--------- details of the file being uploaded (/details)----
      echo "File Name: {$fileDetails['name']}: <br/>";
      echo "File Type: {$fileDetails['type']} <br/>";
      echo "File temp name (Name used while uploading) : {$fileDetails['tmp_name']} <br/>";
      echo "File Size : {$fileDetails['size']} <br/>";
      #---------------(/details)------------------------------
     
      #------------ move the uploaded file to server(move uploaded file)---------
      $temp_file         = $fileDetails['tmp_name'];
      $path              = "uploads/{$fileDetails['name']}";
      $move              = move_uploaded_file($temp_file, $path);  // move the file from temp steam to server
      #--------------------------(/move uploaded file)---------------------------
      if($move)
      {
      echo "File successfully Uploaded";
      }
      else
      {
       echo "OOPS!! There is some error";
      }
   }
}
?>

Now open the "uploads" folder and check for the file.
  • make sure the path of folder is correct and you have proper permissions on that folder
The script I have shown above is without any restriction .. Obviously you will not want anyone to upload file of any type with any size ...

So lets add some validation to our uploading script


<?php
#---- ini settings (ini)----
ini_set('display_errors', '1');
#-------------(/ini)--------

$is_file_uploaded  = (!empty($_FILES))?true:false;
if($is_file_uploaded)
{
 $is_error = ($_FILES['imgFile']['error'] == 0)?false:true;
  if( ! $is_error)
   {
      $fileDetails = $_FILES['imgFile'];
      
      #--------- details of the file being uploaded (/details)---- 
      echo "File Name: {$fileDetails['name']} <br/>";
      echo "File Type: {$fileDetails['type']} <br/>";
      echo "File temp name (Name used while uploading) : {$fileDetails['tmp_name']} <br/>";
      echo "File Size : {$fileDetails['size']} <br/>";
      #---------------(/details)------------------------------
      
      
      #----------   resctrictions ----------------------------
      
      // Restrict the file size to be 50 kb
      $is_valid_size  = ($fileDetails['size'] < 51200)?true:false;
      
      // resctrict valid file type to be png,jpg,gif,jpeg
      
      $validFileTypes = array('image/jpeg','image/jpg','image/png','image/gif');
      $is_valid_type  = (in_array($fileDetails['type'], $validFileTypes)==true)?true:false;  
      
      #---------------(/restrictionns)------------------------
      
      #------------ move the uploaded file to server(move uploaded file)---------
      $temp_file         = $fileDetails['tmp_name'];
      $path              = "uploads/{$fileDetails['name']}";
      
      $is_file_existing  = (file_exists($path))?true:false;
      
      if($is_file_existing)
      {
       @unlink($path);
      }
      
      
      // move file only if size and file type is valid
      if($is_valid_type && $is_valid_size)
      {
       $move           = move_uploaded_file($temp_file, $path);  // move the file from temp steam to server
      }
      else
      {
       echo "Please check Your file type('png,jpg,gif,jpeg') and file size(max 50kb)";
      }
      
      #--------------------------(/move uploaded file)---------------------------
      if($move)
      {
       echo "File successfully Uploaded";
      }
      else
      {
       echo "OOPS!! There is some error";
      }
   }
}
?>
Congrats .. You are done .. !!

Parsing XML using simple inbuilt xml functions

Hi Friends .. In this post you will learn how to parse the xml structure using inbuilt php functions . We will be learning about 2 functions
 1.simplexml_load_file
 2.simplexml_load_string

Lets begin with simplexml_load_file.

simplexml_load_file  takes a xml file as mandatory parameter and coverts it into an object.
On success returns the object of  SimpleXmlElement or false on failure.


To try copy the xml below and save it as sample.xml

<message>
<to>user1</to>
<from>user2</from>
<heading>testxml</heading>
<body>I am testing php xml functions</body>
</message>
<?php
// check if file existx or not
$file        = 'sample.xml';
$file_exixts = (file_exists($file));
if($file_exixts)
{
   $xml_contents = simplexml_load_file($file);
}

// check the file contents
echo "<pre>";
print_r($xml_contents);
echo "</pre>";
//accessing the value 


$to = $xml_contents->to;
echo "This message was sent to $to";

?>



simplexml_load_string  takes a xml string as mandatory parameter and coverts it into an object.
On success it also returns the object of  SimpleXmlElement or false on failure.


<?php

$xml_string = "<message>
              <to>user1</to>
              <from>user2</from>
              <heading>testxml</heading>
              <body>I am testing php xml functions</body>
              </message>";



$xml_object = simplexml_load_string($xml_string);

// check the file contents

echo "<pre>";
print_r($xml_object);
echo "</pre>";


//accessing the value 
$to = $xml_object->to;
echo "This message was sent to $to";

?>

Thursday 14 March 2013

Using ajax and php to change the value of one select box based on the value of the second selectbox

Hello Friends

Welcome to this next post.....


In this post we will be learning how to change the value of a select box based on the value of the other select box..

What does this means ...... ???

Suppose we ask user to select a Country ... based on the country we need to show the valid cities in the select box below it .... ...

So lets start with it ......

STEP 1 : creating the test database
  • Copy the sql import given below.
  • Create a database named "test"
  • Run this code as sql query .
This should create two tables namely country and cities in your database



-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 14, 2013 at 05:20 PM
-- Server version: 5.5.24-log
-- PHP Version: 5.4.3
 
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
 
--
-- Database: `test`
--
 
-- --------------------------------------------------------
 
--
-- Table structure for table `cities`
--
 
DROP TABLE IF EXISTS `cities`;
CREATE TABLE IF NOT EXISTS `cities` (
  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `country_id` int(11) NOT NULL,
  `city_name` varchar(255) NOT NULL,
  PRIMARY KEY (`city_id`),
  KEY `country_id` (`country_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
 
--
-- Dumping data for table `cities`
--
 
INSERT INTO `cities` (`city_id`, `country_id`, `city_name`) VALUES
(1, 1, 'city1Country1'),
(2, 1, 'city1Country1'),
(3, 2, 'city1country2'),
(4, 2, 'city2country2'),
(5, 2, 'city3country2'),
(6, 3, 'city1Country3');
 
-- --------------------------------------------------------
 
--
-- Table structure for table `country`
--
 
DROP TABLE IF EXISTS `country`;
CREATE TABLE IF NOT EXISTS `country` (
  `country_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`country_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
 
--
-- Dumping data for table `country`
--
 
INSERT INTO `country` (`country_id`, `name`) VALUES
(1, 'country1'),
(2, 'country2'),
(3, 'country3');
 
--
-- Constraints for dumped tables
--
 
--
-- Constraints for table `cities`
--
ALTER TABLE `cities`
  ADD CONSTRAINT `cities_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`);




STEP2 : Create html form with countries drop down populated from database .. 

This code gives you the basic idea how to populate the selectbox from the data in database.
Copy the code below save it as as php file(.php) and run.


<?php

#---- connect to database (connect)-----
$connect = mysql_connect('localhost','root','');
mysql_select_db('test',$connect);
#-----------(/end connect)---------


#--- select the countries from database-----

$query   = "SELECT * ".
                  "FROM ".
                  "country";

$resource       = mysql_query($query) or die(mysql_error());
$optionString   = ''; // this will contains the options to be populated in countries select box
while($row = mysql_fetch_assoc($resource))
{
   $optionString .= "<option value='{$row['country_id']}'>{$row['name']}</option>";   
}


#--------------------------------------------


?>

<html>
<head>
</head>
<body>
  <form type='post'>
<label for="country">Countries</label>
  <select name='country'>
  <?php echo $optionString;?>
  </select>
  </form>
</body>
<html> 










STEP3: Create one select box for cities and populate it based on the country This will be your final code ... that you have to run

Now database is created and you have a basic idea how to populate the select box using data from database.
Its time to fulfill our actual motive.

We have two scripts with us  ..

                                       1.testForm.php


This is the main script...in which we have two select boxes ...

When we change the value in the country text box it will populate the Cities drop down which contains the cities that are there in the selected country.

To accomplish this we will be using jquery ajax.Ajax will be called  when the value in the value in the country dropdown changes.

The url for ajax will be the page that gives us the corresponding cities (script named as populateCities.php)


 <?php

#---- connect to database (connect)-----
$connect = mysql_connect('localhost','yourUser','yourUserPassword');
mysql_select_db('test',$connect);
#-----------(/end connect)---------


#--- select the countries from database-----

$query      = "SELECT * ".
                  "FROM ".
                  "country";

$resource       = mysql_query($query) or die(mysql_error());
$optionString   = ''; // this will contains the options to be populated in countries select box
while($row = mysql_fetch_assoc($resource))
{
   $optionString .= "<option value='{$row['country_id']}'>{$row['name']}</option>";   
}


#--------------------------------------------


?>

<html>
<head>

<script src='http://code.jquery.com/jquery-latest.min.js'></script>

<script type='text/javascript'>
$(document).ready(function(){


$("#country").change(function(){

 var data = $("#testFrm").serialize();
alert(data);
   $.ajax({

       url  : 'cityPopulate.php',
       type : 'POST',
       data : data,
       success:function(data){
                $('#cities').html(data)
               }
    })


   });

});

</script>


</head>
<body>
  <form type='post' id='testFrm'>
  <table>
  <tr>
   <td> Country</td>
   <td> <select  id ='country' name='country'>
<option value='0'>--- SELECT COUNTRY------</option>
  <?php echo $optionString;?>
  </select></td>
  </tr>
  <tr>
   <td>CITIES</td>
 <td>
    <select id='cities'> </select>
 </td>
  </tr>
  </table>
  </form>
</body>
<html>

                             2.populateCities.php


This is the magic script ...This script will get the country_id as a POST request from testForm.php and will fetch the corresponding cities .

  
<?php

#---- connect to database (connect)-----
$connect = mysql_connect('localhost','yourUser','yourUserPassword');
mysql_select_db('test',$connect); #-----------(/end connect)--------- #-- get the post value posted using ajax-- $country_id = $_POST['country']; #------------------------------------------ #--- select the countries from database----- $query      = "SELECT * ".                   "FROM cities WHERE country_id = $country_id";                   $resource       = mysql_query($query) or die(mysql_error()); $optionString   = ''; // this will contains the options to be populated in countries select box while($row = mysql_fetch_assoc($resource)) {    $optionString .= "<option value='{$row['city_id']}'>{$row['city_name']}</option>";    } #-------------------------------------------- // echo the result to be showm in city selectbox echo $optionString; ?>


YOU ARE DONE....!!!!

How was it .... ? Hope you must have learned something new and interesting .....







Wednesday 13 March 2013

Posting Json data with php curl and then grabbing it ...

Hello Friends

In this blog you will be seeing how can be pots json data using php and then grab it on other page

You will need two scripts for that ..
1. postJson.php
2. handleCurl.php


I am assuming that before reading this post you have priliminary knowledge of php and curl.
                     
                                                 script for postJson.php

This script is to post the json data using php curl.


  • Since we are sending json data we need to tell this to the http header ..for this we are using custom headers and setting it using CURLOPT_HTTPHEADER.
  • Other this to notice is that since we are not using simple post so we are not using CURLOPT_POST instead we are using  CURLOPT_CUSTOMREQUEST ans setting it to "POST".
                   
<?php

#------- initializations(init)-------------

$data = array("param1" => "1234", "param2" => "30051987", "param3" => "myparam");

$data_string = json_encode($data);

$url = 'http://localhost/handleCurl.php';

#----------------(/init)---------------------------



#-----------curl setting(curl)-----------------

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

                     'Content-Type: application/json',

                     'Content-Length: ' . strlen($data_string))

                     );

$result = curl_exec($ch);

curl_close($ch);

#-------------------(/curl)---------------------

echo $result; // this echo is to see what we have received on handleCurl.


?>
                                          script for handleCurl.php
        
<?php
fopen('php://input','r');
 $rawData =stream_get_contents($fp);
 echo "<pre>" print_r($rawData);
 echo "</pre> 
?>";
  • Now some of  you  may ask why  have we used fopen() and stream_get_contents() instead of $_POST..??
  • The reason for thsi is since we are posting json data using customised headers .. $_POST will not be populated...and we have to get the raw input stream fopen()....


 Thats its .....and you  are done.!!!!

Thanks .. meet you with some other post soon.. Have a nice time !!