Upload image from Android app to server using PHP without any library

Image uploading is necessary in any Android app now a days.
We can upload image to our server from the Android app. Here I used PHP at the server side to catch and save the image file.

Here we did it without using any kind of external library. So you can directly use it in your project without any hassle.

First we pick the image from the gallery. You can checkout my article, “Pick image from gallery before and after KITKAT version in Android” and get the path of the image file in the “path” variable.

Then use following code snippet to upload that image to the server.

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
  connectURL = new URL("http://example.com/imageupload.php");
  HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
  conn.setRequestProperty("Connection", "Keep-Alive");
  conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

  DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
  dos.writeBytes(twoHyphens + boundary + lineEnd);

  HashMap<String, String> params = new HashMap<>();
  params.put("key", "value");	//post params that you want yo send
  StringBuilder result = new StringBuilder();
  for (Map.Entry<String, String> entry : params.entrySet()) {
    result.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + lineEnd);
    result.append(twoHyphens + boundary + lineEnd);

  if (!String.valueOf("").equals(path)) {
    dos.writeBytes("Content-Disposition: form-data; name=\"" + "picture" + "\";filename=\"" + "picture.jpg" + "\"" + lineEnd);
    fis = new FileInputStream(path);
    int bytesAvailable = fis.available();

    int maxBufferSize = 8192;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    int bytesRead = fis.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
      dos.write(buffer, 0, bufferSize);
      bytesAvailable = fis.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fis.read(buffer, 0, bufferSize);
    dos.writeBytes(twoHyphens + boundary + lineEnd);

  InputStream is = conn.getInputStream();

  int ch;

  StringBuffer b = new StringBuffer();
  while ((ch = is.read()) != -1) {
    b.append((char) ch);
  json = b.toString();
} catch (MalformedURLException ex) {
} catch (IOException ioe) {

Make sure that you call this code snippet inside of AsyncTask or Thread. Once you get the response from the server, your image has been uploaded to the server.

Now here is the code for PHP to move the uploaded to the same directory as php file.

    move_uploaded_file($_FILES['picture']['tmp_name'], $_FILES['picture']['name']);

And done! You can find your uploaded image in “images” directory on your server.

PDO connection class in PHP [OOP approach with singleton pattern]

Now a days in PHP and Mysql connection after deprecation of Mysql, PDO [PHP Data Objects] and Mysqli is the best choice. In that PDO is widely used in new frameworks because it has more benefits than Mysql and Mysqli. Here is the list of features of PDO.

  • Have dirvers for 12 different databases [list them using print_r(PDO::getAvailableDrivers());]
  • OOP approach
  • Named parameters
  • Object mapping
  • Prepared statements
  • Fast performance
  • Stored procedures

Now here I am showing you the class of database connection that I used for my work. In that I use singleton pattern that eliminate the chances of having more than one instance of the class object in memory.


class database
    public $dbc;
    private static $instance;

    private function __construct()
        $this -> dbhc= new PDO('mysql:host=localhost;dbname=example', "root", "");

    //singleton pattern
    public static function getInstance()
        if (!isset(self::$instance))
            $object = __CLASS__;
            self::$instance = new $object;
        return self::$instance;


You can use above class using following example code.

//get database connector by calling static method of database class [singleton pattern]
$db = database::getInstance();

//insert operation
$sql = "insert into `user` (`username`, `password`, `fullname`, `email`) values (:username, :password, :fullname, :email)";    //named parameters

$query = $db -> dbc -> prepare($sql);

$result = $query -> execute(array(":username" => $username, ":password" => $password, ":fullname" => $fullname, ":email" => $email));    //named parameters value
    echo "Insert Successfull.";
    echo "Insert Fail."

//update operation
$sql = "update `user` set `username` = ?,  `password` = ?, `fullname` = ?, `email` = ? where `user_id` = ?";    //prepared statements

$query = $db -> dbc -> prepare($sql);

$result = $query -> execute(array($username, $password, $fullname, $email, $user_id));   //prepared statements value
    echo "Update Successfull.";
    echo "Update Failed.";

//delete operation
$sql = "delete from `user` where `user_id` = ?";   //prepared statements

$query = $db -> dbc -> prepare($sql);

$result = $query -> execute(array($user_id));   //prepared statements value
    echo "Delete Successfull.";
    echo "Delete Failed.";

//select operation
$sql = "select * from `user` where `user_id` = ?";   //prepared statements

$query = $db -> dbc -> prepare($sql);
$query -> execute(array($user_id));   //prepared statements value
$query -> setFetchMode(PDO::FETCH_ASSOC); // [PDO::FETCH_NUM for integer key value]
$result = $query -> fetchAll();

Download database class file here : https://www.mediafire.com/view/lmmlosnf26v5lla/db_config.php

References :

How to delete folder with contents in it in PHP

Many times in PHP, we need to delete the folder containing subfolders and files. So we have to check for depth and according to that we have to delete files first and then folders. But if we don’t know the content of it then it will be very difficult task to delete it. I am working on some stuff that need to be delete once it is utilized so I make the function that check for the subfolders and files and recursively delete the contents of it.

Here is the function for delete.

function delFolder($folder) 
	foreach(glob($folder . '/*') as $file) 

Here delFolder is the function that perform delete task.

Here we use following of the PHP function.

  • glob — Find pathnames matching a pattern
  • is_dir — Tells whether the filename is a directory
  • unlink — Deletes a file
  • rmdir — Removes directory

Download the full example with comments here : https://www.mediafire.com/view/winyqdt2fr1jsll/delFolder.php