PHP Slim Post Request

danhodge

In Runtime
Messages
324
Location
UK
Hello again :lol:
So this one's been driving me a little crazy recently, not least of all because i've never looked at php before. I'm doing an assignment where i'm creating a restapi service on gcp, which gets data from a rpi and displays the data on a mobile app. And it's working beautifully for simple sensor data like temp and humidity. However, i'm trying to send images too, and... Well, it aint fun.

I've uploaded test images to the server directly, and my Get function works. However, my Post doesn't. And i've no idea if it's caused by my php script on the server side, or my Python script sending the data. And because it's going through the cloud, i've no idea how to debug this. So anyone who can help with this is a life saver. My main question is: What format does 'data' send the image from the python code, to the php code? Here's the code:

Python
Code:
def takePhoto():
  threading.Timer(10.0, takePhoto).start()
  now = datetime.datetime.now()
  ret, frame = cap.read()
  
  timestampStr = now.strftime("%d%b%Y(%H%M%S%f)")
  timeStr = str(timestampStr)
  path = os.path.dirname(os.path.abspath(__file__))
  fullPath = path +  '\\images\\frame' + timeStr + '.jpg'
  cv2.imwrite(fullPath, frame)  
 
  with open(fullPath, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    
  headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

  payload = {"image": encoded_string}
  imgdata = base64.b64decode(encoded_string)
  filename = 'some_image.jpg'  
  with open(filename, 'wb') as f:
    f.write(imgdata)
  r = requests.post(url='http://mycloudipthatishouldn'tpastehere/index3.php/images/postimagedata', data={'image':encoded_string}, headers=headers)

The PHP script

Code:
   // POST IMAGES
    $app->post('/images/postimagedata', function ($request, $response) {
    $input = $request->getParsedBody();
	
    $input['image'] = json_encode($input['image']);

    $sql = "INSERT INTO images (id,image) VALUES (:id,:image)";
	
    $sth = $this->db->prepare($sql);
    $sth->bindParam("id", $input['id']);
    $sth->bindParam("image",$input['image']);
    $sth->execute();
    $input['id'] = $this->db->lastInsertId();
    return $this->response->withJson($input);
});

And in the database, there are 3 fields, id, time_stamp and image, with id being auto increment and time_stamp being current_timestamp. Image is a Blob.

I know this is a lot, but really the main focus for me is input['image'], because i don't have a clue if that's right, i'm not entirely sure which part of this is the data being read in (and this is after about 8 hours of googling). PHP seems to go over my head.

Thanks for any help people can give me,
Danny
 
Last edited:

danhodge

In Runtime
Messages
324
Location
UK
Okay, scratch that, i'm finally managing to send it in, but it's saving in the database in this format ""\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDAAIBAQEBAQI" (but much longer), and as a result wont actually show in an imageview, whereas the images that work are binary files that i'm base64 decoding in the app to display (and i can't see what they look like, since notepad can't open that kind of thing).

So basically, can anyone actually identify what on earth that string looks like, if it's not a base64 encoded image? :lol:

Interestingly, I can open the original images with my Xamarin code:

Code:
 string image64 = j["image"];

                byte[] imageBytes = Convert.FromBase64String(image64);
                Bitmap im = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);

And the new ones with my python code:

Code:
with open("images-image(4).bin", "rb") as image_file:
    decoded_img = base64.b64decode(image_file.read())

What I need is to be able to open the new images in Xamarin, but i've got no idea what the difference between these two things actually is :silent:
 
Last edited:

carnageX

Private Joker,
Staff member
Messages
25,051
Location
Oregon
What you need to do is:
1. Read file (will be binary)
2. Base64 encode
3. Send as string or JSON object in POST body
4. Receive string or JSON
5. Parse (JSON) and decode from Base64 to binary
6. Save binary object (byte array) to DB (your column should be a binary type, not a varchar)
 

danhodge

In Runtime
Messages
324
Location
UK
What you need to do is:
1. Read file (will be binary)
2. Base64 encode
3. Send as string or JSON object in POST body
4. Receive string or JSON
5. Parse (JSON) and decode from Base64 to binary
6. Save binary object (byte array) to DB (your column should be a binary type, not a varchar)

Carnage you're my hero. Okay, so step 5 is the problem. Does 'base64_decode' convert the base64 into a binary file in PHP? Also, since i'm a tad behind on the terminology for these things, how is a binary file different from base64? I was under the impression that base64 was a binary file :lol:
And it's a BLOB in my DB, I assume that's alright since that's a binary object right?
 

carnageX

Private Joker,
Staff member
Messages
25,051
Location
Oregon
https://www.base64decode.net/php-base64-decode

Base64 is an encoded string. You take one object (usually binary/byte array - but it can be any data type) and convert it to a string for use in other places (such as transporting over HTTP calls) when you encode. Decode is the opposite: string -> original object (in your case, byte array/binary).

What DB engine are you using?
 
Last edited:

danhodge

In Runtime
Messages
324
Location
UK
Oh okay, makes sense, thanks. And i'm using PHPMyAdmin, and the DB is InnoDB. Not sure which of those (or either) is the database engine to be honest (my lack of php knowledge is semi-related to my lack of db usage).

Oh for the love of god, after around 10 hours trying to fix this problem, turns out the issue was just that when i run the python script, if i tried to encode the image in PHP, i get this error in the Python debugger:
"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" (along with a load more red as a result), so I didn't check the resulting image. Turns out this is what fixed it after all. I probably had it 5 hours ago :cry::cry:

Thanks for the help, laying it out in such a simple way showed me where I was going wrong. You're the best :heart:
 
Last edited:

carnageX

Private Joker,
Staff member
Messages
25,051
Location
Oregon
No problem, glad you got it figured out!

Laying out the logical steps helps me out a lot when debugging through weird issues.
 
Top Bottom