Skip to content

Uploading a file in php using an iframe

I recently wrote a PHP file upload application. Yawn, right? There’s a manual entry on this task, which tells you just how often folks need to do it.

Well, I threw in a few new tricks–they were new to me at least. Basically, instead of posting to a page in the typical way, I post to a 1px by 1px invisible iframe, which then generates some javacript:

<form action="/upload.php" enctype="multipart/form-data"
method="post" target="target_upload">
<iframe id="target_upload" name="target_upload"
style="border: 0pt none ; width: 1px; height: 1px">

———–

<script type="text/javascript">
if (parent && parent.uploadFinished) {
parent.uploadFinished(<?php echo $result;?>);
} </script>

The next question is how to communicate from the iframe, which is handling the processing, to the parent window, which is where the user interface is. The upload process parses the file and puts it in a database. If there are any errors, the parsing code ouptuts “0”, otherwise, it returns “1”. This value is passed to a javascript function which is written to the iframe. It looks something like the above, where the uploadFinished function basicly shows divs containing an appropriate message.

How is this superior from a regular page post? Not by very much. It’s not truly asynchronous–you still see the browser wheel spin. The only browser actions you can take while an upload is proceeding are those that open in a new window. That’s not much, but it’s more than a normal post allows you to do. In addition, this is relatively easy to do and you don’t have to deal with creating a new ‘successful upload page’.

[tags]PHP, file upload[/tags]