File Uploader

Uses "Uploadify" flash file uploader & Google's ReCAPTCHA for authentication.


INDEX.PHP


<?php

// For debugging, you can uncomment these phpini overrides.
// error_reporting(E_ALL); // Show all errors
// ini_set('display_errors', 'On'); // Show all errors
// ini_set('SMTP', 'smtp.example.net'); //Specify an SMTP server
// ini_set('smtp_port', '25') //Specify an SMTP port

//====== CONFIGURATION ======//
define("FUNCTIONS", "/home/example/files/functions.php");                            #defines location of header
define("HEADER", "/home/example/files/header.php");                            #defines location of header
define("FOOTER", "/home/example/files/footer.php");                            #defines location of footer
define("TARGET", "/home/example/files/uploads/");                             #defines target path for uploaded files
define("SQLSERVER", "mysql.example.com");                                    #MySQL Server, usually localhost
define("SQLUSER", "example");                                            #MySQL Username
define("SQLPASSWORD", "example");                                        #MySQL Password
define("SQLDB", "example_files");                                            #MySQL Database
define("CURRENTDAY",date('j'));                                                #Defines a constant for the current day (Numerical)
define("CURRENTMONTH",date('n'));                                            #Defines a constant for the current month (Numerical)
define("CURRENTYEAR",date('Y'));                                            #Defines a constant for the current year (4 digit)
define("CURRENTTIME",time());                                                #Current time in Unix Epoch Format
define("SCRIPTLOCATION","http://files.example.com/");                        #Location of script
define("ORGANIZATION","Example.com");                                        #Organization Name
define("DONOTREPLYEMAIL","donotreply@example.com");                            #Address to use to send from
define("ALERTEMAIL","admin@example.com");                                #Where should error emails go?
define("PUBLICKEY","PUBLICKEY");
define("PRIVATEKEY","PRIVATEKEY");
//========================//
 
//===========PAGE DISPLAY LOGIC========//
 include(FUNCTIONS); //grab the functions
 include(HEADER); // Show the header
if (isset($_GET['id'])) { // If an ID is passed along in the URL
    displayRequestedFile(); //Display that file!
} elseif (!$_POST) { // If no ID is passed along, and the form is empty
    displayUploadForm(); //Display the upload form!
} else {  //Otherwise, we assume that the form has been filled out and a file has been submitted
    processUploadedFile(); //So deal with it!
};

include(FOOTER); //Display footer

//THE END.
?>

FUNCTIONS.PHP


<?php
function openDatabaseConnection() { 
        mysql_connect(SQLSERVER, SQLUSER, SQLPASSWORD) or die("Can not connect to DB server.");
        mysql_select_db(SQLDB) or die("Can not connect to database.");
};

function displayUploadForm() { 
    ?> 
    <center><h1><?=ORGANIZATION?> File Sharing Utility</h1></center>
    <form id="fileForm" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data" method="post">
        <table width="500" border="0" cellspacing="0" cellpadding="5">
            <tr>
            <td>
                Your Name:
            </td>
            <td>
                <input name="name" type="Text" size="48">
            </td>
            </tr>
            <tr>
                <td>
                    Your E-mail:
                </td>
                <td>
                    <input name="email" type="Text" size="48">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <b>Separate multiple &quot;Notify E-mail&quot; addresses by a comma.</b>
                </td>
            </tr>
            <tr>
                <td>
                    Notify E-mail:
                </td>
                <td>
                    <input name="toemail" type="Text" id="toemail" size="48">
                </td>
            </tr>
            <tr>
                <td>
                    Upload File:
                </td>
                <td><input id="file_upload" name="file_upload" type="file" /></td>
            </tr>
            <tr>
                <td>Message:</td>
                <td><textarea name="comments" cols="36" rows="6"></textarea></td>
            </tr>
            <tr>
                <td>
                    Bot Check:
                </td>
                <td>
                    <?php
                    require_once('recaptchalib.php');
                    $publickey = PUBLICKEY;
                    echo recaptcha_get_html($publickey);
                    ?>
                </td>
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    <input onclick="$('#file_upload').uploadifyUpload()" type="button" value="Submit" />
                </td>
            </tr>
        </table>
    </form>
    <br>
<?
};

function processUploadedFile() {
    require_once('recaptchalib.php');
    $privatekey = PRIVATEKEY;
    $resp = recaptcha_check_answer ($privatekey,
    $_SERVER["REMOTE_ADDR"],
    $_POST["recaptcha_challenge_field"],
    $_POST["recaptcha_response_field"]);
    if (!$resp->is_valid) {
        echo "<center><h1>Captcha error!</h1></center>";
        echo "Your humanity could not be verified. Please try again!";
    } else {
        $ok=1;
        if (!$_POST['name']) {
            echo "<h1>Uh oh! There's a problem!</h1>";
            echo "Your name is required!";
            $ok=0;
        } elseif (!$_POST['email']) {
            echo "<h1>Uh oh! There's a problem!</h1>";
            echo "Your e-mail address is required!";
            $ok=0;
        } elseif (!$_POST['toemail']) {
            echo "<h1>Uh oh! There's a problem!</h1>";
            echo "The recipient's email is required!";
            $ok=0;
        } elseif ($_SESSION['error'] == 1) {
            echo "<h1>Uh oh! There's a problem!</h1>";
            echo "Invalid Filetype specified: ".$_SESSION['error_ext'];
            $ok=0;
        };            
        if ($ok==0) {
            echo "<br> \n Sorry your file was not uploaded!"; 
            unset($_SESSION);
            session_destroy();
            setcookie ("PHPSESSID", "", time() - 3600);
        } else {
            $hashseed = CURRENTTIME.$_SESSION['filename'];
            $hash = md5($hashseed);
            mkdir($dest = TARGET.$hash);
            $dest = TARGET.$hash.'/'.$_SESSION['filename'];
            $source = TARGET.'/'.$_SESSION['filename'];
            if(copy($source, $dest))  {
                unlink($source);
                $htaccess = TARGET.$hash.'/'.".htaccess";
                $htaccessText = "DirectoryIndex \"".$_SESSION['filename']."\"";
                $htaccessHandle = fopen($htaccess, 'w') or die("can't open file");
                fwrite($htaccessHandle,$htaccessText);
                fclose($htaccessHandle);
                openDatabaseConnection();
                $hash = mysql_real_escape_string($hash);
                $filename = mysql_real_escape_string($_SESSION['filename']);
                $who = mysql_real_escape_string($_POST['name']);
                $ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
                $query = "INSERT INTO files SET hash = '$hash', "
                        ."filename = '$filename', "
                        ."time = ".CURRENTTIME.", "
                        ."who = '$who', "
                        ."ip = '$ip'";
                $result = mysql_query($query);
                if (mysql_error()) {
                    $mysql_error = mysql_error();
                    echo "We're sorry, there was a problem! An email has been sent to the administrator!";
                    $headers =     "From: ".DONOTREPLYEMAIL."\r\n" .
                        "Reply-To: ".DONOTREPLYEMAIL."\r\n" .
                        'X-Mailer: PHP/'.phpversion();
                    $subject = "ALERT: MySQL Error Storing File From ".ORGANIZATION."!";
                    $message = "There was an error with the File Upload Page for ".ORGANIZATION."! \n
                    The error was: '$mysql_error' \n
                    The sender was ".$_POST['email']." \n
                    The timetamp was ".CURRENTTIME;        
                    mail(ALERTEMAIL, $subject, $message, $headers);
                } else {
                    $recipients = $_POST['email'].", ".$_POST['toemail'];
                    $headers =     "From: ".DONOTREPLYEMAIL."\r\n" .
                            "Reply-To: ".DONOTREPLYEMAIL."\r\n" .
                            'X-Mailer: PHP/'.phpversion();
                    $subject = "You have been sent a file by ".ORGANIZATION."!";
                    $message = "You have been sent a file by ".ORGANIZATION."! \n \n".
                    $who." is sending you ".$_SESSION['filename'].". Please visit the following link to download it! \n \n ".
                    SCRIPTLOCATION."?id=".$hash." \n \n ".
                    "Attached Message:\n ".$_POST['comments'];        
                    mail($recipients, $subject, $message, $headers);
                    echo "<h1>File successfully uploaded!</h1>";
                    echo "The file: <b><u>". basename( $_SESSION['filename']). "</u></b> has been uploaded and emailed.".
                    "Please check your email for verification and the download link"; 
                };
            } else {
                echo "Sorry, there was a problem uploading your file. An email has been sent to the administrator!";
                $headers =     "From: ".DONOTREPLYEMAIL."\r\n" .
                    "Reply-To: ".DONOTREPLYEMAIL."\r\n" .
                    'X-Mailer: PHP/'.phpversion();
                $subject = "ALERT: Error Uploading File From ".ORGANIZATION."!";
                $message = "There was an error with the File Upload Page for ".ORGANIZATION."! \n".
                "The file was: ".$__SESSION['filename']." \n".
                "The sender was ".$_POST['email']." \n".
                "The timetamp was ".CURRENTTIME;
                mail(ALERTEMAIL, $subject, $message, $headers); 
            };
        unset($_SESSION);
        session_destroy();
        setcookie ("PHPSESSID", "", time() - 3600);
        };
    };
};
function displayRequestedFile() {
    openDatabaseConnection();
    $hash = mysql_real_escape_string($_GET['id']);
    $query = "SELECT * FROM files WHERE hash = '$hash' LIMIT 1";
    $result = mysql_query($query);
    $num_rows = mysql_num_rows($result);
    if (mysql_error()) {
        $mysql_error = mysql_error();
        echo "We're sorry, there was a problem! An email has been sent to the administrator,".
        "and we're let you know when it's resolved!";
        $headers =     "From: ".DONOTREPLYEMAIL."\r\n" .
                    "Reply-To: ".DONOTREPLYEMAIL."\r\n" .
                    'X-Mailer: PHP/'.phpversion();
        $subject = "ALERT: MySQL Error Sending File From ".ORGANIZATION."!";
        $message = "There was an error with the File Upload Page for ".ORGANIZATION."! \n".
                    "The error was: '$mysql_error' \n".
                    "The sender was ".$_POST['email']." \n".
                    "The timetamp was ".CURRENTTIME;
        mail(ALERTEMAIL, $subject, $message, $headers);
    } elseif ($num_rows == 0) {
        echo "<center><h1>Error locating file!</h1></center> \n".
            "We're sorry, the file you are looking for has expired or could not be found!".
            "If you believe this to be an error, please contact the sender and ask them to".
            "try again. PLEASE NOTE: Files are deleted after 30 days!";
    } else {
        while ($row = mysql_fetch_array($result)) {
            extract($row);
            $uploaddate = date("F j, Y, g:i a", $time);
            ?> 
            <center><h1>Download file: <?=$filename?></h1></center>
            <br>
            <b>Sender:</b> <?=$who?><br>
            <b>Uploaded:</b> <?=$uploaddate?><br>
            <b>Download link (Right click and save as):</b> <a href="<?=SCRIPTLOCATION.'uploads/'.$hash.'/'.$filename?>" target="_blank"><?=$filename?></a>
            <?
        };
    };
};

function mostRecentUploads() {
    echo "<h4>Most Recent Uploads</h4>
    <ul> \n";
    openDatabaseConnection();
    $query = "SELECT * FROM files ORDER BY time DESC LIMIT 10";
    $result = mysql_query($query);
    $num_rows = mysql_num_rows($result);
    if ($num_rows > 0) {
        while ($row = mysql_fetch_array($result)) {
            extract($row);
            echo "<li> \n".
            "<a href=\"/?id=$hash\">$filename</a> by $who at ".
            date("m.d.Y g:i a", $time)." \n".
            "</li> \n";
        };
    } else {
        echo "None yet!";
    };
    echo "</ul>";
};

?>
?>