Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8842963
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T11:05:55+00:00 2026-06-14T11:05:55+00:00

I am getting the picture encoded data in the php file through json. My

  • 0

I am getting the picture encoded data in the php file through json. My requirement is to store that images in server in one folder provided each image should be assigned a unique name. I am getting lot of doubts on how to store the image in a folder with unique name and then again the path of the image is stored in the database. I have seen couple of StackOverflow questions and online sources, but couldn’t get them clearly. This question seems simple to the ones who work on PHP. But as a newbie in php and as an Android developer, I am unable to understand that less-detailed answers. So, I would really appreciate if someone can help me with code snippets and explanation. I tried to keep my explanation of question and code with comments as clear as I can. If there are any mistakes, please go easy.The following is the code that I tried and got stuck at some points. Thanks in advance..

    <?php
    $response = array();

    // check for required fields
    if (isset($_POST['mailid']) && isset($_POST['category']) && isset($_POST['description']) && isset($_POST['contactNum']) && isset($_POST['lookingto']) && isset($_POST['image'])) {

        $usermail = $_POST['mailid'];
        $category = $_POST['category'];
        $description = $_POST['description'];
        $contactNum = $_POST['contactNum'];
        $lookingto = $_POST['lookingto'];
        $base=$_POST['image'];

        $binary=base64_decode($base);

        $folder = "images/"; // This is my folder "images" in which pics have to be stored.

        $file = fopen('storepic.jpg', 'wb');  // Here I have to give name dynamically to each pic provided that should be unique. Here I mentioned pic name as storepic.jpg, a static name.

        fwrite($file, $binary);

        fclose($file);

        // include db connect class
        require_once __DIR__ . '/db_connect.php';

        // connecting to db
        $db = new DB_CONNECT();

        // mysql inserting a new row
        $result = mysql_query("INSERT INTO details(usermail, category, description, contactnumber,posting_for) VALUES('$usermail', '$category', '$description','$contactNum','$lookingto')");

//// Even after giving dynamic name how can we store the path of the dynamic named image into database in the above query. For that what should be done here..

        // check if row inserted or not
        if ($result) {
            // successfully inserted into database
            $response["success"] = 1;

            // echoing JSON response
            echo json_encode($response);
        } else {
            // failed to insert row
            $response["success"] = 0;


            // echoing JSON response
            echo json_encode($response);
        }
    } else {

        $response["success"] = 0;


        // echoing JSON response
        echo json_encode($response);
    }
    ?>

Even in other php file I am retrieving the data by select query. I am able to get the normal data what I inserted could get it on Android client side app. But then again how to get the image from the path for later converting into base64 encoded data and then echoing as json response..

NOTE:- My UI is not form. It’s an Android UI..

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T11:05:56+00:00Added an answer on June 14, 2026 at 11:05 am
        // A very basic field validation. You should really use mysqli* or PDO*.
    
        $fields = array(
            'usermail'    => 'mailid',
            'category'    => 'category',
            'description' => 'description',
            'contactNum'  => 'contactNum',
            'lookingto'   => 'lookingto',
            'binary'      => 'base',
        );
        $okay = true;
        foreach($fields as $var => $field)
        {
             if (!isset($_POST[$field]))
                 $okay = false;
             if ('binary' == $var)
                 ${$var} = base64_decode($_POST[$field]);
             else
                 ${$var} = mysql_real_escape_string($_POST[$field]);
        }
        if (!$okay)
        {    
            $response["success"] = 0;
            Header("Content-Type: application/json;charset=UTF-8");
            die(json_encode($response));
        }
    
        $folder = "images/"; // This is my folder "images" in which pics have to be stored.
    
        $file   = tempnam($folder, 'image');
    
        $fp     = fopen($file, 'w');
        fwrite($file, $binary);    
        fclose($file);
    
        /* BUT WHAT IF THE FILE IS NOT JPEG?
           Then you use GD library and do:
    
           $gd = ImageCreateFromString($binary);
           if (!$gd)
           {
               // Abort. Image was invalid.
           }
           // Here you can even resize it.
           ImageJPEG($gd, $file, 75); // Quality 75%; useable values from 40 to 100
           ImageDestroy($gd);
        */
    
        ...
    
        $result = mysql_query("INSERT INTO details(usermail, category, description, contactnumber,posting_for) VALUES('$usermail', '$category', '$description','$contactNum','$lookingto')");
    
        // I assume that the above table has an unique ID. So we retrieve it
        $lastid = mysql_insert_id(); 
    
        rename($file, $newfile = sprintf("%s/img%08d.jpg", $folder, $lastid));
    

    Above, you do not need a column name for the file name since the name is the same as the row ID: if ID is 1234, the image is images/img00001234.jpg.

    Otherwise you have to issue another query:

        UPDATE details SET filename='$newfile' WHERE id = $lastid;
    

    To retrieve

    In all cases you’ll receive some information about the row to retrieve; at a minimum its ID, or anyway some conditions you can plug into a WHERE. If, for example, you get the user email (and it is a unique key), you’ll use WHERE email='...'.

    So you will be able to issue a SELECT * FROM details WHERE... and among these details you will find either the ID, or the filename field.

    In the first case you’ve got enough to build the filename and do not even need the database query, but remember that anyone knowing the ID can now access the image, this may be harmless or even desired (e.g. user public avatar image) but sometimes it might not be.

    $lastid  = (int)$_REQUEST['id'];
    $newfile = sprintf("%s/img%08d.jpg", $folder, $lastid);
    

    Note that the syntax is the same as above; the (int) cast is to remember that this is user-supplied information and could contain all sorts of malicious crud.

    In the second case you’ll issue a WHERE and fetch either the ID or directly the filename field from the retrieved tuple.

    Having the image path, you can send it to the user… if the image is there. Just checking.

    if (!is_readable($newfile))
    {
        Header('HTTP/1.0 404 Not Found')
        readfile('/path/to/beautiful/error-page.html');
        die();
    }
    // if you are really paranoid, or want to support different quality images,
    // you can $gd = imageCreateFromJPEG($newfile); here, check it succeeded or
    // send 404 / 500 error if it failed, manipulate $gd and send it along with
    // ImageJPEG($gd, '', $quality); instead of the readfile() down there. With
    // this approach, you'll better not send Content-Length, though. This makes
    // image DOWNLOADS more awkward (you don't see "104K of 1.3M downloaded").
    
    Header('Content-Type: image/jpeg');
    Header('Content-Length: ' . filesize($newfile));
    readfile($newfile);
    die();
    

    …and that’s it. In the HTML source calling the above, you might have:

    <img class="avatar" src="images.php?id=<?php echo $details['id']; ?>" />
    

    (the PHP generating that HTML needs to access the database and fetch $details, of course).

    There are other setups that allow the “calling” PHP to save the database tuple information in the _GET parameters in a protected way, so that even if the user sees that the image was retrieved with

    image.php?id=1234
    

    and knows that Bob has ID 7654, still she can’t retrieve the image by changing 1234 into 7654, but I don’t know whether this is of interest to someone.

    With Web browsers, setting the content is enough. Using Internet Explorer you might need the file to end in .jpg, and this in turn might require using a URL Rewriting scheme.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am getting a picture from the iPhone's camera in one nib file (getPhoto.xib),
What's the fastest way of getting a picture into a SQLite data store for
I take the picture with camera.take picture and getting those data in on Picture
I'm getting a JSON encoded array from Facebook which contains: [{message:D\u011bkujeme Zuzana Boh\u00e1\u010dov\u00e1 za
I want to write MJPEG picture internet stream viewer. I think getting jpeg images
I'm getting data from a database, and one of them its a link to
New to PHP- If I have PHP getting a picture name from a form:
After changing the file permissions to allow a picture upload I am now getting
I there a way to getting picture(image) from URL without downloading? I use the
I am using LinkSprite JPEG Color Camera to take picture. I am getting hex

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.