PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] Cant show image from the database using cakephp

 February 21, 2022     cakephp, cakephp-3.0, mysql, php     No comments   

Issue

I'm struggling with cakephp to implement a CRUD that has images. I managed to upload the image, save it (in a maria/mysql database) and now I can see the uploaded images in phpmyadmin.

Now I'm trying to show some image in the browser. In my MapasController I have the following method:

public function mostrarImagem($id){
      $file = $this->Mapas->get($id);
      $this->response->body($file->arquivo->uri);
      $this->response->type('image/png');
      //$this->response->download('filename_for_download.png');
      return $this->response;
  }

But calling for this in the browser gives me the message "The image 'http://localhost:8765/Mapas/mostrarImagem/5' cannot be displayed because it contains errors". If I uncomment the $this->response->download line, I download an invalid file. Dumping the $file variable I get the following content:

Mapa {#147 ▼
  +"id": 5
  +"titulo": "blablabla"
  +"arquivo": stream resource @8 ▶}
  +"created": Time {#145 ▶}
  +"modified": Time {#146 ▶}
  +"sistema_id": 5
  +"unidade_id": null
  +"[new]": false
  +"[accessible]": array:1 [▶]
  +"[dirty]": []
  +"[original]": []
  +"[virtual]": []
  +"[errors]": []
  +"[repository]": "Mapas"
}

The content for $file->arquivo is:

+"arquivo": stream resource @6 ▼
    wrapper_type: "RFC2397"
    stream_type: "RFC2397"
    mode: "rb"
    unread_bytes: 0
    seekable: true
    uri:     "data:text/plain;base64,iVBORw0KGgoAAAANSUhEUgAAA08AAAGnCAYAAABvtmzcAAAABmJLR0Q(....)
mediatype: "text/plain"
base64: true
options: []

What am I doing wrong?


Solution

A data URI isn't a valid PNG image source, and you won't get the data URI that way anyways, as there is no such property on a stream, what you are looking at in the dump is just debug info meta data, so that's the expected behavior.

You want to fetch the raw data instead.

$this->response->body(stream_get_contents($file->arquivo, -1, 0));

... for example.

See also

  • http://php.net/manual/book.stream.php
  • http://php.net/manual/function.stream-get-meta-data.php
  • http://php.net/manual/function.stream-get-contents.php


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing