GrizPwnz GrizPwnz - 1 month ago 5x
PHP Question

PHP upload to certain folder based on HTML checkbox

Im new to PHP and still learning, but I want to know if I am able to do something like this. I have a basic HTML form like the one below.

<form action="upload.php" method="post"
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
<label><input type="checkbox" id="cb" value="checkb">Make Private.</label>

And a basic upload PHP document like the one below as well.


if ($_FILES["file"]["size"] < 2097152) {
if ($_FILES["file"]["error"] > 0) {
header('Location: /');
}else {
echo "Original Name: " . $_FILES["file"]["name"] . "<br>";
echo "File Type: " . $_FILES["file"]["type"] . "<br>";
echo "File Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
$randprefix = hash('ripemd160', openssl_random_pseudo_bytes(32), false);
$filepath = "upload/" . $randprefix . $_FILES["file"]["name"];
if (file_exists($filepath)) {
echo $filepath . " already exists. ";
}else {
move_uploaded_file($_FILES["file"]["tmp_name"], $filepath);
echo "Link to file: " . '<a href = "' . $filepath . '">' . $filepath . '</a>' ;

}else {
echo "File too large.";

What i'm asking is, is it possible to have a checkbox on the HTML form that when checked the file will upload to a folder named "private" and when unchecked the file will upload to a folder named "public". Thank you.


You can use the condition like this so that than only you can get the checkbox value after the form is submitted.

    $filepath = "upload/private" . $randprefix . $_FILES["file"]["name"];
    $filepath = "upload/public" . $randprefix . $_FILES["file"]["name"];

You have to place the name for the checkbox input type so that you can check in the upload.php page and then set the folder over there.


<label><input type="checkbox" id="cb" value="checkb">Make Private.</label>


<label><input type="checkbox" id="cb" value="checkb" name="check">Make Private.</label>

Explanation: When the user selects the checkbox at the time of submitting it will check for the check box value and it will make the $filepath as upload/private or else if the user while submitting the data he/she has not selected the check box it will change the code as per the selection if the check box value. So that you can move_upload_file() based on the selection available.