Arun Code
Arun Code

Reputation: 1638

Uploading a image to server using post PHP

Am planning to develop a image upload API which need to upload a image to the server location as part of my project. (The usage will be to upload user pics and avatar using an android app)

The API which should be similar to Imgur API in which we can use a post request to upload a binary image to the server.

I searched through multiple questions, all am getting is using multi part request which requires html form submitting. Since my aim is to create a API, html form submitting will be impossible.

Anyway am submitting a sample code which uses html form to upload an image. Can someone show to how can I modify the script to meet my requirement?

  <html>
          <body>

<form action="photo.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
                </body>
                </html>

PHP code

<?php
$allow = array("jpg", "jpeg", "gif", "png");

$todir = 'uploads/';

if (!!$_FILES['file']['tmp_name'] ) // is the file uploaded yet?
{
    $info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file

    if ( in_array( end($info), $allow) ) // is this file allowed
    {
        if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
        {
            // the file has been moved correctly
        }
    }
    else
    {
        // error this file ext is not allowed
    }
}
?>

Upvotes: 2

Views: 325

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146410

Some remarks about your server-side code in no particular order:

  • As you can read at Handling file uploads, the correct way to verify an upload is comparing the ['error'] subkey with UPLOAD_ERR_OK (codes explained here). Don't use ['tmp_name'] for that.

  • Don't let the end user pick the actual file name on your server. You'd better generate a unique name yourself and keep the display name elsewhere (e.g. a database)

  • The recommended way to determine a file extension is pathinfo:

    pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)
    
  • File extension provided by the user is not a reliable way to determine file type. For pictures, the getimagesize function is often used.

Upvotes: 2

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146410

multi part request which requires html form submitting

That's wrong. It requires a properly formatted request (headers and body), period. In fact, the server has no way to know what piece of software was used to generate the request—or if you just typed the bytes yourself in a console ;-)

Upvotes: 1

Related Questions