Methods of file handling in php (file handling functions)

File Handling Function

basename() Function

The basename() function returns the filename from a path.

Syntax

File name index.php

basename(path,suffix)

suffix Specifies a file extension. If the filename has this file extension, the file extension will not show

File name index.php

<?php
$path = "home.php";

//Show filename with file extension
echo basename($path) ."<br/>";

//Show filename without file extension
echo basename($path,".php");
?>

Output :-

home.php
home

How to get directory name , file name , extension name and filename without extension in php.

<?php
$path_parts = pathinfo('http://itechtuto.com/ajax/index.php');

echo $path_parts['dirname'];
echo "<br/>";
echo $path_parts['basename'];
echo "<br/>";
echo $path_parts['extension'];
echo "<br/>";
echo $path_parts['filename'];
?>

How to copy file from one directory to another directory.

File name index.php

<?php

//$file = 'myimg.png';
//$newfile = 'testfolder/myimg1.png';


$file = 'example.txt';
$newfile = 'testfolder/example.txt.bak';

if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>

How to clear catche of your page.

File name index.php

<?php
//unlink() does not clear the cache if you are performing file_exists() on a remote file like:

if (file_exists("ftp://ftp.example.com/somefile"))
?>

In this case, even after you unlink() successfully, you must call clearstatcache().

<?php
unlink("ftp://ftp.example.com/somefile");
clearstatcache();
?>

How to clear catche of your page.

File name index.php

<?php
//unlink() does not clear the cache if you are performing file_exists() on a remote file like:

if (file_exists("ftp://ftp.example.com/somefile"))
?>

In this case, even after you unlink() successfully, you must call clearstatcache().

<?php
unlink("ftp://ftp.example.com/somefile");
clearstatcache();
?>

How to check file exits or not.

if file is available in directory or specified path then we use file_exists function.

<?php
$filename = 'example.txt';
$file_path = 'images/myfile/my_file.pdf';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>



if (file_exists($file_path)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>

is_file() :-

The is_file() function is used to check the specified file is a regular file or not. The name of the file is pass as a parameter to the is_file() function and it returns True if the file is a regular file otherwise it returns False.

is_file() function accept one parameter.

is_file() function returns false for if file not exists.

is_file() will return false if the given path points to a directory.(file is available in directory).

$file_name = "myfile.pdf";
is_file($file_name)
{
echo ("$file_name: is regular file");
return true;
}
else{
echo ("$file_name: not a regular file!");
return false;
}

How create a driectory dynamically.

File name index.php

$pathfolder = "appsimages/";
$tod = date('Ymd');
$filename = $pathfolder .$tod."/";

if (!file_exists($filename)) {
mkdir($pathfolder . $tod, 0777);

$fol = $filename."/img";
mkdir($fol);
$fol1 = $filename."/imgs";
mkdir($fol1);
$fol2 = $filename."/phpfile";
mkdir($fol2);

echo "The directory $tod was successfully created.";
exit;
}
else
{
echo "The directory $tod exists.";
}

chmod() Function

The chmod() function changes permissions of the specified file. Returns TRUE on success and FALSE on failure.

Syntax

File name index.php

chmod(file,mode)

The mode parameter consists of four numbers:

  • The first number is always zero
  • The second number specifies permissions for the owner
  • The third number specifies permissions for the owner's user group
  • The fourth number specifies permissions for everybody else
  • Possible values (to set multiple permissions, add up the following numbers):
  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions


  • File name index.php

    <?php
    // Read and write for owner, nothing for everybody else
    chmod("test.txt",0600);

    // Read and write for owner, read for everybody else
    chmod("test.txt",0644);

    // Everything for owner, read and execute for everybody else
    chmod("test.txt",0755);

    // Everything for owner, read for owner's group
    chmod("test.txt",0740);
    ?>

    copy() Function

    The copy() function copies a file from one file to another file.

    Note: If the destination file already exists, it will be overwritten.


    Syntax :- copy(file,to_file)

    File name index.php

    <?php
    echo copy("source.txt","target.txt");
    ?>

    unlink() Function

    The unlink() function delete a file.

    Syntax :-
    unlink(filename,context)

    File name index.php

    <?php
    $file = "test.txt";
    if (!unlink($file))
    {
    echo ("Error deleting $file");
    }
    else
    {
    echo ("Deleted $file");
    }
    ?>

    How to delete or Rename a file in php

    unlink function delete a file.

    rename() function is used to rename a specified file.

    $src = "/assets/images/myfiles/";
    $myfile = "sana.pdf";
    $file_path = $src.$myFile;
    $getext_gfile = explode(".", $myFile);
    $newfile = $getext_gfile[0];
    $extension = end($getext_gfile);
    $new_file_name = $src.$newfile.'_'.date('dmY_his').'.'.$extension;
    if(file_exists($file_path)){
    // unlink($file_path);
    rename($file_path, $new_file_name);
    }

    dirname() Function

    The dirname() function returns the directory name from a path.

    Syntax :-
    dirname(path)

    File name index.php

    <?php
    echo dirname("c:/testweb/home.php") . "<br />";
    echo dirname("/testweb/home.php");
    ?>

    output :
    c:/testweb
    /testweb

    file() Function

    The file() reads a file into an array. Each array element contains a line from the file, with newline still attached.

    File name index.php

    <?php
    print_r(file("test.txt"));
    ?>

    output :-
    Array
    (
    [0] => Hello World. Testing testing!
    [1] => Another day, another line.
    [2] => If the array picks up this line,
    [3] => then is it a pickup line?
    )

    file_exists() Function

    The file_exists() function checks whether or not a file or directory exists.

    File name index.php

    <?php
    echo file_exists("test.txt");
    ?>

    file_get_contents() Function

    The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. Because it will use memory mapping techniques, if this is supported by the server, to enhance performance.

    Syntax :-
    file_get_contents(path,include_path,context,start,max_length)

    Note : This function is binary-safe (meaning that both binary data, like images, and character data can be written with this function).

    File name index.php

    <?php
    echo file_get_contents("test.txt");
    ?>

    file_put_contents() Function

    The file_put_contents() writes a string to a file.

    This function follows these rules when accessing a file:

  • If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of *filename*
  • Create the file if it does not exist
  • Open the file
  • Lock the file if LOCK_EX is set
  • If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
  • Write the data into the file
  • Close the file and release any locks
  • Syntax :- file_put_contents(file,data,mode,context)

    File name index.php

    <?php
    echo file_put_contents("test.txt","Hello World. Testing!");
    ?>

    ootput :
    21

    fgetcsv() Function

    The fgetcsv() function parses a line from an open file, checking for CSV fields.
    The fgetcsv() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.
    This function returns the CSV fields in an array on success, or FALSE on failure and EOF.

    Syntax :- fgetcsv(file,length,separator,enclosure)

    File name mycsv.csv

    Kai Jim, Refsnes, Stavanger, Norway
    Hege, Refsnes, Stavanger, Norway

    Example

    File name index.php

    <?php
    $file = fopen("mycsv.csv","r");
    print_r(fgetcsv($file));
    fclose($file);
    ?>

    Output :-

    Array
    (
    [0] => Kai Jim
    [1] => Refsnes
    [2] => Stavanger
    [3] => Norway
    )

    Example

    File name index.php

    <?php
    $file = fopen("mycsv.csv","r");

    while(! feof($file))
    {
    print_r(fgetcsv($file));
    }

    fclose($file);
    ?>

    Output :-

    Array
    (
    [0] => Kai Jim
    [1] => Refsnes
    [2] => Stavanger
    [3] => Norway
    )
    Array
    (
    [0] => Hege
    [1] => Refsnes
    [2] => Stavanger
    [3] => Norway
    )

    Example

    File name index.php

    <?PHP

    $file_handle = fopen("itech.csv", "r");

    while (!feof($file_handle) ) {

    $line_of_text = fgetcsv($file_handle, 1024);

    print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";

    }

    fclose($file_handle);

    ?>

    Output :-


    fgets()

    File name index.php

    <?PHP

    $file_handle = fopen("itech.txt", "rb");

    while (!feof($file_handle) ) {

    $line_of_text = fgets($file_handle);
    $parts = explode('=', $line_of_text);

    print $parts[0] . $parts[1]. "<BR>";

    }

    fclose($file_handle);

    ?>

    fputcsv() Function

    The fputcsv() function formats a line as CSV and writes it to an open file. This function returns the length of the written string

    Syntax : - fputcsv(file,fields,seperator,enclosure)

    File name index.php

    <?php
    $list = array
    (
    "mahtab,itechtuto,itechaio,it",
    "habib,kalam,rani,alka",
    );

    // $file = fopen("mycsv.txt","w");
    $file = fopen("mycsv.csv","w");

    foreach ($list as $line)
    {
    fputcsv($file,explode(',',$line));
    }

    fclose($file); ?>

    Output :-

    text format

    mahtab,itechtuto,itechaio,it
    habib,kalam,rani,alka

    csv format

    itechtuto csv format

    File name index.php

    <?php

    $list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
    );

    $fp = fopen('file.csv', 'w');

    foreach ($list as $fields) {
    fputcsv($fp, $fields);
    }

    fclose($fp);
    ?>

    Output :-

    aaa,bbb,ccc,dddd
    123,456,789
    """aaa""","""bbb"""

    Write table data in text file and csv file in php.

    File name index.php

    <?php
    $host = "localhost";
    $username ="root";
    $password = "";
    $db_name = "employee_info";
    $con = mysqli_connect($host,$username,$password)or die(mysqli_error());
    mysqli_select_db($con,$db_name)or die(mysqli_error($con));

    $fileName = "myfile1.csv";
    // $fileName = "myfile1.txt";
    $fp = fopen($fileName,"w");
    $outPut = "id \t first_name \t last_name \t address\n";
    $qry = "select * from employee";
    $result = mysqli_query($con, $qry);
    while($row = mysqli_fetch_array($result))
    {
    $outPut .= $row['id']."\t".$row['first_name']."\t". $row['last_name']."\t".$row['address']."\n";
    //fwrite($fp,$row['id']."\n");
    //fwrite($fp,$row['first_name']."\t");
    //fwrite($fp,$row['last_name']."\t");

    }
    fwrite( $fp, $outPut);
    fclose($fp);
    ?>


    Output :-


    How to write database table data in csv file.

    the fputcsv() function accepts array of database results and a file resource pointer. This array of results are converted into the CSV format and written to the target .csv file with the reference of the given file pointer. The syntax of this function is,
    fputcsv($file_pointer, $input_array, $delimiter = ',', $enclosure = '"');
    In this code, we are creating the file pointer by opening PHP output stream. And then, we set this pointer and database field array to the fputcsv() function. This function will be called after setting header with content-type, disposition and CSV file name.

    File name index.php

    <?php
    $host = "localhost";
    $username ="root";
    $password = "";
    $db_name = "employee_info";

    $con = mysqli_connect($host,$username,$password)or die(mysqli_error());
    mysqli_select_db($con,$db_name)or die(mysqli_error($con));


    $filename = "info.csv";
    $fp = fopen($filename, 'w');
    // $fp = fopen('php://output', 'w');

    $query = "SELECT * FROM employee";
    $result = mysqli_query($con, $query);
    while ($row = mysqli_fetch_row($result)) {
    $header[] = $row[0];
    }
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename='.$filename);
    fputcsv($fp, $header);

    $num_column = count($header);
    $query = "SELECT * FROM employee";
    $result = mysqli_query($con, $query);
    while($row = mysqli_fetch_row($result)) {
    fputcsv($fp, $row);
    }

    ?>

    Output :-


    How to create csv file from array data in php.

    The header function is used to send the raw HTML headers to the client. The argument Content-type: text/csv will set the content type, the content disposition header field will force the content to be saved as a file. The Cache control field is controlled using the Pragma header field. The expire header field determines the content is stale. The $data array contains the CSV data which can be obtained using a simple MySQL query. (The MySQL query has been removed for simplicity). Now the function fopen(php://output) will create a file handler which will sent the data to the output stream. Finally the PHP function fputcsv will write the CSV data to a file.

    File name index.php

    <?php
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    $data = array(
    array("mahtab", "34144234", "5000"),
    array("alam", "3245325", "8000"),
    array("raj", "63465235", "10000")
    );
    $file = fopen('php://output', 'w');
    fputcsv($file, array('Name', 'mob', 'cost'));
    foreach($data as $row)
    {
    fputcsv($file, $row);
    }
    exit();
    ?>

    Output :-


    How to insert excel / csv file in database using Php

    File name index.php

    <div style="border:1px dashed #333333; width:300px; margin:0 auto; padding:10px;">

    <form name="import" method="post" enctype="multipart/form-data">
    <input type="file" name="file" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    <?php
    include ("db.php");

    if(isset($_POST["submit"]))
    {
    $file = $_FILES['file']['tmp_name'];
    $handle = fopen($file, "r");
    $c = 0;
    while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
    {

    $pincode = $filesop[0];
    $city = $filesop[1];
    $state = $filesop[2];


    $sql = mysqli_query($con,"INSERT INTO pincode_tbl (pincode, city, state) VALUES ('$pincode','$city','$state')");
    $c = $c + 1;
    }

    if($sql){
    echo "You database has imported successfully. You have inserted ". $c ." recoreds";
    }else{
    echo "Sorry! There is some problem.";
    }

    }
    ?>

    </div>




    </div>
    </div>
    </div>
    </div>



    Method-1: Import excel data using php script

    File name index.php



    $handle = fopen("BooksList.csv", "r");
    while (($data = fgetcsv($handle)) !== FALSE) {
    $num = count($data);
    $row;
    echo "INSERT into importing(text,number)values('$data[0]','$data[1]')";
    echo "<br>";
    }


    Method-2:

    File name index.php



    $handle = fopen("BooksList.csv", "r");
    $fields=array('category','datatype','date','value');
    $table='test';
    $sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
    while (($data = fgetcsv($handle)) !== FALSE) {
    foreach($data as $key=>$value) {
    $data[$key] = "'" . addslashes($value) . "'";
    }
    $rows[] = implode(",",$data);
    }
    $sql_query .= implode("),(", $rows);
    $sql_query .= ")";
    echo $sql_query;


    How to Import Excel/CSV file to MySQL Database Using PHP.

    File name index.php

    <!DOCTYPE html>
    <?php
    include 'db.php';

    ?>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Import Excel To Mysql Database Using PHP </title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Import Excel File To MySql Database Using php">

    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-responsive.min.css">
    <link rel="stylesheet" href="css/bootstrap-custom.css">


    </head>
    <body>

    <!-- Navbar
    ================================================== -->

    <div class="navbar navbar-inverse navbar-fixed-top">
    <div class="navbar-inner">
    <div class="container">
    <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    </a>
    <a class="brand" href="#">Import Excel To Mysql Database Using PHP</a>

    </div>
    </div>
    </div>

    <div id="wrap">
    <div class="container">
    <div class="row">
    <div class="span3 hidden-phone"></div>
    <div class="span6" id="form-login">
    <form class="form-horizontal well" action="import.php" method="post" name="upload_excel" enctype="multipart/form-data">
    <fieldset>
    <legend>Import CSV/Excel file</legend>
    <div class="control-group">
    <div class="control-label">
    <label>CSV/Excel File:</label>
    </div>
    <div class="controls">
    <input type="file" name="file" id="file" class="input-large">
    </div>
    </div>

    <div class="control-group">
    <div class="controls">
    <button type="submit" id="submit" name="Import" class="btn btn-primary button-loading" data-loading-text="Loading...">Upload</button>
    </div>
    </div>
    </fieldset>
    </form>
    </div>
    <div class="span3 hidden-phone"></div>
    </div>

    <table class="table table-bordered">
    <thead>
    <tr>
    <th>ID</th>
    <th>Subject</th>
    <th>Description</th>
    <th>Unit</th>
    <th>Semester</th>


    </tr>
    </thead>
    <?php
    $SQLSELECT = "SELECT * FROM subject ";
    $result_set = mysql_query($SQLSELECT, $conn);
    while($row = mysql_fetch_array($result_set))
    {
    ?>

    <tr>
    <td><?php echo $row['SUBJ_ID']; ?></td>
    <td><?php echo $row['SUBJ_CODE']; ?></td>
    <td><?php echo $row['SUBJ_DESCRIPTION']; ?></td>
    <td><?php echo $row['UNIT']; ?></td>
    <td><?php echo $row['SEMESTER']; ?></td>


    </tr>
    <?php
    }
    ?>
    </table>
    </div>

    </div>

    </body>
    </html>


    import.php

    File name import.php

    <?php
    include 'db.php';
    if(isset($_POST["Import"])){


    echo $filename=$_FILES["file"]["tmp_name"];


    if($_FILES["file"]["size"] > 0)
    {

    $file = fopen($filename, "r");
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
    {

    //It wiil insert a row to our subject table from our csv file`
    $sql = "INSERT into subject (`SUBJ_CODE`, `SUBJ_DESCRIPTION`, `UNIT`, `PRE_REQUISITE`,COURSE_ID, `AY`, `SEMESTER`)
    values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]')";
    //we are using mysql_query function. it returns a resource on true else False on error
    $result = mysql_query( $sql, $conn );
    if(! $result )
    {
    echo "<script type=\"text/javascript\">
    alert(\"Invalid File:Please Upload CSV File.\");
    window.location = \"index.php\"
    </script>";

    }

    }
    fclose($file);
    //throws a message if data successfully imported to mysql database from excel file
    echo "<script type=\"text/javascript\">
    alert(\"CSV File has been successfully Imported.\");
    window.location = \"index.php\"
    </script>";



    //close of connection
    mysql_close($conn);



    }
    }
    ?>

    Database

    CREATE TABLE IF NOT EXISTS `subject` (
    `SUBJ_ID` INT(11) NOT NULL AUTO_INCREMENT,
    `SUBJ_CODE` VARCHAR(30) NOT NULL,
    `SUBJ_DESCRIPTION` VARCHAR(255) NOT NULL,
    `UNIT` INT(2) NOT NULL,
    `PRE_REQUISITE` VARCHAR(30) NOT NULL DEFAULT 'None',
    `COURSE_ID` INT(11) NOT NULL,
    `AY` VARCHAR(30) NOT NULL,
    `SEMESTER` VARCHAR(20) NOT NULL,
    PRIMARY KEY (`SUBJ_ID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=500 ;





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here