6

I am using PostgreSQL on a Laravel installation. A table has a byte-type field that is being used to store binary data (base64_encoded file contents).

When I use Eloquent to retrieve the table I get a resource type variable being returned in this field.

How can I rather retrieve this as a string?

$raw = Media::where('id','=',$id)->first();
$raw->file_data = base64_decode($raw->file_data);   // doesn't work
1

2 Answers 2

10

As the author of this question did not post the details to the answer, I will post my findings here.

As the returned field is a handle to a stream you can use the stream_get_contents function to read the value into a string, you can then use pg_unescape_bytea to get the actual value of the bytea data. Finally use the htmlspecialchars function if you wish to display the bytea data in HTML.

Example code:

$my_bytea = stream_get_contents($resource);
$my_string = pg_unescape_bytea($my_bytea);
$html_data = htmlspecialchars($my_string);
Sign up to request clarification or add additional context in comments.

1 Comment

If you're using postgresql>9 and haven't SET bytea_output = 'escape' then the invoking to pg_unescape_bytea() should be removed to prevent unintended unescape.
1

The answer was to use stream_get_contents on the stream. duh.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.