Illusive bug - $_FILES and database

Discussion in 'PHP' started by Jeremy Benson, Jun 3, 2014.

  1. #1
    I'm working with $_FILES. I'm trying to send an images mimetype to the database based on what's in the array, but the mimetype just wont go. I'm not sure where the bug is. The block making the database call fires. I've used var_dump in it to check. I know the sql statement works, because I've cut it from phpmyadmin directly, and double checked by running the statement from phpmyadmin. I'm really stumped on this one, lol.

    
    if($_FILES['profilePicFile']['tmp_name'] != "")
       {
    
         if($_FILES['profilePicFile']['type'] == "image/jpg" || $_FILES['profilePicFile']['type'] == "image/jpeg" || $_FILES['profilePicFile']['type'] == "image/png" || $_FILES['profilePicFile']['type'] == "image/gif")
         {
           $movePath = "C:\wamp\www\users\\" . $handle . "\images\\";     
           $tmpName = $_FILES['profilePicFile']['tmp_name'];
           
           //rename the file
    
           if($_FILES['profilePicFile']['type'] == "image/jpg")
           {
           
             $_FILES['profilePicFile']['name'] = "profile.jpg";
               //Send mime to database
               
             $dbjpgPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);   
             
             try{
             
               $dbjpgPicMimeStatement = $dbjpgPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime` = ? WHERE `handle` = ?");
               $dbjpgPicMimeStatement->execute([$handle, ".jpg"]);
             
             }catch(\PDOException $e){  }
           }
    
           if($_FILES['profilePicFile']['type'] == "image/jpeg")
           {
    
             $_FILES['profilePicFile']['name'] = "profile.jpeg";
               //Send mime to database   
                $dbjpegPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
             try{
             
               
               $dbjpegPicMimeStatement = $dbjpegPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
               $dbjpegPicMimeStatement->execute([$handle, ".jpeg"]);
             
             }catch(\PDOException $e){  }
    
           }
    
           if($_FILES['profilePicFile']['type'] == "image/png")
           {
    
             $_FILES['profilePicFile']['name'] = "profile.png";
               //Send mime to database
                $dbpngPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
             try{
             
               $dbpngPicMimeStatement = $dbpngPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
               $dbpngPicMimeStatement->execute([$handle, ".png"]);
             
             }catch(\PDOException $e){  }
    
           }
    
           if($_FILES['profilePicFile']['type'] == "image/gif")
           {
    
             $_FILES['profilePicFile']['name'] = "profile.gif";
    
               //Send mime to database     
                $dbgifPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
             try{
             
               $dbgifPicMimeStatement = $dbgifPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
               $dbgifPicMimeStatement->execute([$handle, ".gif"]);
             
             }catch(\PDOException $e){  }
    
           }
    
           $fileName = $_FILES['profilePicFile']['name'];
           
           //Move the file
           move_uploaded_file($tmpName, $movePath . $fileName);
           
         }
       }
    
    PHP:
    $_FILES dump.

    
    array (size=2)
      'profilePicFile' =>
      array (size=5)
      'name' => string 'profile.jpeg' (length=12)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string 'C:\wamp\tmp\php62CF.tmp' (length=23)
      'error' => int 0
      'size' => int 25223
      'audioVideoFile' =>
      array (size=5)
      'name' => string '' (length=0)
      'type' => string '' (length=0)
      'tmp_name' => string '' (length=0)
      'error' => int 4
      'size' => int 0
    
    Code (markup):

     
    Jeremy Benson, Jun 3, 2014 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Well, first of, you're not assigning $handle anywhere, and you're not outputting anything in the catch() blocks, so even if you have an error, it won't tell you...
     
    PoPSiCLe, Jun 3, 2014 IP
  3. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #3
    Sorry, I assigned all the variables. I'll post the full code here. I just thought the error was there, because I've checked all the values. I never thought of outputting my error variable in the catch block, lol. Do I just echo $e?

    
    <?php
    
    require('sqldata.php');
    
    session_start();
    
    $idCheck = $_SESSION['ID'];
    
    $handle = NULL;
    
    $playerType = NULL;
    
       //Get user's handle
       
       $dbHandle = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
       
       try{
         
         $retrievedHandle;
         $dbHandleStatement = $dbHandle->prepare("SELECT `handle` FROM `users` WHERE `ID` = ?");
         $dbHandleStatement->execute([$idCheck]);
         $retrievedHandle = $dbHandleStatement->fetch();
         $handle = $retrievedHandle[0];
       
       }catch(\PDOException $e){  }
       
       $bio = $_POST['bio'];
       
       $bio = trim($bio);
    
    /*
       if($_POST['playerType'])
       {
       
         if($_POST['playerType'] == "audio")
         {
       
           $playerType = "audio";
       
         }elseif($_POST['playerType'] == "video")
         {
       
           $playerType = "video";
         
         }   
       
       }
    
    */
    
    
       //update the user's bio if it's not empty.
       
       if(!empty($bio) || $bio != "")
       {
       
         $dbUpdateBio = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);   
       
         try{
       
           $dbUpdateBioStatement = $dbUpdateBio->prepare("UPDATE `users` SET `bio`= ? WHERE `ID` = ?");
           $dbUpdateBioStatement->execute([$bio, $idCheck]);
       
         }catch(\PDOException $e){  }
       
       }
       
       //Process files
       
       
       if($_FILES['profilePicFile']['tmp_name'] != "")
       {
    
         if($_FILES['profilePicFile']['type'] == "image/jpg" || $_FILES['profilePicFile']['type'] == "image/jpeg" || $_FILES['profilePicFile']['type'] == "image/png" || $_FILES['profilePicFile']['type'] == "image/gif")
         {
           $movePath = "C:\wamp\www\users\\" . $handle . "\images\\";     
           $tmpName = $_FILES['profilePicFile']['tmp_name'];
           
           //rename the file
    
           if($_FILES['profilePicFile']['type'] == "image/jpg")
           {
           
             $_FILES['profilePicFile']['name'] = "profile.jpg";
               //Send mime to database
               
             $dbjpgPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);   
             
             try{
             
               $dbjpgPicMimeStatement = $dbjpgPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime` = ? WHERE `handle` = ?");
               $dbjpgPicMimeStatement->execute([$handle, ".jpg"]);
             
             }catch(\PDOException $e){  }
           }
    
           if($_FILES['profilePicFile']['type'] == "image/jpeg")
           {
    
             $_FILES['profilePicFile']['name'] = "profile.jpeg";
               //Send mime to database   
                $dbjpegPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
             try{
             
               
               $dbjpegPicMimeStatement = $dbjpegPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
               $dbjpegPicMimeStatement->execute([$handle, ".jpeg"]);
             
             }catch(\PDOException $e){  }
    
           }
    
           if($_FILES['profilePicFile']['type'] == "image/png")
           {
    
             $_FILES['profilePicFile']['name'] = "profile.png";
               //Send mime to database
                $dbpngPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
             try{
             
               $dbpngPicMimeStatement = $dbpngPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
               $dbpngPicMimeStatement->execute([$handle, ".png"]);
             
             }catch(\PDOException $e){  }
    
           }
    
           if($_FILES['profilePicFile']['type'] == "image/gif")
           {
    
             $_FILES['profilePicFile']['name'] = "profile.gif";
    
               //Send mime to database     
                $dbgifPicMime = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
             try{
             
               $dbgifPicMimeStatement = $dbgifPicMime->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
               $dbgifPicMimeStatement->execute([$handle, ".gif"]);
             
             }catch(\PDOException $e){  }
    
           }
           
           
           $fileName = $_FILES['profilePicFile']['name'];
           
           //Move the file
           move_uploaded_file($tmpName, $movePath . $fileName);
           
         }
       }
       
       if($_FILES['audioVideoFile'])
       {
       
           $movePath = "C:\wamp\www\users\\" . $handle . "\uploads\\";     
           $tmpName = $_FILES['profilePicFile']['tmp_name'];
    
           if($_FILES['audioVideoFile']['type'] == "video/ogg" || $_FILES['profilePicFile']['type'] == "audio/ogg" || $_FILES['profilePicFile']['type'] == "audio/mp3" || $_FILES['profilePicFile']['type'] == "audio/wav" || $_FILES['profilePicFile']['type'] == "video/mp4")
           {
           
             //Move the file
             move_uploaded_file($tmpName, $movePath . $fileName);
           
           }
       }
    
         var_dump($_FILES);
         
       //edit player options
       
       if(!is_null($playerType))
       {
       
         $dbPlayerType = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
         
         try{
         
           $dbPlayerTypeStatement = $dbPlayerType->prepare("UPDATE `profilesettings` SET `playerType`= ? WHERE `handle` = ?");
           $dbPlayerTypeStatement->execute([$playerType, $handle]);
         
         }catch(\PDOException $e){  }
       }
       
    //   header("Location: ../../../dashboard.php?option=edit");
    //   exit;
    ?>
    
    PHP:
     
    Jeremy Benson, Jun 3, 2014 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    1. Don't create more than one instance of PDO unless you're connecting to different databases.
    2. Don't ever ever ever ever rely on the "type" in the $_FILES array. It comes straight from the user and can't ever be trusted. Right now I can't upload a PHP file with an image mime type, and it will save on your server, even conserving the .php extension.
    3. Instead, use the file extension and validate that.
    4. $e is an instance of Exception. Use $e->getMessage() to see the error message.
    5. You probably won't ever need is_null(). Doing $playerType !== null is faster and doesn't add another function call.
     
    nico_swd, Jun 3, 2014 IP
  5. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #5
    First off, you should try doing error-display for PHP - ie, put the following at the top of the file:
    
    ini_set('display_errors',1);
    error_reporting(E_ALL);
    
    Code (markup):
    Also, you don't blank assign a variable in PHP using $retrievedHandle; - you either assign an empty variable, to have the variable available for later ($retrievedHandle = '';) or not at all until you need it - so you can delete that line in that try{}.
    Second, assigning NULL to a variable just adds complexity - just do $variable = ''; and check for empty($variable)
     
    PoPSiCLe, Jun 3, 2014 IP
  6. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #6
    You could probably condense that to the following:
    
    <?php
    session_start(); //always at the very top of the file
    
    require('sqldata.php');
    
    //$idCheck = $_SESSION['ID']; // this will fail and throw an error if the SESSION-value isn't set
    //you should do like this:
    $idCheck = (isset($_SESSION['ID']) ? $_SESSION['ID'] : '');
    
    $handle = '';
    $playerType = '';
    
    $dbconnect = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
      $userHandle = $dbconnect->prepare("SELECT handle FROM users WHERE ID = ?");
      try {
      $userHandle->execute([$idCheck]); //note that this will fail unless you're running on the latest PHP-version
      $retrievedHandle = $userHandle->fetch();
      $handle = $retrievedHandle[0];
      } catch(PDOException $e) { 
      echo $e->getMessage(); //this is not recommended, since it will output sensitive information, depending on the error
      }
    
      $bio = (isset($_POST['bio'])) ? trim($_POST['bio']) : '';
    
      //update the user's bio if it's not empty.
      if (!empty($bio)) {
      $updateBio = $dbconnect->prepare("UPDATE users SET bio = ? WHERE ID = ?");
      try {
      $updateBio->execute([$bio, $idCheck]);
      } catch(PDOException $e) {
      echo $e->getMessage();
      }
      }
    
    //Process files
      if ($_FILES['profilePicFile']['tmp_name'] != '') {
      if($_FILES['profilePicFile']['type'] == 'image/jpg' || $_FILES['profilePicFile']['type'] == 'image/jpeg' || $_FILES['profilePicFile']['type'] == 'image/png' || $_FILES['profilePicFile']['type'] == 'image/gif') {
      $movePath = 'C:\wamp\www\users\\' . $handle . '\images\\'; // this is very bad coding - you shouldn't use defined filesystems - you should assign this based on your webservers config
      $tmpName = $_FILES['profilePicFile']['tmp_name'];
    
      //rename the file
      $filetypearray = array(1 => 'image/jpg',2 => 'image/jpeg', 3 => 'image/png', 4 => 'image/gif');
    
      foreach ($filetypearray as $key => $value) {
      if ($_FILES['profilePicFile']['type'] == $value) {
      $filetype = explode('/',$value);
      $executearray = array(1 => $handle, 2 => '.'.$filetype[1]);
      }
    
      }
    
      $assignMime = $dbconnect->prepare("UPDATE profilesettings SET profileImageMime = ? WHERE handle = ?");
    
      try {
      $assignMime->execute($executearray);
      } catch (PDOException $e) {
      echo $e->getMessage();
      }
    
    
      $fileName = $_FILES['profilePicFile']['name'];
    
    //Move the file
      move_uploaded_file($tmpName, $movePath . $fileName);
      }
      }
    
      if ($_FILES['audioVideoFile']) {
    
      $movePath = "C:\wamp\www\users\\" . $handle . "\uploads\\";  
      $tmpName = $_FILES['profilePicFile']['tmp_name'];
    
      if($_FILES['audioVideoFile']['type'] == 'video/ogg' || $_FILES['profilePicFile']['type'] == 'audio/ogg' || $_FILES['profilePicFile']['type'] == 'audio/mp3' || $_FILES['profilePicFile']['type'] == 'audio/wav' || $_FILES['profilePicFile']['type'] == 'video/mp4') {
    
      //Move the file
      move_uploaded_file($tmpName, $movePath . $fileName);
    
      }
      }
    
    //edit player options
    
      if (!empty($playerType)) { // this will never trigger with the above code
      $playerType = $dbconnect->prepare("UPDATE profilesettings SET playerType = ? WHERE handle = ?"); 
    
      try {
      $playerType->execute([$playerType, $handle]);
      } catch(PDOException $e){ 
      echo $e->getMessage();
      }
    }
    
    ?>
    
    PHP:
    Note, this hasn't been tested, so there are probably a couple minor problems, but more or less, it should work
    Also note that I've added a couple comments, which you shold read, as they are for specific stuff in the code.
    I've not done anything about the filetype-problem, that's for another run
     
    PoPSiCLe, Jun 3, 2014 IP
  7. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #7
    Awesome. I remember validating the extension when I was learning all this last time. Since I've gotten better at reading arrays and working with them. I thought I was being smart seeing that type was in there... I'll revert back and grab the extension. Also if I'm only supposed to use one database object for each query in a script I've got a lot of code to condense, haha. I'll work on that though. Thanks again for all the help. Life saving tips here :)
     
    Jeremy Benson, Jun 4, 2014 IP
  8. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #8
    I've fixed this bit of code and all my other scripts using PDO, lol. I had a question about filesystems.

    
    $movePath = "C:\wamp\www\users\\" . $handle . "\uploads\\";  //This has to change.
    
    PHP:
    The reason I wrote the line above like that was because I couldn't figure out the proper way. I was gonna save it until later and find out how to ready all those paths for a live run. I tried writing it like I would in html..

    users\username\uploads
    Code (markup):
    but I get a weird error in Expression. Says no such file in steps/users/scripts/users/scripts/username/uploads... (pseudo representation of the error), but it's way off...

    Here's the new script. A lot cleaner thanks to you guys :)

    
    <?php
    
    session_start();
    
    require('sqldata.php');
    
    $idCheck = (isset($_SESSION['ID']))?$_SESSION['ID']:1;
    
    $handle = "";
    
    $playerType = "";
    
       //Get user's handle
       
       $dbConnect = new PDO($dsn, $dbUserName, $dbPassword, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
       
       try{
       
         $dbHandleStatement = $dbConnect->prepare("SELECT `handle` FROM `users` WHERE `ID` = ?");
         $dbHandleStatement->execute([$idCheck]);
         $retrievedHandle = $dbHandleStatement->fetch();
         $handle = $retrievedHandle[0];
       
       }catch(\PDOException $e){  }
       
       $bio = (IsSet($_POST['bio']))?$bio = trim($_POST['bio']): $bio = "";
         
       //update the user's bio if it's not empty.
       
       if(!empty($bio))
       {   
       
         $dbUpdateBioStatement = $dbConnect->prepare("UPDATE `users` SET `bio`= ? WHERE `ID` = ?");
    
         try{
         
           $dbUpdateBioStatement->execute([$bio, $idCheck]);
       
         }catch(\PDOException $e){  }
       
       }
       
       //Process profile pic.
       
       if($_FILES['profilePicFile']['tmp_name'] != "")
       {
         //Where the file is and where it will go
         $tmpName = $_FILES['profilePicFile']['tmp_name'];
         $movePath = "C:\wamp\www\users\\" . $handle . "\images\\";  //This has to change.
         //Retrieve the file extension
         $extension = $_FILES['profilePicFile']['name'];
         $positionDot = strpos($extension,'.');
         $extension = substr($extension, $positionDot, strlen($extension));
         //Rename the file
         $_FILES['profilePicFile']['name'] = "profile" . $extension;
         $fileName = $_FILES['profilePicFile']['name'];
         
         //If the extension is right send it to the database.
         if($extension == ".jpg" || $extension == ".jpeg" || $extension == ".png" || $extension == ".gif" )
         {       
         
           $dbExtension = $dbConnect->prepare("UPDATE `profilesettings` SET `profileImageMime`= ? WHERE `handle` = ?");
           
           try{
           
             $dbExtension->execute([$extension, $handle]);
           
           }catch(\PDOException $e){  }
           
           //Move the profile pic.
           
           move_uploaded_file($tmpName, $movePath . $fileName);
         }
       
       }
       
       
       //Process vide audio file
       
       if($_FILES['audioVideoFile']['tmp_name'] != "")
       {
    
         $tmpName = $_FILES['audioVideoFile']['tmp_name'];
         $movePath = "C:\wamp\www\users\\" . $handle . "\uploads\\";  //This has to change.
         
         $extension = $_FILES['audioVideo']['name'];
         $positionDot = strpos($extension,'.');
         $extension = substr($extension, $positionDot, strlen($extension));
           
         //If the file extension is right upload the files to user's upload directory
         if($extension == ".mp3" || $extension == ".mp4")
         {
           
           move_uploaded_file($tmpName, $movePath . $_FILES['profilePicFile']['name']);
         
         }
       
       }
         
       //edit player options
       
       $playerType = (IsSet($_POST['playerType']))? $_POST['playerType']: "";   
       
       if(!empty($playerType))
       {
           
         try{
         
           $dbPlayerTypeStatement = $dbConnect->prepare("UPDATE `profilesettings` SET `playerType`= ? WHERE `handle` = ?");
           $dbPlayerTypeStatement->execute([$playerType, $handle]);
         
         }catch(\PDOException $e){  }
       }
      
    //   header("Location: ../../../dashboard.php?option=edit");
    //   exit;
    ?>
    
    
    PHP:
     
    Jeremy Benson, Jun 5, 2014 IP
  9. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #9
    Here's a hint: you never use backslashes in a HTML/PHP-file to represent filesystems (apart from gettting local files on a Windows machine, but you shouldn't really ever need to do that)
    Forward slashes: / is the correct way. If you need absolute paths, you do (if your webpage is in the folder C:\webhost\www\this_is_the_domain - you do /this_is_the_domain/ and if you need a subfolder, you use /this_is_the_domain/sub_folder
    Remember that if you're using files from subfolders etc, you need to prefix the path with a / <- this starts at the root, while this_is_the_domain/sub_folder starts from the sub_folder you're already in.
     
    PoPSiCLe, Jun 9, 2014 IP