#native_company# #native_desc#
#native_cta#

File uploads made easy Page 3

By Darren Beale
on August 31, 2007

An OO developer would probably make this whole script a class and have each one of the following functions as methods. Personally, I prefer to write my code using a function based approach.
To start us off, I want to write the upload form as a small function, I can then call it many times in this code without lots of messy repeating. If you are wondering why there are lots of n’s everywhere, this is so that the outputted HTML is not all squashed onto one line. In bigger applications it makes for easier debugging when you view source, so I’m not being anal for no reason.

<?php

function form($error=false) {

global $PHP_SELF,$my_max_file_size;

    if ($error) print $error "<br><br>";
    
    print 
"n<form ENCTYPE="multipart/form-data"  action="" $PHP_SELF "" method="post">";
    print 
"n<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="" $my_max_file_size "">";
    print 
"n<INPUT TYPE="hidden" name="task" value="upload">";
    print 
"n<P>Upload a file";
    print 
"n<BR>NOTE: Max file size is " . ($my_max_file_size 1024) . "KB";
     print 
"n<br><INPUT NAME="the_file" TYPE="file" SIZE="35"><br>";
    print 
"n<input type="submit" Value="Upload">";
    print 
"n</form>";

# END form

?>

Note, the <form enctype..> if we don’t add this nothing will get uploaded. I’ve also set the parameter $error to false, this is a nice way of pre-defining the value, so I don’t have to always pass the parameter in.
Our second function is to check if a certain value is in an array, now PHP4 has this built in, but PHP3 does not, so we wrap an IF statement around it checking the PHP version, if you are running PHP4, you can delete the whole thing but I’ve left in so it can use it on differing servers without too much thought.

<?php

if (!ereg("^4",phpversion())) {
    function 
in_array($needle,$haystack) { # we have this function in PHP4, so for you PHP3 people
        
for ($i=0$i count($haystack); $i++) {
            if (
$haystack[$i] == $needle) {    
                return 
true;
            }
        }
    }
}

?>