Delete the temp file, if it is invalid

My original posting here, in the PHP section said this:
I’m looking for help adding to this Upload Form. Currently if you upload the wrong size or wrong format the corresponding error message appears, but the erroneous action can still proceed.

How can I halt the ‘Submit’ until the correct file format is chosen?
How can I halt the ‘Submit’ until the correct size is chosen?

Here’s some of the Form’s html:

    <input class="button-form3" type="submit" value="Submit >>" name="B3" />
    <input class="upload-form-input" type="hidden" name="form_submitted" value="yes" />

Here’s the Form’s php code:

    if ($form_submitted == 'yes')
    {
    $allowedExts = array("doc", "docx", "gif", "jpeg", "jpg", "txt", "rtf", "pdf", "png", "txt");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = strtolower( end($temp) );

    if(!in_array($extension,$allowedExts) && $_FILES["file"]["name"] != "" )
    {
    echo ("<div id=\"errorMessage\">Error: Invalid File Name </div>");
   }
    else if ($_FILES["file"]["size"] >= 100000)
    {
    echo ("<div class=\"errorMessage1\">Error: Image File Size Exceeds Limit     </div>");
    }
    $length = 20;
    $randomString = (time());
    $thumbnail = $_SESSION['user_id'] . '-' . $randomString . "." . $extension;
    $uploadedFile = $_FILES["file"]["tmp_name"];

    if($uploadedFile != NULL)
    {
    move_uploaded_file($uploadedFile, "upload/" . $thumbnail);
    }
    else
    {
    copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
    }

    $_SESSION['thumbnail'] = $thumbnail;
    $file_location = '<a href="http://www....com/upload/' . $thumbnail . '">' . $thumbnail     . '</a>';
    }

I was referred to the Javascript section, and it was suggested:
“you are just printing “Error: Invalid File Name”. At this point, it should still be in a temp directory (normally, it remains there JUST long enough for it to be moved elsewhere.) Instead of moving the file to another folder, just delete it (if the temp folder doesn’t already do that automatically.)”

So, can PHP code be added to delete an incorrect file format, or incorrect file size, when the appropriate error appears? (so that I can change the error messages to essentially say “upload blocked try again”). If so, can you provide a code example, please?

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

Usually it happens automatically so you don’t need anything in that instance. It is when you want to keep the file that you need the code to copy it to somewhere out of the temp folder in order that it NOT get deleted.

Thank you for your reply.
The code above moves the uploaded file to /uploads folder, so currently nothing is actually getting deleted, everything is moving to the /uploads folder.
So, I guess the additional code I need should only move files, from the Temp folder to the /uploads folder, that do not exceed the file size limit, and that are the correct file format? All other files should trigger an error message? Would that be the solution to getting only appropriate files into the /uploads folder?

yes

Thank you for your reply.
Can someone please provide an example of code that would only move files, from the Temp folder to the /uploads folder, that do not exceed the file size limit, and that are the correct file format, and then generate an error message for the all files that are not moved? I look forward to any assistance, thanks.

Put the code you have in a function then call the function. After each error message return false and only return true if the code gets to the end. If the function call returns false then you know that an error message was produced and the file wasn’t moved. If it returns true you know the file is valid and has been saved.

Thanks alot for that explanation/clarification. That makes sense. Much appreciated.
I don’t have the skill level to accomplish that. I’m hoping to get some coding help, if possible.
Any additional guidance would be greatly appreciated.

It’s really a good idea to avoid running all this php within html. Instead of echoing errors as they are found, set them to a variable. You then can check if “that” variable isset() to determine if you are moving temp or copying the NoInfo image. Sample code below

<?php
if (isset($_POST['upload'])):

    if(isset($_FILES) && $_FILES['file']['error'] != 0){
    
        //Unable to upload file to temp
        $error = '<div id="errorMessage">Error: Unable to upload your file </div>';
            
    }else{
    
        $allowedExts = array("doc", "docx", "gif", "jpeg", "jpg", "txt", "rtf", "pdf", "png", "txt");
        $temp = explode(".", $_FILES['file']['name']);
        $extension = strtolower( end($temp) );
        
        if(!in_array($extension,$allowedExts)){
        
            $error = '<div id="errorMessage">Error: Invalid File Name </div>';
            
        }elseif($_FILES['file']['size'] >= 100000){
        
            $error = '<div class="errorMessage1">Error: Image File Size Exceeds 100 KB Limit </div>';
            
        }
        
        // $randomString needed regardless of passing tests so put outside error condition
        $randomString = time();
        
        if(!isset($error)){            
            $uploadedFile = $_FILES['file']['tmp_name'];
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . "." . $extension;        
            move_uploaded_file($uploadedFile, "upload/" . $thumbnail);             
        }else{            
            //Make sure NoInfo image has png extension   
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
            copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
        }
        
        $_SESSION['thumbnail'] = $thumbnail;
        $file_location = '<a href="http://www....com/upload/' . $thumbnail . '">' . $thumbnail     . '</a>';
    }
endif;
?>
<html>
<body>
<?php
//echo error or file_location within html
if(isset($error)){echo $error;}
if(isset($file_location)){echo $file_location;}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="upload" value="submit" />
</form>
</body>
</html>

Thanks for your reply. Much appreciated, however, I’m sorry I don’t really understand “check if “that” variable isset()”, but I went ahead and replaced my code with your:

if (isset($_POST['upload'])):
etc.....

And added this to the html Form page:

<?php
//echo error or file_location within html
if(isset($error)){echo $error;}
if(isset($file_location)){echo $file_location;}
?>

But because I already have the lines:

<form enctype="multipart/form-data" action="uploader.php" method="POST"> 
<input class="button-form3" type="submit" value="Submit >>" name="B3" />
<input class="upload-form-input" type="hidden" name="form_submitted" value="yes" />

I didn’t add your:

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="upload" value="submit" />

And it didn’t work successfully. No errors appeared when I uploaded the wrong file format and
the NoInfoAvailable.png image didn’t appear, as before when no file was uploaded.

Any additional guidance will be greatly appreciated.

Yes I was speaking descriptive rather than literal. In my example I set those error messages to the variable $error so “that” variable is $error and that final condition is

if(!isset($error)){

SO IF $error is NOT SET move_uploaded_file()

As far as not working, you need to apply the script so it matches your form.

Try changing the first wrapper condition from

if (isset($_POST['upload'])):

TO

if (isset($_POST['B3'])):

OR your hidden input name if you wish

if (isset($_POST['form_submitted'])):

…so it matches your form

Thanks again for your reply. I really appreciate the help.
I changed it to:
if (isset($_POST[‘form_submitted’])):
and upon testing it seems that file formats listed appear in the upload/ folder and any other file type does not - thanks. However, no error appears when other formats are submitted. Additionally, when a file is not selected, and the ‘form_submitted’ proceeds, the NoInfoAvailable.png image does not appear, as it did successfully using my original posted code.

Any ideas on how to remedy the missing error issue, and missing NoInfoAvailable.png image will be greatly appreciated.

Can I see your updated code?

Do you REALLY want the NoInfoAvailable.png added when they just submit the form without selecting a file to load? I wouldn’t think so, but is if you do want that you would need to move the $randomString line to the top and add another copy of copy() to that first condition check. The other formats error works for me.

<?php
if (isset($_POST['form_submitted'])):

    // $randomString needed regardless of passing tests so put outside error condition
    $randomString = time();

    if((isset($_FILES) && $_FILES['file']['error'] != 0) || !isset($_FILES)){
    
        //Unable to upload file to temp
        $error = '<div id="errorMessage">Error: Unable to upload your file </div>';
        
        //Make sure NoInfo image has png extension   
        $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
        copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
            
    }else{
    
        $allowedExts = array("doc", "docx", "gif", "jpeg", "jpg", "txt", "rtf", "pdf", "png", "txt");
        $temp = explode(".", $_FILES['file']['name']);
        $extension = strtolower( end($temp) );
        
        if(!in_array($extension,$allowedExts)){
        
            $error = '<div id="errorMessage">Error: Invalid File Name </div>';
            
        }elseif($_FILES['file']['size'] >= 100000){
        
            $error = '<div class="errorMessage1">Error: Image File Size Exceeds 100 KB Limit </div>';
            
        }
        
        
        if(!isset($error)){            
            $uploadedFile = $_FILES['file']['tmp_name'];
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . "." . $extension;        
            move_uploaded_file($uploadedFile, "upload/" . $thumbnail);             
        }else{            
            //Make sure NoInfo image has png extension   
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
            copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
        }
        
        $_SESSION['thumbnail'] = $thumbnail;
        $file_location = '<a href="http://www....com/upload/' . $thumbnail . '">' . $thumbnail     . '</a>';
    }
endif;
?>

Thanks again for your reply. Much appreciated.
I’m using a PHP script where this Form ultimately uploads a video. It has been modified so that the user, after filling in the Form, can optional add an image file to his Form info, then the Submit button uploads the Form info and (optional) image, after Submit the next page is where the user selects a video file to upload. When the video is searched a link appears next to the video thumbnail image. The link is for viewing the (optional) image file. When a file has not been uploaded via the Form, the link showed only “Access Forbidden”, until the NoInfoAvailable.png code was added (successfully).

Regarding “my updated code”, it is the code you’ve provided:

if (isset($_POST['form_submitted'])):

    // $randomString needed regardless of passing tests so put outside error condition
    $randomString = time();

    if((isset($_FILES) && $_FILES['file']['error'] != 0) || !isset($_FILES)){
    
        //Unable to upload file to temp
        $error = '<div id="errorMessage">Error: Unable to upload your file </div>';
        
        //Make sure NoInfo image has png extension   
        $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
        copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
            
    }else{
    
        $allowedExts = array("doc", "docx", "gif", "jpeg", "jpg", "txt", "rtf", "pdf", "png", "txt");
        $temp = explode(".", $_FILES['file']['name']);
        $extension = strtolower( end($temp) );
        
        if(!in_array($extension,$allowedExts)){
        
            $error = '<div id="errorMessage">Error: Invalid File Name </div>';
            
        }elseif($_FILES['file']['size'] >= 100000){
        
            $error = '<div class="errorMessage1">Error: Image File Size Exceeds 100 KB Limit </div>';    
        }
              
        if(!isset($error)){            
            $uploadedFile = $_FILES['file']['tmp_name'];
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . "." . $extension;        
            move_uploaded_file($uploadedFile, "upload/" . $thumbnail);             
        }else{            
            //Make sure NoInfo image has png extension   
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
            copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
        }
        
        $_SESSION['thumbnail'] = $thumbnail;
        $file_location = '<a href="http://www....com/upload/' . $thumbnail . '">' . $thumbnail     . '</a>';
    }
endif;

And, after adding this latest code, sorry to report, still no error message. Any additional suggestions/remedy will be greatly appreciated.

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

IS the path and your file name correct?

"upload/NoInfoAvailable.png"

Back on post #9 you said “html Form page”… This is a php page right? so it can echo php and the form and processing is on the same page?

Thanks for your reply.
Yes, the path is correct.
Yes, it is a php page.
In my original code, the errors appeared after “Submit” on the next (corresponding html) page where the user selects a video file to upload.
I’m attaching a copy of the uploader.php file code, if you’d like to take a peek at it.
Any additional help is appreciated.
uploader.txt (10.1 KB)

It’s still a little unclear if the form and processing are on the same page, uploader.php.
It looks as though you are redirecting to main_1.htm with inner_upload_video.htm at the end of the file based on $procede == true. SO I am thinking, in each of these sections where the image upload fails and we set the $error variable, we should set $procede = false; I assume that if we set $procede to false we will stay on uploader.php and we should see the error messages.

Based on the server settings you may or may not be able to process php in htm to echo those error messages. Usually not. Again it is unclear what you have going on. Looks like a template system of some sort. Does the page get reloaded when these “render” scripts run?

$TBS->Render     = TBS_OUTPUT;
$TBS->Show();

Thanks again for your reply and for taking the time to look at that previous attachment. I appreciate it.
Yes, this script is templated, with main_1.htm as essentially the header file and inner_upload_video.htm as where the upload Form is. I changed to “false” and did not proceed but, see no error message upon selected a .php file to upload, and selecting Submit. I’m sorry I don’t know the answer to your “render” question, and I’m not clear on what to do with your TBS code.
I’am attaching a copy of the uploader_finished.php file if you’d like to take a peek at it.
Any additional help will be appreciated.
uploader_finished.txt (9.1 KB)

OK, so you said the error messages were showing when you just echoed them, so let’s try just adding the echo after the upload processing. That way it is basiclly being done where it was before.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

if (isset($_POST['form_submitted'])):

    // $randomString needed regardless of passing tests so put outside error condition
    $randomString = time();

    if((isset($_FILES) && $_FILES['file']['error'] != 0) || !isset($_FILES)){

        //Unable to upload file to temp
        $error = '<div id="errorMessage">Error: Unable to upload your file </div>';

        //Make sure NoInfo image has png extension
        $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
        copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);

    }else{

        $allowedExts = array("doc", "docx", "gif", "jpeg", "jpg", "txt", "rtf", "pdf", "png", "txt");
        $temp = explode(".", $_FILES['file']['name']);
        $extension = strtolower( end($temp) );

        if(!in_array($extension,$allowedExts)){

            $error = '<div id="errorMessage">Error: Invalid File Name </div>';

        }elseif($_FILES['file']['size'] >= 100000){

            $error = '<div class="errorMessage1">Error: Image File Size Exceeds 100 KB Limit </div>';

        }


        if(!isset($error)){
            $uploadedFile = $_FILES['file']['tmp_name'];
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . "." . $extension;
            move_uploaded_file($uploadedFile, "upload/" . $thumbnail);
        }else{
            //Make sure NoInfo image has png extension
            $thumbnail = $_SESSION['user_id'] . '-' . $randomString . ".png";
            copy("upload/NoInfoAvailable.png", "upload/" . $thumbnail);
        }

        $_SESSION['thumbnail'] = $thumbnail;
        $file_location = '<a href="http://www....com/upload/' . $thumbnail . '">' . $thumbnail     . '</a>';
    }
endif; 
if(isset($error)){echo $error;}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Thank you again for your assistance.
The “Error: Invalid File Name” appears in the top left corner of the html Form page and does not proceed (because $procede = false;), after submit. Since the message appears after it looks like the file is being uploaded to the Temp folder, I’m guessing?
Is it possible to select Submit and the file only uploads if it is an approved file format/file size?

Sounds like error message is being shown outside html tags instead of in the body of the page. Is that how it “was working” before?

[quote=“ChrisjChrisj, post:19, topic:112217”]
and does not proceed (because $procede = false;), after submit.
[/quote] Yes if you added $procede = false; in the processing as I suggested in POST #16.
It’s up to you HOW you wish the page to behave. Take those out if you wish.

[quote=“ChrisjChrisj, post:19, topic:112217”]
Since the message appears after it looks like the file is being uploaded to the Temp folder, I’m guessing?
[/quote]Yes

It doesn’t matter that file is loaded to $_FILES['file']['tmp_name']. That is part of the upload process. SEE POST # 2
What matters is what you do with it after this when we check the conditions of type and size.

It is only moved to your upload folder if it is an approved file format/file size.
The NoInfoAvailable.png image is copied and added to the upload folder if the file upload doesn’t pass the format/file size conditions.

That IS how you had it.

OR are you talking about the changes made in POST # 11 and #12 where we copy the NoInfoAvailable.png when they just submit the form without selecting a file to load?