I'm trying to store an image into an SQL database without using temporary files. I don't want to use temporary files as too many of them could cause problems. I saw this tutorial: but that uses temporary files as does this question and this . I have the image as a php resource and not a file. Trying to put a base64 string of the image in fails as well.I am writing to a blob. Thanks for looking, any help would be appreciated.
Asked
Active
Viewed 680 times
1
-
2I'm not sure the architecture of PHP makes it reasonable to directly receive the file without using a temp directory. – Denys Séguret Jun 12 '12 at 17:27
-
@dystroy is right - the file needs to go somewhere once it's off the user's computer, no? You could just use the `$_FILES['uploadedfile']['tmp_name']` file, but that's as close to not re-saving as you can get. – Josh Toth Jun 12 '12 at 17:33
-
I was hoping that the file could just be in the sql database and not as a temp file. – jersam515 Jun 12 '12 at 17:34
-
You can do that in most languages but PHP doesn't permit it as it lets Apache handle the uploading. – Denys Séguret Jun 12 '12 at 17:36
-
1The good news, though, is that the temp file is automatically deleted by Apache after the request is complete. So you will not end up with thousands of temp files "causing problems," as you say. – Jazz Jun 12 '12 at 18:11
2 Answers
2
Output buffering!
ob_start();
imagejpeg($image_resource);
$image = ob_get_clean();
$image now holds image data you can write to a blob field in your mysql database.

John David Ravenscroft
- 191
- 6
-
That's for **output** buffering : "While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer." – Denys Séguret Jun 12 '12 at 17:45
-
p.s. try to leave it 24-48 hours before selecting an answer :) – John David Ravenscroft Jun 12 '12 at 17:45
-
-
yes it is. `imagejpeg()` will output to a file or to the output stream. the code I gave you captures that stream. you are only buffering between `ob_start()` and `ob_get_clean()` you can then continue outputing to stream as normal. `ob_get_clean()` closes the buffering session and returns whatever was stored in it. – John David Ravenscroft Jun 12 '12 at 17:48
-
1
PHP isn't really built to handle long tasks or file uploading.
That means it relies on Apache functions for file upload.
So you have to do as all examples show you : let Apache handle the uploading in a temp directory and only after put the file in database.

Denys Séguret
- 372,613
- 87
- 782
- 758
-
OK, I will do that, thanks for helping all even if what I wanted to do is impossible/impracticle. – jersam515 Jun 12 '12 at 17:43
-
That's a good practice for most language, though. The good news is that Apache is good at handling the upload. – Denys Séguret Jun 12 '12 at 17:44