简体   繁体   中英

Reading a CSV file from an unknown path, php

I have an php aplication that needs to import a CSV to mysql. But i only can import if the path is in the code. But i don't want it that way. I don't know were my cliente have the .CSV file. Can you help me? This is my code:

<form enctype='multipart/form-data' action="" method='post'onSubmit='getPath();'>
    <input type="file" name="file" /> 
    <input type='submit' name='submit' value='Importar'/>
</form>

<?php

$conexao = mysql_connect ("localhost", "root", "") or die (mysql_error());
$bd = mysql_select_db ("wcfleet_demo"); 

if (isset ($_POST['submit'])) 
    {       


        $file = $_FILES ['file'] ['name'];

        $filepath="C:\\xampp\htdocs\wecreatefleet\\";
        $msg = $filepath."".$file; //bind
        $handle = fopen ($msg, "r");
        $i= 0;

        //$caminho = "C:\\xampp\htdocs\wecreatefleet\\teste.csv";   
        //$abraArq = fopen ($caminho, "r");

        if (!$handle) 
            {
                echo ("<p> Arquivo não encontrado! </p>");
            }
        else
            {
                while (($valores = fgetcsv ($handle, 100000, ";"))!== false) 
                {
                    $lines = file($msg);

                    if($i>=8)
                    {                       
                        $line = explode (';', $lines[$i]);          
                        $sql = "INSERT INTO via_verde (identificador, matricula, referencia, data_entrada, hora_entrada, entrada, data_saida, 
                                            hora_saida, saida, valor, valor_desconto, taxa_iva, operador, servico, data_pagamento, cartao_n) 
                                            VALUES ('$line[0]', '$line[1]', '$line[2]', '$line[3]', '$line[4]', '$line[5]', '$line[6]', '$line[7]', 
                                                    '$line[8]', '$line[9]', '$line[10]', '$line[11]', '$line[12]', '$line[13]', '$line[14]', '$line[15]')";     
                        mysql_query ($sql) or die (mysql_error());                          
                    }
                    $i++;
                }   
                fclose ($handle);   
                mysql_close($conexao);
                echo "Processo finalizado.";        
            } 
    }  

You should probably be able to use the filepath of the uploaded file as the source for fopen - $_FILES['file']['tmp_name'] like this - though it is not tested. Unless you also need to save the uploaded csv file then there is not eveen a need to use move_uploaded_file as you would normally with file uploads.

The obligatory "do not use mysql_* functions" - they are deprecated and offer no protection against sql injection. Preferably use mysqli or PDO so that you can take advantage of prepared statements

<?php
    /* logic tests to ensure there is data present */
    if( isset( $_POST['submit'], $_FILES['file'] ) ) {       

        /* assign the tmp_name of the uploaded file to a variable */
        $tmp  = $_FILES['file']['tmp_name'];
        /* open a file handle on the temp file */
        $handle = fopen( $tmp, "r" );
        $i=0;

        if ( !$handle ) {
            echo "<p> Arquivo não encontrado! </p>";
        } else {
            /* only open db connection if there are no problems */
            $conexao = mysql_connect ("localhost", "root", "") or die ( mysql_error() );
            $bd = mysql_select_db ("wcfleet_demo"); 

            while ( $valores = fgetcsv( $handle, 100000, ";" )!== false ) {
                $lines = file( $msg );

                if( $i >= 8 ) {                       
                    $line = explode ( ';', $lines[$i]);          
                    $sql = "INSERT INTO via_verde (identificador, matricula, referencia, data_entrada, hora_entrada, entrada, data_saida, 
                                        hora_saida, saida, valor, valor_desconto, taxa_iva, operador, servico, data_pagamento, cartao_n) 
                                        VALUES ('$line[0]', '$line[1]', '$line[2]', '$line[3]', '$line[4]', '$line[5]', '$line[6]', '$line[7]', 
                                                '$line[8]', '$line[9]', '$line[10]', '$line[11]', '$line[12]', '$line[13]', '$line[14]', '$line[15]')";     
                    mysql_query( $sql ) or die ( mysql_error() );                          
                }
                $i++;
            }   
            fclose( $handle );   
            mysql_close( $conexao );
            /* delete the temp file */
            @unlink( $tmp );

            echo "Processo finalizado.";        
        }
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM