Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday 25 April 2013

Reading Data From File in File system

Often we need to read the data from the file that is present on our file system.
PHP provides a very good support for file handling .

In this post I will mainly be concerned about reading of data from file .
Writing and updating new content and deleting file will be explained in upcoming post.

For reading file we have many inbuilt functions at our disposal.
In this article we will go through 
a) fread() and required fopen() and fclose()
b) file_get_contents.
c) file()

METHOD ONE : Reading file using fread()

First let we have a sample text file 'sample.txt' in our file system.
For testing let its contents be 
    
This is sample test file.
It contains the dummy contents.


Now we have to read its contents using php.

step 1 : Open the file using fopen() in read mode.
step 2 : read the contents using fread()
step 3 : close the file handler.

When we read the file using fopen() it gives us the pointer or you can say a resource handler to handle the file.
Its takes the file path and mode as mandatory parameters

<?php
fopen("path to sample.txt", "r");
?>

A file may be opened in following modes other then read mode
MODEDESCRIPTION
r Read only.
r+ Read/Write.
w Write only. over write the contents of file or creates a new file if it doesn't exist
w+ Read/Write. over write the contents of file or creates a new file if it doesn't exist
a Append. Add the contents to the end of file or creates a new file if it doesn't exist
a+ Read/Append. Add the contents to the end of file
x Write only. Creates a new file.
x+ Read/Write. Creates a new file.

 If you want to read more about it go here

once we have appropriate handle we can read it using fread()

It has 2 parameters 
 ==> file handler
 ==> Length in bytes you want to read 


$contents = fread($handle,1025);

Now we have all contents of text file in $contents .We will now close the file and echo its contents.

 fclose($handle);
 echo $contents;

So complete program will be like this
<?php
 $handle   = fopen("sample.txt", "r");
 $contents = fread($handle,1000);
 fclose($handle);
 echo $contents;
?>




This function returns false on failure.
You can read official documentation for more info.


METHOD TWO : Reading file using file_get_contents();

This is yet another function for reading the file ..

This difference beween this and fread() is that you need not to explicitly open and close the file .

<?php

$contents =file_get_contents('path to file');

echo $contents;

?>



Read more here


METHOD THREE

The last method that I am going to discuss here is file().
This method will read the file and convert it into array.In this method also you need not to open the file manually.

<?php
 $lines = file('path to sample.txt',FILE_IGNORE_NEW_LINES);
 foreach($lines as $line)
 { 
   echo $line;
 }
?>
I have used FILE_IGNORE_NEW_LINES to ignore '\n' that would have else been printed at end of each line.

The other available options are .
FILE_USE_INCLUDE_PATH  : search for file in include path
FILE_SKIP_EMPTY_LINES    : skip empty lines


You can read in more detail  here.


Quite simple .. isn't it..?

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";

?>

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 !!