-1

I know this sounds like a stupid question, but I can't get my head around this problem. Basically I want to quit the script only if the folder in the directory already exists but all I get is the blank page with the echo "la cartella esiste" I guess this is because of the exit function. What I want is to have the message displayed on the page itself just like the other errors displayed, but without carrying on with the code. Do you have any suggestion on how to proceed?

<?php

    
    require('db.php');

    if (isset($_POST['upload'])) {
        $batch_number = stripslashes($_REQUEST['batch_number']);
        $batch_number = mysqli_real_escape_string($con, $batch_number);
        $product_name = stripslashes($_REQUEST['product_name']);
        $product_name = mysqli_real_escape_string($con, $product_name);
        $vial_size = stripslashes($_REQUEST['vial_size']);
        $vial_size = mysqli_real_escape_string($con, $vial_size);
        $Sterile = $_POST['Sterile'];
        $Macchina = $_POST['Macchina'];
        $location = "immagini/$batch_number/";
        $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; 
        $allowTypes = array('jpg','png','jpeg', 'bmp');
        $img_name = array_filter($_FILES['image']['name']);
        $select = mysqli_query($con, "SELECT * FROM info_flaconi WHERE batch_number = '". $_REQUEST['batch_number']."'");
        if(file_exists($location) && is_dir($location)) {
            exit ("la cartella esiste");
            
        } else{
            mkdir("immagini/$batch_number/", 0777, true);
            echo "Cartella creata.";        

        }
                   
        if(!empty($img_name)){
            foreach($_FILES['image']['tmp_name'] as $key=>$val){
                //file upload path
                $fileName= $_FILES['image']['name'][$key];
                $fileName_tmp= $_FILES['image']['tmp_name'][$key];
                $targetPath = $location .$fileName;
                $ext=strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));
                $uploadDate = date('Y-m-d H:i:s');
                $uploadOk = 1;
                
                // Check whether file type is valid 
                
                if(in_array($ext, $allowTypes)){ 
                // Upload file to server 
                    if(move_uploaded_file($fileName_tmp, $targetPath)){
                        $sqlVal = $fileName;
                    }  else{
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "File coud not be uploaded.");
                        }
                }else{
                    $response = array(
                    "status" => "alert-danger",
                    "message" => "Only .jpg, .jpeg, .png and bmp file formats allowed.");
                }
                if(!empty($sqlVal)){                   
                    $query    = "INSERT INTO `info_flaconi` (batch_number, product_name,  vial_size, vial_image, uploaded_on, Sterile_Area, Macchina)
                    VALUES ('$batch_number', '$product_name', '$vial_size', '$sqlVal', '$uploadDate', '$Sterile', '$Macchina')";
                    $result   = mysqli_query($con, $query);
                    if($result){
                        $response = array(
                            "status" => "alert-success",
                            "message" => "Immagini caricate correttamente.");    
                    
                    }else{
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Files coudn't be uploaded due to database error.");
                    }  
                }
            }
        }else {
            // Error
            $response = array(
            "status" => "alert-danger",
            "message" => "Per favore seleziona le immagini da caricare.");
           
        }
    }                                       
    ?>  
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Import Immagini</title>
            <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
            <link rel="stylesheet" href="style_5.css">    
        </head>
        <body>
        <header>
            <div class="wrapper">
                <div class="logo">
                    <img src="biotech.png" alt="">
                </div>
        <ul class="nav-area">
        <li><a href="dashboard.php">Home</a></li>
        <li><a href="table/index.html">Contatti</a></li>
        <li><a href="logout.php">Logout</a></li>
        
        </ul>
        </div>
                <div class="inserimento">
                <h1> Inserisci flaconi da caricare </h1>
                <form action="" method="POST" enctype="multipart/form-data">
                    
                    
                    <input type = "file" name= "image[]"  id="chooseFile" multiple><br>
                    <label> Inserisci numero batch: </label><input type='text' name="batch_number" class='form-control' required placeholder="inserisci batch number"/><br>
                    <label> Inserisci prodotto: </label><input type='text' name="product_name" class='form-control' required placeholder="inserisci nome prodotto "/><br>
                    <label> Inserisci grandezza flacone: </label><input type='text' name="vial_size" class='form-control' required placeholder="inserisci formato flacone"/><br>
                    
                                         
                   
                   
                    
                    <select class='form-control' name="Sterile">

                        <option value="" >--Select--</option>
                        <option value="Sterile Area 1" >Sterile Area 1</option>
                        <option value="Sterile Area 2" >Sterile Area 2</option>
                        <option value="Sterile Area 3" >Sterile Area 3</option>
                        <option value="Sterile Area 4" >Sterile Area 4</option>
                        <option value="Sterile Area 5" >Sterile Area 5</option>
                        <option value="Sterile Area 6" >Sterile Area 6</option>
                        <option value="PDS" >PDS</option>
                    </select><br>

                    <select class="form-control" name="Macchina" autofocus="autofocus" required>
                   
                        <option value="" >--Select--</option>
                        <option value="Sedeneider" >Sedeneider</option>
                        <option value="Groheninger" >Groheninger</option>
                        <option value="Optrel400" >Optrel400</option>
                    </select>
                    <input type="submit" name="upload" value="Upload Image/Data"><br>
                </div>
                
                </form>
                     
                <?php if(!empty($response)) {?>
                <div class="alert <?php echo $response["status"]; ?>">
                   <?php echo $response["message"]; ?>
                </div>
            <?php }?>            
        </body>     
        
        </html>

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 2
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. Instead of building queries with string concatenation, always use [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) with [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). See [**this page**](https://phptherightway.com/#databases) and [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for some good examples. – Alex Howansky Feb 06 '22 at 00:21

1 Answers1

-1

It looks like you need to set the $response array for other code (which you haven't shown us) to display a message. One way would be to wrap the code you showed us in a do { ... } while (false) block (where "..." is all the code you showed above), and in the spot where you are currently calling exit(), change it to:

$response = array(
  "status" => "alert-danger",
  "message" => "la cartella esiste"
);
break;

The call to break will exit the loop and continue with the rest of the code that draws the page based on the contents of $response.

Here is your code, modified as described:

<?php
require('db.php');

do { // Begin one-time loop

if (isset($_POST['upload'])) {
    $batch_number = stripslashes($_REQUEST['batch_number']);
    $batch_number = mysqli_real_escape_string($con, $batch_number);
    $product_name = stripslashes($_REQUEST['product_name']);
    $product_name = mysqli_real_escape_string($con, $product_name);
    $vial_size = stripslashes($_REQUEST['vial_size']);
    $vial_size = mysqli_real_escape_string($con, $vial_size);
    $Sterile = $_POST['Sterile'];
    $Macchina = $_POST['Macchina'];
    $location = "immagini/$batch_number/";
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    $allowTypes = array('jpg', 'png', 'jpeg', 'bmp');
    $img_name = array_filter($_FILES['image']['name']);
    $select = mysqli_query($con, "SELECT * FROM info_flaconi WHERE batch_number = '" . $_REQUEST['batch_number'] . "'");
    if (file_exists($location) && is_dir($location)) {
        $response = array(
            "status" => "alert-danger",
            "message" => "la cartella esiste"
        );
        break;
    } else {
        mkdir("immagini/$batch_number/", 0777, true);
        echo "Cartella creata.";
    }

    if (!empty($img_name)) {
        foreach ($_FILES['image']['tmp_name'] as $key => $val) {
            //file upload path
            $fileName = $_FILES['image']['name'][$key];
            $fileName_tmp = $_FILES['image']['tmp_name'][$key];
            $targetPath = $location . $fileName;
            $ext = strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));
            $uploadDate = date('Y-m-d H:i:s');
            $uploadOk = 1;

            // Check whether file type is valid 

            if (in_array($ext, $allowTypes)) {
                // Upload file to server 
                if (move_uploaded_file($fileName_tmp, $targetPath)) {
                    $sqlVal = $fileName;
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "File coud not be uploaded."
                    );
                }
            } else {
                $response = array(
                    "status" => "alert-danger",
                    "message" => "Only .jpg, .jpeg, .png and bmp file formats allowed."
                );
            }
            if (!empty($sqlVal)) {
                $query    = "INSERT INTO `info_flaconi` (batch_number, product_name,  vial_size, vial_image, uploaded_on, Sterile_Area, Macchina)
                VALUES ('$batch_number', '$product_name', '$vial_size', '$sqlVal', '$uploadDate', '$Sterile', '$Macchina')";
                $result   = mysqli_query($con, $query);
                if ($result) {
                    $response = array(
                        "status" => "alert-success",
                        "message" => "Immagini caricate correttamente."
                    );
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "Files coudn't be uploaded due to database error."
                    );
                }
            }
        }
    } else {
        // Error
        $response = array(
            "status" => "alert-danger",
            "message" => "Per favore seleziona le immagini da caricare."
        );
    }
}
} while (false); // Loop will only execute once
?>  
kmoser
  • 8,780
  • 3
  • 24
  • 40
  • I have tried like you suggested but i get "Fatal error: 'break' not in the 'loop' or 'switch' context". I guess this is because of my php version. I posted the entire code, what do you mean by setting the $response array for the other code ? – francesco primerano Feb 06 '22 at 09:52
  • If you get that error, then you haven't put all your code in a `do { ... } while (false)` loop like I showed. It has nothing to do with your version of PHP. As for setting `$response`, it looks like that needs to be done so that the info in `$response` can be displayed on the page by other code that you did not show us. – kmoser Feb 06 '22 at 17:40