Search code examples
phpmysqlpassword-hash

Load Data Local Infile with password_hash


I am trying to upload CSV to a table. However, the passwords are in plain text which i would like convert to password_hash in the process. Please help.

$sql = "LOAD DATA LOCAL INFILE '".$mylfile."'
   INTO TABLE parentstudent
   FIELDS TERMINATED BY ','
   OPTIONALLY ENCLOSED BY '\"' 
   LINES TERMINATED BY '\n' 
   IGNORE 1 LINES 
   (parentstudent_id, @parent_id, student_id, school_id)
   set parent_id =".password_hash."'(parent_id,".PASSWORD_DEFAULT.")";

$con=mysqli_connect("localhost","root","","confapp");

$result = mysqli_query($con, $sql);

Solution

  • Assuming there is a file called clearpwords.csv with contents like this:

    1,test,1,1
    2,testtest,2,1
    

    The following program will hash the second column.

    <?php
    // this is needed for any significant number of inputs to password_hash()
    set_time_limit(0);
    
    $infile = "clearpwords.csv";
    $myfile = "hashedpwords.csv";
    
    $reader = fopen($infile, 'r');
    $writer = fopen($myfile, 'w');
    $buffer = '';
    
    while ($line = fgetcsv($reader)) {
        $line[1] = password_hash($line[1], PASSWORD_DEFAULT);
    
        $buffer .= implode(',', $line) . "\n";
    
        if (strlen($buffer) > 1024) {
            fwrite($writer, $buffer);
            $buffer = '';
        }
    }
    
    fwrite($writer, $buffer);
    fclose($reader);
    fclose($writer);
    

    It will create a file called myfile.csv that looks like this.

    1,$2y$10$KwG1S4w7T4ov71bFSsKhlOW2CpFrMurtZRz3az94o7BX70pmohCb.,1,1
    2,$2y$10$zQkH5vDIYLCqkUxxaqH6nuZ67fXj71XiBVjxztvst.dtvSlFqjDou,2,1
    

    You can now run your script on myfile.csv

    $sql = "LOAD DATA LOCAL INFILE '".$mylfile."'
            INTO TABLE parentstudent
            FIELDS TERMINATED BY ','
            OPTIONALLY ENCLOSED BY '\"' 
            LINES TERMINATED BY '\n' 
            IGNORE 1 LINES 
            (parentstudent_id, @parent_id, student_id, school_id)";
    
    $con = mysqli_connect("localhost", "root", "", "confapp");
    $result = mysqli_query($con, $sql);
    

    Note that password_hash is only available in PHP 5.5 and above. If you are running a version prior to this and upgrading is not an option use the crypt function instead.

    Don't be tempted to use SHA-* or MD-*.