help…! same page file upload to mysql
Question
so i decided against using uploadify as i could not get any help on it. i've been now trying to implement a simpler solution. but unfortunately i cannot seem to process the upload code on a single page without receiving the following error:
Warning: fopen() [function.fopen]: Filename cannot be empty in C:\xampp\htdocs\speedycms\manageclient.php on line 205
Warning: fread() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\speedycms\manageclient.php on line 206
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\speedycms\manageclient.php on line 208 Error, query failed
this is the code i've been trying to get to work... can you suggest any means of getting it all to work on a single page rather than splitting it up into two apart from ajax (im not too familiar with that)... its all on a single page
any help would be appreciated!
<!-- upload file --->
<?php
if (array_key_exists('uploadfile',$_POST)) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$uploadQry = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($uploadQry) or die('Error, query failed');
echo "<br>File $fileName uploaded<br>";
exit;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?id=' . intval($client_id); ?>">
<p>
<b>File Upload</b></p>
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"><BR />
<input type="hidden" name="uploadfile" value="1"/>
<input name="upload" type="submit" id="upload" value=" Upload ">
</p>
<p> <a href="#viewFiles" class="form" rel="facebox">View files</a>
</p>
<div id="viewFiles" style="display:none;" rel="facebox">
<div style="width:300px; height: 300px;"></div></div></form>
Solution
You need to set the correct encoding of your form to enable file uploads:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
...
</form>
Edit: Filename cannot be empty
is telling you that you have not specified the file name in your first call to fopen - you're passing in $tmpName to that method, which is assigned from $_FILES['userfile']['tmp_name']
.
The only reason I can think of for $_FILES['userfile']['tmp_name']
to be empty is that you haven't actually uploaded a file?
OTHER TIPS
The error message says that in
$fp = fopen($tmpName, 'r');
$tmpName is blank (or NULL).
Try looking in $_FILES to see what you've got:
print serialize($_FILES);