PHP file uploads

Install:
  • Check php.ini variables
  • Copy upload.php

php.ini:
Check the following 3 variables.
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir = "c:/wamp/tmp"

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M

upload.php:
<?php

$uploadPath = './';

if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
    if ( isset( $_FILES[ 'upload' ] ) ) {
        $allowed = array( 'image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png' );
        if ( in_array( $_FILES[ 'upload' ][ 'type' ], $allowed ) ) {
            if ( move_uploaded_file( $_FILES[ 'upload' ][ 'tmp_name' ], $uploadPath . $_FILES[ 'upload' ][ 'name' ] ) ) {
                echo '<p>File uploaded.</p>';
            }
        } else {
            echo '<p>Please upload a jpeg or png image.</p>';
        }
    }

    if ( $_FILES[ 'upload' ][ 'error' ] > 0 ) {
        echo '<p>The file could not be uploaded because:<br />';
        switch ( $_FILES[ 'upload' ][ 'error' ] ) {
            case 1:
                echo 'The file exceeds the upload_max_filesize setting in php.ini.';
                break;
            case 2:
                echo 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                break;
            case 3:
                echo 'The file was only partially uploaded.';
                break;
            case 4:
                echo 'No file was uploaded.';
                break;
            case 6:
                echo 'No temporary folder was available.';
                break;
            case 7:
                echo 'Unable to write to the disk.';
                break;
            case 8:
                echo 'File upload stopped.';
                break;
            default:
                echo 'A system error occurred.';
                break;
        }
        echo '</p>';
            
        if ( file_exists( $_FILES[ 'upload' ][ 'tmp_name' ] ) && is_file( $_FILES[ 'upload' ][ 'tmp_name' ] ) ) {
            unlink( $_FILES[ 'upload' ][ 'tmp_name' ] );
        }
    }
}
?>

<form enctype="multipart/form-data" action="" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="524288" />
    <fieldset>
        <legend>Select a JPEG or PNG image of 512KB or smaller to be uploaded:</legend>
        <p>File: <input type="file" name="upload" /></p>
    </fieldset>
    <input type="submit" name="submit" value="Upload" />
</form>

No comments:

Post a Comment