Skip to content

Upload, crop and resize images with PHP – Part 1

One of the most common actions on the modern web application is upload, crop and resize of images, whether for avatar use or general use of resized images in galleries or as thumbnails.

This tutorial will cover all the needed techniques starting with an old school upload form and gradually building up a modern solution which you can then use in every day situations.

Upload image with PHP

We will start this tutorial with a classic image upload so you can easily understand the means and methods of how uploading files in PHP works.

In this first example we will a form for uploading files and save that file in a folder on the server, but only if that file is an image.

To upload a file, you need a form with a special input field type of file. So, open your favorite editor and paste in this code and save it as form.php:

[code lang=”html”]
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using normal form and PHP</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" />
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
</body>
</html>
[/code]

One thing that you already noticed is probably the enctype attribute of our form. It basically prepares the form for binary data, like the contents of a file.

Next step is to create a file that will handle our uploaded images. Go ahead, create upload.php file and paste this in:

[code lang=”php”]
<?php
// fileToUpload is the name of our file input field
if ($_FILES[‘fileToUpload’][‘error’] > 0) {
echo "Error: " . $_FILES[‘fileToUpload’][‘error’] . "<br />";
} else {
echo "File name: " . $_FILES[‘fileToUpload’][‘name’] . "<br />";
echo "File type: " . $_FILES[‘fileToUpload’][‘type’] . "<br />";
echo "File size: " . ($_FILES[‘fileToUpload’][‘size’] / 1024) . " Kb<br />";
echo "Temp path: " . $_FILES[‘fileToUpload’][‘tmp_name’];
}
[/code]

Now, open form.php in browser and try to select and upload a file. If everything went fine, you should see some info about the uploaded file when you submit a form.

Nice start, but user can now upload anything to your server and basically blow it to pieces. So, let’s modify the upload.php code to check if uploaded file is actually an image:

[code lang=”php”]
<?php
if ($_FILES[‘fileToUpload’][‘error’] > 0) {
echo "Error: " . $_FILES[‘fileToUpload’][‘error’] . "<br />";
} else {
// array of valid extensions
$validExtensions = array(‘.jpg’, ‘.jpeg’, ‘.gif’, ‘.png’);
// get extension of the uploaded file
$fileExtension = strrchr($_FILES[‘fileToUpload’][‘name’], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
echo ‘Uploaded file is allowed!’;
} else {
echo ‘You must upload an image…’;
}
}
[/code]

So, we checked if the file is an image and now we can write code to move that image in some folder on the server, so change your code to this:

[code lang=”php”]
<?php
if ($_FILES[‘fileToUpload’][‘error’] > 0) {
echo "Error: " . $_FILES[‘fileToUpload’][‘error’] . "<br />";
} else {
// array of valid extensions
$validExtensions = array(‘.jpg’, ‘.jpeg’, ‘.gif’, ‘.png’);
// get extension of the uploaded file
$fileExtension = strrchr($_FILES[‘fileToUpload’][‘name’], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
// we are renaming the file so we can upload files with the same name
// we simply put current timestamp in fron of the file name
$newName = time() . ‘_’ . $_FILES[‘fileToUpload’][‘name’];
$destination = ‘uploads/’ . $newName;
if (move_uploaded_file($_FILES[‘fileToUpload’][‘tmp_name’], $destination)) {
echo ‘File ‘ .$newName. ‘ succesfully copied’;
}
} else {
echo ‘You must upload an image…’;
}
}
[/code]

Before you try this out, create a folder named uploads in the directory in which the code is in.

Congratulations, you successfully uploaded and saved a file on the server.

Crop and resize images with PHP

Now the fun part begins. We will resize the uploaded image and save resized version in uploads folder so you can easily use them later. We can do this from scratch, but there are plenty of useful libraries on the web that does an excellent job.

I will use a great ImageManipulator class by Phil Brown. Download it and put inside your working directory.

Now, update your upload.php file:

[code lang=”php”]
<?php
// include ImageManipulator class
require_once(‘ImageManipulator.php’);

if ($_FILES[‘fileToUpload’][‘error’] > 0) {
echo "Error: " . $_FILES[‘fileToUpload’][‘error’] . "<br />";
} else {
// array of valid extensions
$validExtensions = array(‘.jpg’, ‘.jpeg’, ‘.gif’, ‘.png’);
// get extension of the uploaded file
$fileExtension = strrchr($_FILES[‘fileToUpload’][‘name’], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = time() . ‘_’;
$manipulator = new ImageManipulator($_FILES[‘fileToUpload’][‘tmp_name’]);
// resizing to 200×200
$newImage = $manipulator->resample(200, 200);
// saving file to uploads folder
$manipulator->save(‘uploads/’ . $newNamePrefix . $_FILES[‘fileToUpload’][‘name’]);
echo ‘Done …’;
} else {
echo ‘You must upload an image…’;
}
}
[/code]

The same class can be used to crop the image, so let’s change the code so the image cropped to 200×130 px. We want to crop the center of the image, so the good parts are intact, so we have to calculate crop coordinates:

[code lang=”php”]
<?php
// include ImageManipulator class
require_once(‘ImageManipulator.php’);

if ($_FILES[‘fileToUpload’][‘error’] > 0) {
echo "Error: " . $_FILES[‘fileToUpload’][‘error’] . "<br />";
} else {
// array of valid extensions
$validExtensions = array(‘.jpg’, ‘.jpeg’, ‘.gif’, ‘.png’);
// get extension of the uploaded file
$fileExtension = strrchr($_FILES[‘fileToUpload’][‘name’], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = time() . ‘_’;
$manipulator = new ImageManipulator($_FILES[‘fileToUpload’][‘tmp_name’]);
$width = $manipulator->getWidth();
$height = $manipulator->getHeight();
$centreX = round($width / 2);
$centreY = round($height / 2);
// our dimensions will be 200×130
$x1 = $centreX – 100; // 200 / 2
$y1 = $centreY – 65; // 130 / 2

$x2 = $centreX + 100; // 200 / 2
$y2 = $centreY + 65; // 130 / 2

// center cropping to 200×130
$newImage = $manipulator->crop($x1, $y1, $x2, $y2);
// saving file to uploads folder
$manipulator->save(‘uploads/’ . $newNamePrefix . $_FILES[‘fileToUpload’][‘name’]);
echo ‘Done …’;
} else {
echo ‘You must upload an image…’;
}
}
[/code]

Awesome. Now you learned how to upload, resize and crop images using pure PHP. It is time to make some modern variations on the theme.

Join us next week to see how to upload, crop and resize images in a more modern way usingjQuery and HTML5.

Tags:

5 thoughts on “Upload, crop and resize images with PHP – Part 1”

  1. I see you’re checking that the file is an image by verifying the extension. I was recently doing something similar and found out that checking the MIME type is a more accurate way of checking files even those that have fake extensions. I’m also still wondering if MIME types are a robust means of doing so. Thanks for your tutorials though, they’re quite enjoyable.

  2. Hi,

    Just a quick q for you. Why do we have to do this:

    $newImage = $manipulator->resample(200, 200);

    are we using $newImage anywhere later on?

    Thanks

    S

  3. Hi, your tutorial is excellent and the best I have come across so for, but I realize it will allow just one image at a time. How can I get it to upload multiple images for a unique real estate property. I would appreciate your assistance very much. Thank you.

Comments are closed.