Jack Snyder Jack Snyder - 1 month ago 7
HTML Question

PHP Single button file upload through internal php function

As part of a class I've been asked to create a simple file upload system that uploads files in a single button to a folder called ./files. I've been able to do this and I have been able to keep it all contained in one a3.php file with this:

<form action="a3.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload" name="submitFile">
</form>


Which opens up a file dialog and only requires the user to press two buttons

I use the following function to run the upload function.

if(isset($_POST['submitFile']))
{
uploadFile();
}


The uploadFile() function simply uses move_uploaded_file to move to file to the ./files folder. Currently without any questions asked.

My issue is that my attempts to make the buttons for the file upload a single one have been stymied. I have attempted to use the following code to resolve the issue:

<form name="frm" action="a3 - Copy.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" onchange="frm.submit();">
</form>


Which, while it refreshes the page as if an action is being performed, appears to do nothing. I have attempted to look into how exactly .submit() works but haven't gotten any closer to understanding any intricacies it may have while a part of onchange.

I've looked around and I've found code that can upload in a single button, and I've found code that can upload using an internal php function, but none that does both.

Answer

You can try using a button but not displaying it. When the file input is changed, using javascript trigger a click on the hidden button, like in the code below:

<form name="frm" action="a3 - Copy.php" method="post" enctype="multipart/form-data"> 
    <input type="submit" name="submitFile" style="display:none" id="submit">
    <input type="file" name="uploadFile" onchange="document.getElementById('submit').click()">
</form>

<?php
if(isset($_POST['submitFile']))
{
    uploadFile();
}
?>
Comments