user2090618
user2090618

Reputation: 55

PHP read lines not working on some computers but works on most

So im reading an CSV file and splitting it apart to get email,name,last name, however this outputs differently on different computers in my platform, let's say when I upload the same file it reads 38 lines and save them. However in 2 specific computers it reads only 1.

Before I was reading only TEMP file, but now im saving it to a directory and reading from there, however the problem is still here, I compared the file size and is the same even the content. Is this a PHP bug ?

<?php
global $user;
if(isset($_POST['submit'])) {

    if ($_FILES['file']['tmp_name']) {

        $nome = $_POST['nome'];
        $file = $_FILES['file']['tmp_name'];

        $user->criarLista($nome, $file);
    } else {
        $user->mensagem(1, "Não existe nenhum ficheiro");
    }

}
?>         

public function criarLista($nome,$file){

        // ADDED TO SAVE THE FILE IN THE SYSTEM AND READ FROM IT 
        if(file_exists("uploads/lista.txt")){ unlink("uploads/lista.txt"); }
        move_uploaded_file($file, "uploads/lista.txt");

        $file = file_get_contents("uploads/lista.txt");



        $user = $this->user;
        $get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
        $fetch = $get->fetch_array(MYSQLI_ASSOC);
        $user_id = $fetch['id'];

        if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
            $insert->bind_param("is", $user_id,$nome);
            $insert->execute();
            $list_id = $insert->insert_id;

            $file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
            $file = strip_tags($file);
            $lines = file("uploads/lista.txt");

            $emails = array();
            $fnames = array();
            $lnames = array();
            $linha = 0;
            foreach($lines as $line) {

                if($linha == 0){

                }else{
                echo $Linha."</br>";
                    if (strpos($line, ',') !== false) {

                        $arr = explode(",", $line);
                        // Email \ FNAME | LAST

                        $emailx = trim($arr[0]);
                        $emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
                        array_push($emails,$emailx); 


                        if(isset($arr[1])){
                           $fname = trim($arr[1]);
                           $fname = str_replace('"','',$fname);
                           array_push($fnames,$fname); 
                        }

                        if(isset($arr[2])){
                           $lname = trim($arr[2]);
                           array_push($lnames,$lname); 
                        }

                    }else{
                       array_push($emails,trim($line)); 
                    }  

                }   

                $linha++;

            }

            array_map('trim', $emails);
            array_map('trim', $fnames);
            array_map('trim', $lnames);

            $emails = implode(",",$emails);
            $fnames = implode(",",$fnames);
            $lnames = implode(",",$lnames);

            if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
                $insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
                $insert_list->execute();

                $this->mensagem(2,"Lista adicionada com sucesso");

            }else{
                echo 
                '
                <div class="alert alert-danger">
                    Erro: '.$this->connect->error.'
                </div>
                ';
            }


        }else{

            echo 
            '
            <div class="alert alert-danger">
                Erro: '.$this->connect->error.'
            </div>
            ';

        }    

    }

FIXED this adding this on top of the function :

        ini_set('auto_detect_line_endings',true);

Upvotes: 1

Views: 64

Answers (1)

Apps-n-Add-Ons
Apps-n-Add-Ons

Reputation: 2146

I am not sure this is an 'answer' to what is going on, though it is what I had to do to fix an issue with a Mac user sending files.

What I found was that, every time he did an upload, it would send a .zip file, not just the file (like the PCs did). I did not have other Mac users to test against, so, again, I can't say this is exactly the issue you have, but I trust it will at least help in your search.

Note that I had to chop a lot of code out of this (where I was doing various other functions with the database, etc.), so this may not run directly, but I think I closed all the 'ifs' and such - or you can figure it out (if not, let me know and I'll go through it again).

Hope this helps!

$save_file = basename($_FILES["fileToUpload"]["name"]);
$zipfile='maps/'.$save_file;  // location of a temp location (stops double uploads)
$alert_upload_file_exists = "Uploaded file exists!";   
$alert_upload_successful = "UPLOAD SUCCESSFUL"; 
$action_failed_text = "Action FAILED";
if(file_exists($zipfile) && (empty($_GET['overwrite']) || $_GET['overwrite'] == 'false')) 
    die($alert_upload_file_exists);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $zipfile))
{
    // I found this mac to be sending a .zip file, not a standard one..... :(
    $uploadOk = 0;
    $mac_file = 0;
    if($basename = basename($_FILES["fileToUpload"]["name"],".zip"))
    {
        $zip = new ZipArchive;
        if($zip->open($zipfile) === true){
            // echo "basename is $basename<BR>";
            for($i = 0; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                $fileinfo = pathinfo($filename);
                // look for the file we really want (in our case, any sort of img file)
                if($fileinfo['basename'] == $basename . '.png' || $fileinfo['basename'] == $basename . '.jpg'  || $fileinfo['basename'] == $basename . '.gif') {
                    $imgfile = $_GET['loc_data_id'].".".$fileinfo['extension'];
                    $files[]=$fileinfo['basename'];
                //      echo "file added to the list <BR>";
                }
                 //  echo "filename is $filename, basename is ->".$fileinfo['basename']."<- fileinfo = ";print_r($fileinfo);
                 // CHECK TO SEE IF THIS WAS THE 'WEIRD' MAC FILE               
                 if($fileinfo['basename'] == "__MACOSX") 
                     $mac_file = 1;
                //   echo "mac_file is $mac_file ";
            }
            if(($imglist = array_keys(array_flip(preg_grep('/^.*\.(jpg|jpeg|png|gif)$/i',$files))))
            {
            //          echo "imglist = ";print_r($imglist);
            //  echo "files = ";print_r($files);
                foreach($files as $key => $value)
                {
                    if ($imglist[0]==$value) {$file = $imgfile;}
                    $upgrade += file_exists('maps/'.$file);
                    //  echo "imgfile is $imgfile, file is $file upgrade is $upgrade and value is ".$basename."/".$value." ............";
                    // more 'FUNNY BUSINESS' to work the Mac file....
                    if($mac_file){
                        $extracted = $zip->extractTo('maps/',$basename."/".$value);
                        rename("maps/$basename/$value","maps/$file");   
                    }
                    else {
                        $extracted = $zip->extractTo('maps/',$value);
                        rename("maps/$value","maps/$file"); 
                    }
                }
                // AND A BIT MORE.....
                if($mac_file){
                    rmdir ("maps/$basename");
                }
                $zip->close();
                $imgcount=0;$mapcount=0;$uploadOk=1;
                $html = file_get_html('maps/'.$mapfile);
                $imgck = strpos($html,'<img ');
                if(($imgck===false) || $imgck<>0) {
                    $uploadOk += 2;
                }
                //      echo "uploadOk is $uploadOk<br>";
                if($uploadOk==1)
                {
                    $mapname = pathinfo('maps/'.$mapfile);
                    //  echo "mapfile is $mapfile, mapname = ";print_r($mapname);
                }
            }
            else $uploadOk += 20;
        }
    }
    if($uploadOk==1) echo basename($_FILES["fileToUpload"]["name"])." ".$alert_upload_successful;
    else echo $action_failed_text . " ".$uploadOk;
    // delete the original .zip file (and any that are in the 'maps/' folder)
    array_map('unlink', glob("maps/*.zip"));
}
else
{
    echo "Sorry, there was an error uploading your file.";
    echo "temp name is " . $_FILES["fileToUpload"]["tmp_name"]. " save file is ". $save_file."<br>";
}

Upvotes: 1

Related Questions