views:

41

answers:

1

Hi, I'm trying to require a file upload in a form, but cannot get it to work. Any ideas? I'd rather echo the php error on the page vs. a javascript popup. Thanks for taking a look:

<?php 


// initialize $file1
$file1 = $_POST['file1'];


 // check upload of $file1
 if ($file1 == '' )  { 
$error = "Please upload an image";
 } 


?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Require upload of an file</title>
</head>

<body>

<?php if ($error) {echo $error;} ?>

<br /><br /><br />

<form id="form1" name="form1" method="post" action="nextpage.php">

<input type="file" size="8" name="file1" />

<input name="Submit" type="Submit" />

</form>



</body>
</html>
+2  A: 

See this tutorial it have all that you need.

To sum up:

  • Use enctype="multipart/form-data" and method="POST" in the <form> tag.
  • In PHP use $_FILES['uploadedfile']['name'] to read original name ("uploadedfile" is the name of your file input - "file1" in your example).
  • In PHP use $_FILES['uploadedfile']['tmp_name'] to read server side temp file name.
  • In PHP use $_FILES['uploadedfile']['error'] to get the error (if any) see there for possible codes.
  • Also see the PHP manual for more info.

In your exemple use this form instead:

<form id="form1" name="form1" method="post" action="nextpage.php" enctype="multipart/form-data">
    <input type="file" size="8" name="file1" />
    <input name="Submit" type="Submit" />
</form>

In "nextpage.php":

//Use $_FILES['file1'] to check the file upload...
print_r($_FILES['file1']);
AlexV
Thanks for your help. If I skip the file upload, it still goes to the next page. I need to prevent them from getting to the next page without the file upload.
Barry
With your actual design you can't do that as action="nextpage.php". Either set action to the page where the form is and if the form validates go to nextpage.php or if you want to do the form validation in nextpage.php you can redirect to the form with a header location call.
AlexV
I changed it to: action="<?php $_SERVER['PHP_SELF']; ?>" but it still doesn't require the file upload.
Barry
You could pre-validate the form with JavaScript to ensure that the file has been selected prior form submit. But you will ultimately need to validate the form with PHP (as JavaScript can be tempered with or even OFF client side). Something like: if the form is valid and if the file has been successfuly uploaded then load nextpage.php else display error message and display form again. It's not automatically done as you may think...
AlexV