2

In my code you have a choice of either uploading a file or not and if you don't it should just end the code, but if you do upload a file and select an appropriate pack name(which is a database name they created) then it is suppose to run the code and submit to file directory. But my problem is that in this line of code

if($_FILES['packFiles']['error'] == UPLOAD_ERR_OK){

it checks if file is not empty or "No errors" and it runs the code inside but because i have a "multiple file upload" like this

<input type="file" name="packFiles[]" multiple>

it skips it and ends the code. I noticed that when i removed the multiple part and it worked perfectly. So my question is if there is a way to check if its not empty while allowing users to upload multiple files. Here is my code.

PHP

   <?php
session_start();

 if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
        $postMax = ini_get('post_max_size'); //grab the size limits...
        echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
        return $postMax;
    }

if(isset($_COOKIE['id'])){

    if($_SESSION['came_from_upload'] != true){

        setcookie("id", "", time() - 60*60);
        $_COOKIE['id'] = "";
        header("Location: developerLogin.php");
        exit;


    }
    echo "<h1> UPDATE PACK FILES INFORMATION</h1>";
    try{

        // new php data object 
        $handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
        //ATTR_ERRMODE set to exception
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        }catch(PDOException $e){
             die("There was an error connecting to the database");   

        }
       $userid = $_SESSION['id'];
       $stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
       $stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
       $stmt->execute();
        echo "<h2> Please select the pack name you want to update!</h2>";


   if($_SERVER['REQUEST_METHOD'] =="POST"){
         $token = $_SESSION['token'];

       if(!empty($_POST['packNameSelection'])){
            $price = addslashes(trim((int)$_POST['price']));
            $description = addslashes(trim($_POST['description']));
            $packname = addslashes(trim($_POST['pack_name']));

           $packNameSelection = $_POST['packNameSelection'];
           if(!empty($packname)){

               $stmtPacknameCheck = $handler->prepare("SELECT * FROM pack_profile WHERE pack_name = :packname");
               $stmtPacknameCheck->bindParam(':packname', $packname, PDO::PARAM_STR);
               $stmtPacknameCheck->execute();
               if($stmtPacknameCheck->fetch()){

                   echo "Packname entered is already in use... Please try again";
                   exit;
               }

               $stmtPackname = $handler->prepare("UPDATE pack_profile SET pack_name = :packname WHERE pack_name = :packNameSelection");
               $stmtPackname->bindParam(':packname', $packname, PDO::PARAM_STR);
               $stmtPackname->bindParam(':packNameSelection', $packNameSelection, PDO::PARAM_STR);
               $stmtPackname->execute();
           }

           if(!empty($price)){

               if(!ctype_digit($price)){

                    echo "PRICE ENTERED IS NOT AN INTEGER... PLEASE TRY AGAIN!";
                    exit;
                }

                $stmtPrice = $handler->prepare("UPDATE pack_profile SET pack_price = :price WHERE pack_name = :packNameSelection");
                $stmtPrice->bindParam(':price', $price, PDO::PARAM_INT);
                $stmtPrice->bindParam(':packNameSelection', $packNameSelection, PDO::PARAM_STR);
                $stmtPrice->execute();
           }

           if(!empty($description)){

               if(strlen($description) < 10){

                echo "Description field MUST to be GREATER than 10 characters!";
                exit;
            }

               $stmtDescription = $handler->prepare("UPDATE pack_profile SET pack_description = :description WHERE pack_name = :packNameSelection");
               $stmtDescription->bindParam(':description', $description, PDO::PARAM_STR);
               $stmtDescription->bindParam(':packNameSelection', $packNameSelection, PDO::PARAM_STR);
               $stmtDescription->execute();

           }

           if(!empty($_FILES['packFiles']['tmp_name'])){

               $stmtPackCheck = $handler->prepare("SELECT * FROM pack_profile WHERE pack_name = :packNameSelection");
               $stmtPackCheck->bindParam(':packNameSelection', $packNameSelection, PDO::PARAM_STR);
               $stmtPackCheck->execute();
               $resultPack = $stmtPackCheck->fetch();

               $file_name = "";
               $packid = $resultPack['pack_id'];
                foreach($_FILES['packFiles']['tmp_name'] as $key => $error){

                     if ($error != UPLOAD_ERR_OK) {
                        $errors[] = $_FILES['packFiles']['name'][$key] . ' was not uploaded.';
                        continue;
                    }
                    $pack_tmp = file_get_contents($_FILES['packFiles']['tmp_name'][$key]);
                $pack_filename = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['packFiles']['name'][$key]));
                     $pack_filename = strtotime("now")."_".$pack_filename;
                    $file_name .= $_FILES['packFiles']['name'][$key].",";
                    //Insert into file directory
                    $dir = "devPacks/" .$userid."/".$packid;
                    if(is_dir($dir)==false){

                        mkdir($dir, 0777, true);
                    }
                    if(!move_uploaded_file($_FILES['packFiles']['tmp_name'][$key],$dir.'/'.$pack_filename)){

                            die("an error occurred sending this file... Pleas try again later!");

                }


                }
           }

           die("ok");
       }else{

           echo "Please select valid value from dropdown list";
           exit;
       }
}
}


?>

<form method="post" enctype="multipart/form-data" autocomplete="off">

    <select name="packNameSelection">
        <option value="" disabled selected>Select Your Pack Name</option>
    <?php

        while($result = $stmt->fetch()){
     echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
   }


    ?>
    </select>

    <br>
    Pack Name: <input type="text" name="pack_name" placeholder="Your pack name">
    <input type="hidden" name="post_id">
    <br></br>
    Price: <input type="text" name="price" placeholder="If FREE enter 0">
    <br></br>

    Descripion: <textarea rows="4" cols="50" name="description" placeholder="Description..."></textarea>
    <br></br>
    Select Pack Files: <input type="file" name="packFiles[]" multiple>
    <br></br>
    <!--Select Pack Screenshots/Video: <input type="file" name="file[]" multiple> -->
<br></br>
    <input type="submit" name="submit">

</form>
2
  • you need to loop through $_FILES['packFiles'] so before this line if($_FILES['packFiles']['error'] == UPLOAD_ERR_OK){ you need to do something like foreach($_FILES['packFiles'] as $fileUpload){ Commented Aug 9, 2017 at 17:10
  • wait but what if the user doesn't submit any data? I will get an error cause files aren't there? Commented Aug 9, 2017 at 17:13

3 Answers 3

9

We can use this for a multiple file input:

if(!empty($_FILES['packFiles']['name'][0])){ 
    // do something
}
Sign up to request clarification or add additional context in comments.

Comments

2
// check and see whether is empty
if(!empty($_FILES['packFiles']['name'])){

    foreach($_FILES['packFiles']['tmp_name'] as $key => $error){
        $filename = file_get_contents($_FILES['packFiles']['tmp_name'][$key];
        // check file_get_contents
        if($pack_tmp = file_get_contents($filename) !== false){

            $pack_filename = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['packFiles']['name'][$key]));
            $pack_filename = strtotime("now")."_".$pack_filename;
            $file_name .= $_FILES['packFiles']['name'][$key].",";
            //Insert into file directory
            $dir = "devPacks/" .$userid."/".$packid;
            if(is_dir($dir)== false){
                mkdir($dir, 0777, true);
            }

            if(move_uploaded_file($_FILES['packFiles']['tmp_name'][$key],$dir.'/'.$pack_filename)){

            } else {
                die("an error occurred sending this file... Pleas try again later!");
            }
        }
    }
} else {
    //error any error message u want.
}

Check the file before foreach loop

3 Comments

Thank you but when it is "empty" i get this error "( ! ) Warning: file_get_contents(): Filename cannot be empty in C:\wamp64\www\MT\developer_packupdater.php on line 110 "
Because i have other inputs that i check if not empty and i run the code and i get that error. I didn't show the other code cause its too long and i wanted to focus on the file
I added this one to control the error if($pack_tmp = file_get_contents($filename) !== false)
0
if( isset($_FILES['packFiles']) and count($_FILES['packFiles']['tmp_name']) > 0 )
{
   // Your code
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.