3/31/15

PHP File Open Read


PHP comes with a couple of different ways to read the contents of file.

=> Read the contents using file_get_contents( ) function

The easiest way to read the contents of a disk file with the file_get_contents( ) function.
This function accepts the name and path to a disk file, and read the entire file into a string variable.
Eg i
 <?php
  //read file into string
  $str=file_get_contents('output.txt') or die('ERROR:cannot find the file');
  echo $str;
 ?>

=> Read the contents using file( ) function

An alternative way of reading data from a file is file( ) function, which accepts the name and path to a file and reads the entire file into an array,
with each element of the array representing one line of the file.
Here’s an example which reads a file into an array and then displays it using foreach loop.
Eg ii
 <?php
  //read file into array
  $arr=file('output.txt') or die('ERROR: cannot file file');
  foreach($arr as $line)
  {
  echo $line;
  } 
 ?>

=> Reading remote files contents

All above defined file_get_contents( ) function and file( ) function support reading data from URLs using either the HTTP or FTP protocols.
Here’s an example which reads an HTML file off the Web into an array.
Eg iii
 <?php
  //read file into array
  $arr=file('http://www.google.com') or die('ERROR: cannot file file');
  foreach($arr as $line)
  {
  echo $line;
  } 
 ?>

In case of slow network links, it’s sometimes more efficient to read a remote file in “chunks” to maximize the efficiency of available network bandwidth.

=> Read the contents of the file using fread( ) function

=> Read the contents of the file using fgets( ) function

=> Read the contents of the file using fgetc( ) function



To do this use the fgets( ) function to read a specific number of bytes from a file.
Here’s an example which reads an HTML file using fgets( ) function.
Eg iv
 <?php
  //read file into array chunks
  $fo=fopen('http://www.google.com','r') or die('ERROR: cannot open file');
  while(!feof($fo))
   {
  $str.=fgets($fp,512);  
   }
  echo $str;
  fclose($fo);
 ?>

Read the external PHP file using include( ) or require( ) function

There are 4 functions to include external PHP files.
  1. inculde( )
  2. require( )
  3. inculde_once( )
  4. require_once( )
include( ) function says, a file should be developed which you want to call,
otherwise it shows waring error.
require( ) function says, a file must be developed which you want to call,
otherwise it shows Fatal error.
include_once( ) function says, a file should be called once on a page.
require_once( ) function says, a file must be called once on a page.

PHP File Create Write


PHP comes with a couple of different ways to do this as well.
To write inside the file first file must be opened with mode.

How to Open a file in PHP

fopen( ) is used to open a file. You have to pass two parameters inside this function.
The first one is file name which you want to open and second is mode(purpose to open) of the file.
Syntax
 <?php
  $fo=fopen("filename","mode");
  ?>

Different types of File MODE

The file may be opened in one of the following modes:
ModesDescription
wWrite 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
rRead only. Starts at the beginning of the file
r+Read/Write. Starts at the beginning of the file
aAppend. 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
xWrite 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

Write the contents inside file

1 file_put_contents()
The first is the file_put_contents()function, a close cousin of the file_get_contents() you will read about later.
file_put_contents() accepts a filename and path, together with the data to be written to the file, and then writes the latter to the former
Eg i
<?php
  //write string to file
  $data="A fish out of water";
  file_put_contents("output.txt",$data)
     or die('ERROR:Can not write file');
  echo "data written inside  this file";
?>

If the file specified in the call to file_put_contents() already exists on disk,.file_put_contents() will overwrite it by default.
if instead, you’d prefer to preserve the file’s contents and simply append new data to it, and the special FILE_APPEND flag to your .file_put_contents() function call as a third argument.
Eg ii
<?php
  //write string to file
  $data="A fish out of water";
  file_put_contents("output.txt",$data,FILE_APEND)or die('ERROR:Can not write file');
  echo "data written inside  this file";
?>

2 How to use fwrite( ) function

An alternative way to write data to a file is to create a file pointer with fopen( ), and then write data to the pointer using PHP’s fwrite( ) function.
Eg iii
 <?php
  //open and lock file 
  //write string to file
  //unlock and close file
  $data="A fish out of water"; 
  $fo=fopen("output.txt","w");
  flock($fo,LOCK_EX) or die('ERROR:cannot lock file');
  fwrite($fo,$data);
  flock($fo,LOCK_UN) or die('ERROR:cannot unlock file');
  fclose($fo);
  echo "Data written to file";
 ?>

2 How to use fputs( ) function

An alternative way to write small data to a file is fputs( ) function.
Eg iv
 <?php
  //open and lock file 
  //write string to file
  //unlock and close file
   $data="A fish out of water"; 
   $fo=fopen("output.txt","w");
   flock($fo,LOCK_EX) or die('ERROR:cannot lock file');
   fputs($fo,$data);
   flock($fo,LOCK_UN) or die('ERROR:cannot unlock file');
   fclose($fo);
   echo "Data written to file";
 ?>

PHP Directory

Directory is the collection of related files.

How to create a directory using PHP

Syntax
  <?php
         mkdir("your_dir_name");
  ?>
Eg i
  <?php
         mkdir("mydocs");
  ?>
   Output :
In the above example
in this program we use mkdir()function . Pass the directory name inside this function to create the directory.

How to create a sub directory inside a directory using PHP

Syntax
  <?php
         mkdir("your_dir_name/your_sub_dir_name");
  ?>

Eg ii
  <?php
         mkdir("mydocs/new updated docs");
  ?>
   Output :
In the above example use mkdir( ) function . pass the directory name/sub directory name inside mkdir() function sub directory create inside the main directory(make sure first must create a directory).

How to remove(delete) a directory in PHP
Syntax
  <?php
         rmdir("your_dir_name");
  ?>

Eg iii
  <?php
         rmdir("mydocs");
  ?>
   Output :
In the above example
We want to delete existing directory. Pass directory name “mydocs” inside rmdir( ) function.
it will delete the directory.
How to rename a directory
Syntax
  <?php
         rename("your_old_dir_name","new _ dir _name");
  ?>

Eg iv
  <?php
         rename("mydocs","my updated docs");
  ?>
   Output :
In the above example
if we want to rename a directory name. rename( ) function is used. it accept two argument first “the existing directory name” and second “new name which replace first directory name”.
How to check existence of directory
Syntax
  <?php
        echo file_exists("your_dir_name"");
  ?>

Eg v
  <?php
    echo  file_exists("mydocs");
  ?>
   Output :
In the above example
if we want to check the existence of a directory. file_exist( ) function is used with (directory name) .
if directory exist it gives true(“1″)

How to get files(contents) from directory
Note first manually store some files inside your directory
Syntax
  <?php
        scandir("your_dir_name"");
  ?>

Eg vi
  <?php
    $files =  scandir("mydocs");
    print_r($files);
  ?>
   Output :
in the above example
We get the contents of a directory. use scandir( ) function , directory name declare inside this.
scandir( ) function returns the files in array so stored the return value in a variable( $files).
Now print this using print_r($files) function i.e specially used to print the value and index of array.
it gives an output of an array type with index and their corresponding value.
How to open a directory
Syntax
  <?php
        opendir("your_dir_name"");
  ?>

Eg vii
  <?php
    $od =  openddir("mydocs");

  ?>
   Output :
In the above example
if we open the directory use opendir( ) function with directory name (“mydocs”).
store in variable $files because these open directory variable is going to used in further communication(for reading the contents).

How to read all files from a directory
Syntax
  <?php
        $files = readdir($od);
  ?>

Eg viii
  <?php
    $od =  opendir("mydocs");
    while($files =  readdir("mydocs"))
     {
       echo $files."<br/>";
    }
  ?>
   Output :
In the above example
first we open the directory of name(“mydocs”) and stores the values in $files(in previous example).
Now start to read the file using readdir( ) function till the file ends because here we are using while( ) loop.
to display the file name we have used echo statement in while loop.

PHP File Handling


The file system functions allow you to access and manipulate the file.
file system provides a concept to start a specific data using different types of file format.
That means file gives us linear type database concept. There is no any type of relations will be found with value because it doesn’t support RDBMS concept.
Through this concept you will retrieved data from disk filesXML documents and many other data sources.
Files In a computer, a file system (sometimes written filesystem) is the way in which files are named and where they are placed logically for storage and retrieval.
The DOS, Windows, OS/2, Macintosh, and UNIX-based operating systems all have file systems in which files are placed somewhere in a hierarchical (tree) structure.
A file is placed in a directory (folder in Windows) or sub-directory at the desired place in the tree structure.

How to Create a file using PHP

touch( ) function is used to create a file
Syntax
 <?php
    touch("fileName with extension");
 ?>

Eg i
 <?php 
  //create a ms word file
  touch("resume.doc");
  
  //create text file
  touch("data.txt");
  
  //create pdf file
  touch('corephp.pdf');
 ?>
 
  Output : Check your folder manually
(same folder where you have saved your program) a file will be created

How to Delete a file using PHP

unlink( ) function is used to delete a file
Syntax
  <?php
   unlink("fileName with extension");
  ?>
Eg ii
 <?php 
  //delete  resume word file
  unlink("resume.doc");
  
  //delete text file
  unlink("data.txt");
  
  //delete pdf file
  unlink('corephp.pdf');
 ?>
 
  Output : Check your folder manually
(same folder where you have saved your program) a file will be deleted

How to copy a file using PHP
copy( ) function is used to copy file
Syntax
 <?php
 copy("source file with extension","destination fileName with same extension");
 ?>
Eg iii
 <?php 
  //copy resume doc
  copy("resume.doc","Update resume.doc");
  
  //copy text file
  copy("data.txt","update data.txt");    
 ?>
 
  Output : Check your folder manually
(same folder where you have saved your program) a file will be copied with new name

How to Rename file using PHP
rename( ) function is used to rename file.
Syntax
<?php
   rename("old fileName with extension","New fileName with same extension");
?>
Eg iv
 <?php 
  //rename resume doc
  rename("resume.doc","Update resume.doc");
  
  //rename text file
  rename("data.txt","update data.txt");    
 ?>
 
  Output : Check your folder manually
(same folder where you have saved your program) a file will be renamed
Checks whether a file or directory exists
file_exists( ) function is used to check file or directory existence.
Syntax
<?php
   file_exists("fileName with extension");
    OR
  file_exists("directory name");
?>
Eg v
 <?php 
  //check file existence
  echo file_exists("Update resume.doc");
      
 ?>
 
  Output : It returns true(1) if file exists
        otherwise return false(blank screen)

Check size of the file in PHP
filesize( ) function is used to check file size.
Syntax
<?php
   filesize("fileName with extension");
?>
Eg vi
 <?php 
  //check file size
  echo filesize("Update resume.doc")." Bytes";   
 ?>
 
  Output : 0 Bytes

Check Path of the file in PHP
realpath( ) function is used to check real path of the file.
Syntax
<?php
   realpath("fileName with extension");
?>
Eg v
 <?php 
  //check real path of the file
  echo realpath("Update resume.doc");
      
 ?>
 
  Output : C:\xampplite\htdocs\YoufProject\fileName with extension
                 OR
        C:\wamp\www\YoufProject\fileName with extension    

PHP Date And Time


<?php
if(isset($_POST['sub']))
{
$mm=$_POST['mm'];
$dd=$_POST['dd'];
$yy=$_POST['yy'];

$dob=$mm."/".$dd."/".$yy;
$arr=explode('/',$dob);
 //$dateTs=date_default_timezone_set($dob); 
 $dateTs=strtotime($dob);
 $now=strtotime('today');
 if(sizeof($arr)!=3) die('ERROR:please entera valid date');
 if(!checkdate($arr[0],$arr[1],$arr[2])) die('PLEASE: enter a valid dob');
 if($dateTs>=$now) die('ENTER a dob earlier than today');
 $ageDays=floor(($now-$dateTs)/86400);
 $ageYears=floor($ageDays/365);
 $ageMonths=floor(($ageDays-($ageYears*365))/30);
 echo "<font color='red' size='10'> You are aprox $ageYears years and $ageMonths months old.  </font>";
}
?>

<form method="post"><center>
 choose your DOB
 <select name="yy">
  <option value="">Year</option>
          <?php
  for($i=1900;$i<=2014;$i++)
  {
  echo "<option value='$i'>$i</option>";
  }
  ?>
 </select>
 
 <select name="mm">
  <option value="">Month</option>
  <?php
  for($i=1;$i<=12;$i++)
  {
  echo "<option value='$i'>$i</option>";
  }
  ?>
 </select>
 
 
 <select name="dd">
  <option value="">Date</option>
  <?php
  for($i=1;$i<=31;$i++)
  {
  echo "<option value='$i'>$i</option>";
  }
  ?>
 </select>
 <input type="submit" name="sub" value="check it"/>
 </center>
 </form>
 

Output :  You are aprox 26 years and 4 months old
               choose your DOB

    

Create an age Calculator(Enter your DOB in text box)

Eg ii

<?php 
error_reporting(1);
$day=0;
$yr=0;
$mon=0;
if(isset($_POST['b1']))
{
$d1=$_POST['t1'];
$d2=$_POST['t2'];
$arr=explode("/",$d1);
$brr=explode("/",$d2);
if($arr[0]<$brr[0])
{
$arr[0]+=30;
$arr[1]-=1;
}
$day=$arr[0]-$brr[0];
if($arr[1]<$brr[1])
{
$m1+=12;
$arr[2]-=1;
}
$mon=$arr[1]-$brr[1];
$yr=$arr[2]-$brr[2];
}
?>

<form method="post">
<table border="2">
<tr>
<td align="center" colspan="2"><font color="orange"><h2><b>Age Calculator</b></h2></font></td>
</td>
<tr>
<td align="center"><b>enter current date:</b></td>
<td align="center"><input type="text" name="t1" autofocus></td>
</tr>
<tr>
<td align="center"><b>enter your DOB:</b></td>
<td align="center"><input type="text" name="t2"></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" name="b1" value="calculate"></td>
</tr>
<tr>
<td align="center"><b>Your Age is:</b></td>
<td align="center"><?php 
error_reporting(1);
echo '<font color="blue" size="5">';
echo $yr.' years '.$mon.' months '.$day.' days ';
echo '</font>';
?>
</td>
</tr>
</table>
</form>
Output : 
          

Age Calculator

Your Age is:26 years 4 months 0 days
enter current date:
enter your DOB:
In the above example
Create a HTML script to take input from users separated by “/” current(year, month, date) and his date of birth (year, month, date).
Convert the inputted value mm/dd/yyyy string into array using explode( ) function for both current date and date of birth.
strore these values in $arr variable at 0 index date, at 1 index month and at 2 index year like
$arr[0]=date
$arr[1]=month
$arr[2]=year
same as for (date of birth) inside $brr variable.
Now check for date if current “date” is less than date of birth “date” then borrow 1 month and add 30days in current date and calculate.
Same as for Month here borrow 1year from existing year and add 12 months.
subtract current months with date of birth “month” and store in $mon variable.
at last calculate for year and store the value in $yr variable.
Display the all calculated values(Year,Month, Date) like: 26 years 4 months 0 days

PHP Nested Array


Syntax
 array(array(val1, val1, val2..), array(val1,val2,val3..))

Create a two dimensional numeric array and find the sum.

Eg i
<?php
error_reporting(1);
$arr=array(array(10,10,10),array(10,10,10),array(10,10,10));
$s=0;
$s1=0;
//using for loop:
for($i=0;$i<3;$i++)
{
 for($j=0;$j<3;$j++)
 {
 echo $arr[$i][$j]." ";
 $s=$s+$arr[$i][$j];
 }
 echo "<br>";
}
echo "sum of array:".$s;
 
      ?>
Output :  10 10 10
          10 10 10
          10 10 10
          sum of array : 90
In the above example
Create a variable $arr with value an nested array.
Here at the place of array’s first element there is also an array with three value like
$arr[0][0]=10, $arr[0][1]=10, and $arr[0][2]=10.
at the second index the value are : $arr[1][0]=10, $arr[1][1]=10, and $arr[1][2]=10.
at the 3rd index the value are : $arr[2][0]=10, $arr[2][1]=10, and $arr[2][2]=10.
Now first call all nested array using for loop. first for loop call the three array(row) one by one, inside this loop again call a for loop i.e used to call first array’s all value(columns of row),
print it using echo statement and also make sum ans store inside a variable $s.
So the output will display:
first row’s three column i.e 10 10 10
second row’s three column i.e 10 10 10
Third row’s three column i.e 10 10 10
and the final sum is 90

Create a two dimensional numeric array and find the sum using for-each

Eg ii
 <?php
error_reporting(1);
$arr=array(array(10,10,10),array(10,10,10),array(10,10,10));
$s=0;
$s1=0;
//using for loop:
foreach($arr as $k)
{
  foreach($k as $v)
   {
   echo $v;
   $s1=$s1+$v;
   }
 echo "<br>";
}
echo "sum of array:".$s1;

?>
Output :  10 10 10
          10 10 10
          10 10 10
          sum of array : 90

Two dimensional associative array( user’s name and mobile number)

Eg iii
<?php
error_reporting(1);
$arr=array(array("name"=>"neeraj","mob"=>342353534),
           array("name"=>"rohit","mob"=>34235),
           array("name"=>"deepak","mob"=>33534)
          );
echo '<table border="2">';
echo '<tr>';
echo '<td align="center">Name:</td>';
echo '<td align="center">MOb:</td>';
foreach($arr as $k)
{
echo '<tr>';
foreach($k as $v)
{
echo '<td align="center">'.$v.'</td>';
}
echo '</tr>';
}
echo '</table>';

?>
Output :
NameMobile
neeraj342353534
rohit34235
deepak33534

Two dimensional associative array

Eg iv (display city according to selected country)
<?php
 $country=array("ind"=>array("Lucknow","Rajasthan","Delhi"),
            "pak"=>array("Islamabad","Lahore"),
            "ch"=>array("ch1","ch2")
           );
if(isset($_GET['display']))
 {
 $get_country=$_GET['c'];
echo "City ";
 foreach($country as $country_key => $cname)
   {
     if($country_key==$get_country)
    {
         echo "<select>";
       foreach($cname as $state)
         {
  echo "<option>".$state."</option>";
   }
  echo "</select>"; 
           }
      }
 }

?>
<form method="get">
<select name="c">
<option value="ind">india</option>
<option value="pak">Pak</option>
<option value="ch">china</option>
</select>
<input type="submit" value="submit" name="display"/>
</form>

Output : select country 
                  City  
                     
In the above example
first create an array in which multiple index(country) are defined as array, on that array multiple city defined(as column of row).
Now user has to select his country name from select box.
according to selected country, find the city i.e stored on country index using foreach loop.

Multidimensional associative array

Syntax
 array(array(array(array(val1, val1, val2....))))
Eg v
 <?php
    $country=array("pak"=>"pakistan","ind"=>array("br"=>"bihar",
   "dl"=>array("Nd"=>"North delhi","sd"=>"south delhi",
   "Ed"=>array("dwarka","uttam nagar"))));

 echo $country["ind"]["br"]."<br/>";
 echo $country["ind"]["dl"]["Nr"]."<br/>";
 echo $country["ind"]["dl"]["Ed"][0];
 
?>
 
Output : bihar
  North delhi
  dwarka

FIND US ON FACEBOOK

FIND US ON Twitter