0

I'm trying to import and fetch data from CSV file and store it in my database my database table schema is like this
users ( ID , Fname , Lname, user_type , major , Bday , Email,password , image , status )
csv ( 111 , Leo , pichon, , business, , leo@yzu.cn ) and this is my csv file schema , columns only matching the required filed of my database schema its somthing like this : '' the empty filed either have default value or null ''

after importing i get the following notice for almost each row of my data file : Undefined offset: 1 in php csv here's my php function :

if ($_GET['action'] = 'UsersCvs') {

if (isset($_FILES['users_cvs']['name'])) {
    $file = $_FILES['users_cvs']['tmp_name'];
    if ($_FILES["users_cvs"]["size"] > 0) {


        $handle = fopen($file, "r");
        $c = 0;
        while (($files = fgetcsv($handle, 2000, ",")) !== false) {

            // $id = mysqli_real_escape_string($link , $files[0]);
            // $fname = $files[1];
            // $lname =  $files[2];
            // $user_type = $files[3];
            // $major = $files[4];
            // $email = $files[6];
            // $gender = mysqli_real_escape_string($link, $filesop[6]);
            //$sql = "INSERT INTO users(ID , Fname,Lname , user_type , major , Email) values ('" . $id . "','" . $fname . "' ,'" . $lname . "' ,'" .$user_type. "','" . $major . "','" . $email . "')";

            // mysqli_query($link, $sql);
            $num = count($files);
            echo "<p> $num fields in row $c: <br /></p>\n";
            $c++;
            for ($i = 0; $i < $num; $i++) {
                echo $files[$i] . "<br />\n";
            }
        
        }
        fclose($file);
        // if ($sql) {
        //     echo 1 ;
        // } else {
        //     echo mysqli_error($link); ;
        // }
    } else {

    }
}else{
    echo 'no file found';
}

}

what seems strange to my and after inspection my data gets encoded to unreadable string somthing like this

 <p> 3 fields in line 2: <br /></p>

�Ѷѩ\h�1�������
��dr
KK(G~�S⼥���Nw|x���
�s�k�Ŗ�X���J�fb�fWш�eʬ�y�`hc�g�

1 fields in line 3:

���y��Q�b~���^�)�Ϸ�������LD?��r�:��DN��(����C��*T�?��C��!�&�e���!_�8��+[�|��PK�N�@}�":[docProps/core.xml��QK�0���C�{��cm*{r 8Q|��lҐD��{�v����c�9���^R������:��� Ah���%zٮ���gZ���P�8��no

2 fields in line 4:

I've really tried my best and did online research but i couldn't find any matching reference i would highly appreciate help thanks in advance

HAMMASI
  • 33
  • 1
  • 7
  • You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized prepared statements instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even by trusted users, [you are still at risk of corrupting your data](https://bobby-tables.com/). [Escaping is not enough](https://stackoverflow.com/q/5741187). – Jason K Apr 26 '21 at 20:35
  • Are you sure you are reading the right file? Check the value of $file. – Jason K Apr 26 '21 at 20:38
  • Is your form method a get or a post? Not sure if you can upload with a get. – Jason K Apr 26 '21 at 20:55
  • Yes Im reading the right file , I'm using ajax post method , and appending action to my url just to indicate my action type – HAMMASI Apr 26 '21 at 21:11
  • I'm not inserting the data yet it seems to be injected right after reading it from the file – HAMMASI Apr 26 '21 at 21:14

1 Answers1

2

The file you are trying to process is not a CSV file, but an Excel workbook (a ".xlsx" file).

There are two clues here:

  • First, the data you're seeing clearly isn't human-readable text. A CSV file is just a text file formatted to a particular convention, whereas this looks very much like binary data intended only for machine use.
  • The very short snippet you posted happened to include the string "docProps/core.xml". If you search for that online, you'll get lots of references to the "Office Open XML" format used by modern versions of Microsoft Office. The files are structured as a zip file containing multiple XML files, and that's the name of one of the internal files in the zip.

The first thing you should do is add some validation to your code. Input from the user always needs validating, and in this case a check for the expected number of fields, or a mandatory header row, would have given you an error straight away.

The second thing you should do is either a) tell the user to export the spreadsheet as a CSV file, or b) re-write the code using a library that can read Excel files, such as PhpSpreadsheet.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • that's exactly what's going on , I remember I pasted my data in existed .xlsx file and manually changed the file name plus .csv format i thought this would parse my file to .csv format , i have a validation before upload however i'm just validating the file name .csv unfortunately this has to pass my validation . thank you very much that saved my day , if i may ask more , how can i validate the core format of a file not just the name using either JS or PHP ? thanks again – HAMMASI Apr 27 '21 at 08:31
  • @HAMMASI There is no universal way of validating a file format, because ultimately all files are just a string of bits. For a CSV file, though, it's really easy: if you always have the same header, that line should be identical in every file uploaded, and if it's not there, you can just give an error straight away. Then as you load each line, you can validate that it has the right number of columns, and maybe that columns you expect to be numbers are, etc. – IMSoP Apr 27 '21 at 09:08