vlevsha
vlevsha

Reputation: 179

How do I check with PHP if a file was attached to an HTML form?

I need to make sure that either the text was entered into the form's textarea input element or a file attached through the file input element. I tried various things, including this:

if((empty($_POST['text'])) && (!empty($_FILES['uploadedfile']))) {
            $errors .= 'Please either enter your text or attach a file.<br/><br/>';
        }

Doesn't work.

Thank you!

Upvotes: 0

Views: 4958

Answers (3)

dqhendricks
dqhendricks

Reputation: 19251

if ((!empty($_POST['text']) && file_exists($_FILES["image"]["tmp_name"])) || (empty($_POST['text']) && !file_exists($_FILES["image"]["tmp_name"]))) {
    throw new Exception('must choose one or other');
}

this will pass if one is set or the other, but not both and not none.

Upvotes: 0

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

if($_FILES!=null && $_POST!=null){
    $file = $_FILES["image"]["tmp_name"];   

    if(!isset($file)){

       }
}

this is the code i have used

Upvotes: 1

LeeR
LeeR

Reputation: 1636

Try

if((empty($_POST['text'])) || (empty($_FILES['uploadedfile']))) {
    errors .= 'Please either enter your text or attach a file.<br/><br/>';
}

You only want one OR the other so you ask if the "text" field is empty OR the "uploadFile" is empty

Upvotes: 2

Related Questions