PHP Tutorial: How To Upload An Image Using Basic PHP

When developing a PHP website, there comes a time when you’re required to add a functionality that allows your users to upload files. This is where the File upload feature comes in handy. This feature allows your users to upload file/files on your server through your PHP website. So, in this PHP tutorial, we’ll cover the basic process of uploading an image using PHP.

Now, before moving ahead to upload image PHP, there are small details that must be correct in order to successfully upload a file. First of all, you need to make sure that PHP is configured to allow uploads. Check your “php.ini” file and ensure the “file_uploads” directive value is “on”.

Files that are uploaded are stored in a temporary directory initially, but you can move these files to a permanent location via your PHP script. For this, you’ll have to specify your location using the “upload_tmp_dir” directive in “php.ini”.

Once, this task is done, it’s time to move on to the coding part. The following HTML form will provide an interface to a user to upload a file.

HTML Form:

<form action="accept-file.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="image" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
After you create this HTML form, you’ll now have to write a PHP script in order to process the PHP file upload. Below you’ll find PHP file upload script code for the same.
PHP Script:
//if they DID upload a file...
if($_FILES['image']['name'])
{
//if no errors...
if(!$_FILES['image']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['image']['tmp_name']); //rename file
if($_FILES['image']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}

//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['image']['error'];
}
}

//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']

That’s it! Your work is done here. if you still have any doubts in this PHP tutorial regarding upload image PHP, you can contact our PHP developers for the solution and if you’d like to hire PHP developer, you can contact Space-O Technologies today.

Do you want to download the whole script so you can use it in your next project? Then you can directly download it on GitHub.

This page was last edited on October 16th, 2018, at 7:40.
 
 

Have an App Idea?

Get your free consultation now