Today, one of my friends asked me how to select photos from gallery and upload it to server in iPhone. I think it is much helpful to write a tutorial with example source code, instead of asking him to google the solution. To make sure that my example works properly (it always works properly though), I will write a server side function which accepts the upload images. The server side functions will be implemented by PHP, a very simple script language. After that, I will write another tutorial for upload images from gallery or camera in iPhone and iPad.

In this tutorial, I will start from the simplest case. Then, I will make the script more complicated. First, let’s talk about uploading a file and save it on server.

<?php //ignore this comment >
    $uploadFolder = "./upload";
    if (!file_exists($uploadFolder)) {
        mkdir($uploadFolder);
    }
    
    $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $uploadFile)) {
        echo "Successfully";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

The above php script will make a folder to save the uploading file, if the folder doesn’t exist. Then, it will save the incoming file to this folder.

Ok, now I will make it more complicated. As this tutorial is talking about how to upload photos to server from iPhone. So we need to set some constrains such as the incoming files must be images. Let’s see the example source code version 2:

<?php //ignore this comment >
    $uploadFolder = "./upload";
    if (!file_exists($uploadFolder)) {
        mkdir($uploadFolder);
    }
    
    $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"]);

    if(!(getimagesize($_FILES["fileToUpload"]["tmp_name"]) !== false)) {
        echo "Sorry, your image is invalid";
        exit;
    }

    $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));
    if($imageFileType != "jpg"
            && $imageFileType != "png"
            && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        exit;
    }

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $uploadFile)) {
        echo "Successfully";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

Great! In above php example source code, we successfully add two constrains to detect the incoming files are real images. If you want to limit the incoming file’s size smaller than 2M, you can add another constrain:

<?php //ignore this comment >
    $uploadFolder = "./upload";
    if (!file_exists($uploadFolder)) {
        mkdir($uploadFolder);
    }
    
    $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"]);

    if(!(getimagesize($_FILES["fileToUpload"]["tmp_name"]) !== false)) {
        echo "Sorry, your image is invalid";
        exit;
    }

    $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));
    if($imageFileType != "jpg"
            && $imageFileType != "png"
            && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        exit;
    }

    if ($_FILES["fileToUpload"]["size"] > 2000000) {
        echo "Sorry, your file is too large.";
        exit;
    }

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $uploadFile)) {
        echo "Successfully";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

Test Upload Script with HTML FORM

The mechanism of selecting and uploading image to server is the same as submitting a form in html. To test above PHP script, we can simply create following test case:

<html>
    <head>
        <title>PHP Upload Test</title>
    </head>
    <body>
        <form action="http://192.168.31.105/uploadimage.php" method="post" enctype="multipart/form-data">
            <input type="file" name="fileToUpload" />
            <input type ="hidden" name="partyGroupId" id="partyGroupId" value="10050"/>
            <input type="submit" name="submit" value="Click to Upload"/>
        </form>
    </body>
</html>

Select and Upload Multiple Photos from iPhone

The above example only shows you how to handle one image uploading. However, the real use case is more complicated than that. In most popular iOS apps, they allow users to select and upload multiple photos at once. To support this scenario, we need to change the above PHP example source code a little bit.

<?php  //ignore this comment >
$uploadFolder = "./upload";
if (!file_exists($uploadFolder)) {
    mkdir($uploadFolder);
}

if (is_array($_FILES["fileToUpload"])) {
    $numberOfFiles = count($_FILES["fileToUpload"]["name"]);
    for ($i = 0; $i < $numberOfFiles; $i++) { //ignore this comment >
        $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"][$i]);
        $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));

        if (!(getimagesize($_FILES["fileToUpload"]["tmp_name"][$i]) !== false)) {
            echo "Sorry, your image is invalid";
            exit;
        }

        if ($_FILES["fileToUpload"]["size"][$i] > 10000000) {
            echo "Sorry, your file is too large.";
            exit;
        }

        if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            exit;
        }

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $uploadFile)) {
            echo "Upload image ".basename($_FILES["fileToUpload"]["name"][$i])." successfully!";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

How to Test Above PHP Script for Selecting and Uploading Multiple Images from iPhone

Before we start to build the iPhone app to select and upload multiple images, let’s make sure that our backend application is able to accept multiple images uploading. Again, we can use HTML form to simulate this action. Here is a test case to select and upload two images at once. You can add more images by adding more input tag in the html form.

<html>
    <head>
        <title>PHP Upload Test</title>
    </head>
    <body>
        <form action="http://192.168.31.105/uploadimage.php" method="post" enctype="multipart/form-data">
            <input <!->-->
type="file" name="fileToUpload[]" />
            <input <!->-->
type="file" name="fileToUpload[]" />
            <input type ="hidden" name="partyGroupId" id="partyGroupId" value="10050"/>
            <input type="submit" name="submit" value="Click to Upload"/>
        </form>
    </body>
</html>

As we assign the name=”fileToUpload[]” in each input tag, the server side will treat the incoming fileToUpload variable contains several files. Therefore, the php script will use for loop to save every uploaded image.

Previous PostNext Post

27 Comments

  1. Hi…. Thanks for the multiple image upload code…
    But now I want to upload multiple videos.. so which are the changes need to do in php?
    In iOS I will send nsdata of video but how to haldle it in Php?

    Thanks

  2. Hi, downloaded your files… can’t seem to get it to work. it says its successful uploading… however i look in my ftp in filezilla… and no images are there :/

    1. You’d better to check the code. I copy the example code from my project. BTY, my current example code is for uploading images. I have set some constrain in the code.

      1. I checked the code. What constraints do you mean? It creates the folder in my server. I can see the mkdir function… however doesn’t put the image in it :/ what constraints are you talking about?

        1. Do you have any PHP programming background? If yes, it will be a very simple case to debug and find the solution. If no, please study the basic PHP programming first. Here I give you some tips about how to debug and find the problem:
          1. check $_FILES[“fileToUpload”] value
          2. check your image size
          3. check your image extension, only lower case .jpg, .png, .jpeg, gif supported.

  3. My encoded string coming from ios app is as below:
    String is too long, pasting just a portion
    Need to know how to decode and upload it to server using php

    iVBORw0KGgoAAAANSUhEUgAAAoAAAAKACAIAAACDr150AAAAAXNSR0IArs4c6QAAABxpRE9UAAAAAgAAAAAAAAFAAAAAKAAAAUAAAAFAAAN+qq4fJwIAAEAASURBVHgB7LwJc2tZdl6ZmW/igHmeJwIkSJCYSBAgQRIAMU……………

    1. Hello Puneet,

      First, if you want to decode this string, you have to know how you app encode this string, otherwise there is no way to decode. Another possibility, i can just save this string in your database. When your app needs, you can return the encoded string to app and let app to decode it. It is much safe.

  4. Can we show the multiple images we have selected in image view in view controller rather than upload them direct from gallery to the server?

      1. Which header file of ELCImagePickerController is use at above? and i’m getting an error with ur code , in – (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info method . What is this in the method? POST_BODY_BOURDARY, where it come from. I just copy and paste ur code

  5. If I use this code to upload videos from the iphone to the server, there are problems — once I click the “choose file” button and select the video I want, the video loads and I click on the “use” button to attach it to the form. However, iOS then shows me a “compressing video…” message and the entire process stops. Any ideas on how to get passed this issue? The video I am trying to upload is maybe 20-30 seconds. thanks

  6. I downloaded the sample into XCode and ran it on my iPhone – it works if the files are jpg but not heic

Leave a Reply to James Liu Cancel reply

Your email address will not be published. Required fields are marked *