Simple File Upload with PHP

Date Posted: January 21, 2015, 6:46 am


simple-file-upload-with-php-screenshot

Demo Download

The Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$message = '';

if(isset($_POST['submit'])){
   
    // Check if there is an error
    if(!$_FILES['photo']['error']){
       
        // Limit file size to 1MB
        if($_FILES['photo']['size'] > (1024000)){
            $message = '<p class = "bg-danger">Oops!  The size of your file is too large.</p>';
       
        } else {       
            // Replace file name spaces and convert to lower case.
            $new_file_name = str_replace(' ', '_', strtolower($_FILES['photo']['name']));
       
            // Check if file was uploaded
            if(move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name)){
                $message = '<p class = "bg-success">File successfully uploaded</p>';
            }
        }
       
    } else {
        // Output all errors
        $message = '<p class = "bg-danger">Oops!  Your upload triggered the following error:  '.$_FILES['photo']['error'] . '</p>';
    }
     
}

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me