Saving file name as `BLOB` in database - php

While I'm sending file ( type="file") to database (PHPmyAdmin), instead of saving with file name it saves as BLOB as shown in the following figure.
I found the the similar question Saving Files as blob in database ajax php pdo
here but didn't help me. My php code is as follows for sending file to the database.
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $get.".".$ext; //$newname='newfilename.'.$ext
$target ="folder/".$newname;
$doc= move_uploaded_file( $_FILES['file']['tmp_name'], $target);
$sql="INSERT INTO apply(mobile,doc,position)
VALUES (' $mobile','$newname',' $position')";
$query=mysqli_query($conn, $sql);
The file is sending to target folder (named folder) with the correct required name but Why I'm not getting the same name in the database. What's going wrong in my code?
Thanks in advance.

First of all, you should not tore files into the database directly because of critical performance issues.
Suggested way is to store files in file system, and store their path in database as TEXT or Varchar.
Now coming to your question:
While I'm sending file ( type="file") to database (PHPmyAdmin), instead of saving with file name it saves as BLOB as shown in the following figure.
Every file is composed of binaries but in different order and format. Storing it in database is not actually tricky. Database converts them into array of bytes/ stream of bytes and then stores these byte format data into the table.
When a fetch query is fired, it returns the exact byte stream in response. And at application level, these bytes are treated as files by their respective encoding techniques.
It's worth reading this post and subsequent link in the accepted answer.

Related

read pdf content from BLOB in MySQL

i have developed a system which parses and stores emails into a MySQL database.
I save the attachments as an array of objects in JSON into a MEDIUMBLOB field.
Everything works almost as expected. At least when saving.
When i try to read the attachments i only get back the images, but not the pdf file.
The BLOB has the following 'dummy' content:
[
{
"filename":"img1.png", "ext":"png", "type": "image/png", "size":4096,
"dispo":"inline", "cid":"123#abc", "content":"base64_encoded binary-
data"
},
{
"filename":"pdf1.pdf", "ext":"pdf", "type": "application/pdf",
"size":4096, "dispo":"attachment", "cid":null,
"content":"base64_encoded binary-data"
}
]
The attachments are written as follows:
json_encode($attachmentsDB,JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).
I debugged, but somehow when i fetch data BLOB from the DB - in this case - the last element = the pdf-file is not returned. Only the preceding image files.
When i hardcode the data and try my code it works perfectly.
The data isn't truncated either.
It seems that it's not a memory problem
If anybody could give me a hint please... ?
Many thanks in advance
Storing big data in database is bad idea because most case it will make your server slow..
rather you can copy your pdf in a folder by php script then store it's references in sql database...
Now you can easily read your pdf content from database..
Or you can check this
PHP: Upload a Pdf to SQL Database
As mentioned by #Shadow:
Mediumblob is up to 16MB only. Base64 drastically increases the size of the data, so there may be some data truncation even if the original binary size is below 16MB. Pls include the code that stores and retrieves the files from the database.
i modified the field to LONGBLOB and now it seems to work fine! :-)

Encode image in base64 format and store in mysql database , not woring for all type of images with php and laravel

I have upload one image and want to store it in base64 encoded format in database. for some images it is not working to store in database.
In my local system it is working for all images but on live server it not stores some of images in base64 format in mysql database . my code to store image in database is below,
$handle = $_FILES["file_name"]["tmp_name"];
$fileObj = $req->files->get('file_name');
$filename = $fileObj->getClientOriginalName();
$fileInfo = pathinfo($filename);
$fileExt = $fileInfo['extension'];
$file1 = $req->files->get('file_name');
$mime = $file1->getMimeType();
$fileName = base64_encode(file_get_contents($handle));
$File = new File();
$File->file_name = $fileName;
$File->save();
from above code if I chane below line then it is working
$fileName = (file_get_contents($handle));
but I want to store it in base64 encoded format in mysql database
in my data table this field's type is "long blob".
If you base64 the image, the column should be longtext. Blob are for binary.
But think again before storing files to database.
Storing image to database is a bad practice because whenever your app layer (in your case, php) retrieve the images, it will increase your memory usage and if you are retrieving list, your server can easily out of memory if multiple users are using the same function.
Storing data as base64 make it worse because the data size is bigger (8/6)
The best practice is to store the file in a file server and only the necessary meta or link in the database.
Storing image details instead saving a blob is better. You can store all images on another server or the same server in a folder and store the path , name of that image in mysql. To retrieve it you can simple get the file from the path stored in mysql.

saving blob file in oracle using php

please tell me how can i insert pdf or doc files into oracle blob field .
this is the code which i use for varchr data type and this is fine but how can i save the files into blob data type please help me !!!
if(isset($_POST['elm1'])) {
$pdata=$_POST['elm1'];
$profile_name=$_POST['profilename'];
$profile_id=$_POST['profileid'];
$query = "insert into prepaid_profiles values('$profile_id' , '$profile_name','$pdata')";
$result = oci_parse($dbc,$query);
oci_execute($result);
oci_close($dbc);
When user uploads file, save it in server, show only link to it. When saved text from editor, you save only link (with rest of text). File is still on server.
But if you really need to make your database huge and slowly, read uploaded file with file_get_contents, that convert it to base64 and save to database long string (no idea why it's better).
TinyMCE don't need file content in <textarea>.

PHP binary files (images) corrupted when stored in database but not DOCs from email attachments

The problem is when I receive email attachments images/binary data becomes corrupted however when I upload files to the same database table they aren't corrupted.
On the left side is the normal image that works (when renamed to PHP and it's binary data is copied). The right side is the image after it's been corrupted. I figured I'd add the image because someone may see it and just know what is going on here. PHP code below...
So I have other files including images stored in the database and they work just fine...
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
//INSERT INTO table (data), ($data);//etc
However the error is occurring in the PHP code that I use to clean up emails and then store them in the database along with attached files. I know that the attached files are being targeted in PHP correctly so it's simply HOW I'm storing it which seems to be the problem. The data column in MySQL is longblob and uploading images before sending them works fine but when I RECEIVE emails this code that handles putting received attachments is what breaks (using the same database table).
$data = mysqli_real_escape_string($connection,base64_decode($email['attachments'][$t]['attachment']));
$data = mysqli_real_escape_string($connection,$email['attachments'][$t]['attachment']);
$data = base64_decode($email['attachments'][$t]['attachment']);
$data = mysql_real_escape_string(base64_decode($email['attachments'][$t]['attachment']));
$data = addslashes($email['attachments'][$t]['attachment']);

How to store a PDF file in MySQL database?

How to store a PDF file in a MySQL database using PHP?
Using BLOB (Binary Large Object) (longblob datatype)
$fileHandle = fopen($fileUpload, "r");
$fileContent = fread($fileHandle, $fileUpload_size);
$fileContent = addslashes($fileContent);
$dbQuery = "INSERT INTO myBlobs VALUES ";
$dbQuery .= "('$fileContent')";
The full tutorial available here
but it's strongly recommended to store files on the file system, and just add a reference in the DB (a field with the file path and name). Several reasons:
Faster
Easier to access (don't need any special application)
Faster backups
Less space
Use a type BLOB.
Here's an example in PHP
As others mentioned, you can use a BLOB type.
Alternatively, what you can also do is save the PDF in the file system and save the relative link to it into the database. This is the same principle that applies for saving things such as Thumbnails and other data types that may be unique to the user and are expensive in terms of resources.
If you are simply looking to store uploaded PDF files on your server, it's more common to copy the file to a given directory with a unique filename and simply store the full path of that file in your MySQL table.
If you are definitely looking to store the full binary data of the file in your MySQL database, then you will have to do a little more work to put the binary data into a BLOB field in MySQL and then to turn it back into a file when you pull it out again at a later date.
You will probably want to store not only the binary data for the file in your MySQL table, but also the filename, filetype and possibly even the size of the file (for listing on your webpage). You will probably want a table such as;
CREATE TABLE files (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
filename VARCHAR(128) NOT NULL,
mimetype VARCHAR(64) NOT NULL,
data MEDIUMBLOB NOT NULL
);
In your PHP, you can then insert an uploaded file with something like the following;
$filePointer = fopen($_FILES['fileUpload']['tmp_name'], 'r');
$fileData = fread($filePointer, filesize($_FILES['fileUpload']['tmp_name']));
$fileData = addslashes($fileData);
$sql = "INSERT INTO files (filename, mimetype, data) VALUES( $fileName, $fileType, $fileData )";
Getting the file back out again will required a dedicated script that selects the appropriate file and then uses a series of 'header' commands to push that file back down to the browser with in a form that the browser knows how to handle it.
You can read a full tutorial about this here.

Categories