Thursday, May 16, 2013

Upload a file with PHP

The ability to upload files to your web server can be very beneficial to your website's user experience. I am building an inventory information system for a current project and I want the administrators to be able to upload product images when creating things to sell.

I have commented most of the important parts so if you have a basic understanding of PHP, this should basically make sense to you.

<?php
    if (isset($_POST['Submit'])) {
        //create variable to write file to server
        $loc = 'upload/';
        $loc = $loc . basename($_FILES['uploaded']['name']);

        //move uploaded file to specified $loc
        if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $loc)) {
            echo "The file " . basename($_FILES['uploadedfile']['name']) . " has been uploaded.<br />";
            echo "<a href='upload/'>Click Here</a> to view uploaded files.";
        } else {
            echo "Sorry, there was a problem uploading your file.";
        }
    } else {
        //upload form
        echo "<form enctype='multipart/form-data' action='upload.php' method='POST'>
        Please choose a file: <input name='uploaded' type='file' /><br />
        <input type='submit' name='Submit' value='Upload' />
        </form>";
    }
?>

To get this script to work on your own server, copy and paste the code into a file named upload.php. Then, the folder 'upload' needs to be created in the same directory as 'upload.php'.

Here is an explanation of 'move_upload_files': http://www.w3schools.com/php/func_filesystem_move_uploaded_file.asp

Happy Coding XD

No comments:

Post a Comment