Forum Moderators: coopster

Message Too Old, No Replies

PHP form errors.need help

confirmation message shows on form load

         

alibobs

1:15 pm on Apr 23, 2009 (gmt 0)

10+ Year Member



I'm making a form for uploading files. I have the upload script working but it shows 'file uploaded successfully' upon loading the form (this should only be shown after the button is pressed and the file is uploaded). The code is below. How do I remove the confirmation message until the file is actually uploaded?

<body>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<div style="padding-bottom:15px; padding-top:20px;">Please select the upload button to upload the weekly pdf file from your PC.</div>
<div style="padding-bottom:10px;"><input name="file" id="file" type="file" /> </div>
<div><input type="submit" value="Upload File" name="uploadBtn" /></div>
</form>

<?php
$current_dir = '/upload/';
$dir = opendir($current_dir);
$upfile = $current_dir.$_FILES['file']['name'];

if ($_FILES['file']['error'] > 0)
{echo 'Problem: ';
switch ($_FILES['file']['error'])
{
case 1: echo 'File exceeded upload_max_filesize'; break;
case 2: echo 'File exceeded max_file_size'; break;
case 3: echo 'File only partially uploaded'; break;
case 4: echo 'No file uploaded'; break;
}
exit;
}
else echo 'File uploaded successfully';
?>
</body>

d40sithui

3:38 pm on Apr 23, 2009 (gmt 0)

10+ Year Member



There are lots of ways to do this. You keep getting that landing statement because even if $_FILES[] is not set, PHP automatically will evaluate that its value to be 0. Since your base case is anything not greater than 0, it will always print. The easiest way to counter this is to use the isset() function to check if there was a file submitted. You can put in around the whole php (to save unnecessary processing power.

if(isset($_POST['file'])){
$current_dir = '/upload/';
$dir = opendir($current_dir);
$upfile = $current_dir.$_FILES['file']['name'];

if ($_FILES['file']['error'] > 0){
echo 'Problem: ';
switch ($_FILES['file']['error']){
case 1: echo 'File exceeded upload_max_filesize'; break;
case 2: echo 'File exceeded max_file_size'; break;
case 3: echo 'File only partially uploaded'; break;
case 4: echo 'No file uploaded'; break;
}
exit;
}
else{
echo 'File uploaded successfully';
}
}


You can also put it at the end as such


elseif($_FILES['file']['error'] == 0 && isset($_POST['file']) ){
echo 'File uploaded successfully';
}