1

code:

<?php
    if(isset($_POST['upload']))
    {
        $filename = $_FILES['files']['name'];
        $path = "upload_enq/";
        $move = move_uploaded_file($_FILES['files']['tmp_name'],$path.$_FILES['files']['name']);
        $path_file = "upload_enq/".basename($_FILES['files']['name']);

        $c =0;
        $fileObj = fopen( $path_file, "rt" );
        if($fileObj){
            while(!feof($fileObj)){
                $content = fgets($fileObj);
                if($content)    
                $c++;
            }
        }
        fclose($fileObj);
        echo $c;
    }
?>
<form class="forms-sample" method="post" enctype="multipart/form-data">
    <input type="file" name="files" id="files" />
    <input type="submit" class="btn btn-success mr-2" name="upload" id="upload" value="Upload" />
</form>

In this code I have create a simple form where I am uploaded csv file and I want to count lenght of csv file. Now what happen when I uploaded csv file which having 295 rows but it shows wrong output it count 926 rows. So, How can I fix this issue ?Please help me.

Thank You

omkara
  • 974
  • 5
  • 24
  • 50

2 Answers2

0

As you said that you need the row count of the csv file, so use file()

$fp = file( $path_file, FILE_SKIP_EMPTY_LINES);
echo count($fp);

So the code will become short now

<?php
    if(isset($_POST['upload']))
    {
        $filename = $_FILES['files']['name'];
        $path = "upload_enq/";
        $move = move_uploaded_file($_FILES['files']['tmp_name'],$path.$_FILES['files']['name']);
        $path_file = "upload_enq/".basename($_FILES['files']['name']);

        $fp = file( $path_file);
        echo count($fp);
    }
?>

I have tested it on local:-

https://prnt.sc/jody8e

https://prnt.sc/jodyjl

https://prnt.sc/jodyoz

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

As per my comments use Count function to get total number of rows in CSV file like this

$fileObj= file('filename.csv');
echo count($fileObj);

for more details read PHP Manual

Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42