Base64 encode uploaded file then save in database

前端 未结 1 1291
礼貌的吻别
礼貌的吻别 2021-01-08 01:05

I want to base 64 encode uploaded file then save this into Blob type column of a table in MySQL database.

I have tried built in PHP function base64_encode with file

相关标签:
1条回答
  • 2021-01-08 01:42

    As @Sjoerd and @zerkms correctly point out, you do not need to do this - a blob column is be used to store raw binary data, so you can bypass the Base64 process and insert the raw data of the file.

    If you want to store images in a database (which, by the way, I personally don't like to do) it is better to store the raw data - Base64 encoding the data makes it larger, and means that it must be decoded before the image is rendered, which adds processing overhead.

    This is how you can insert the raw binary data (assuming the MySQL extension):

    $data = file_get_contents($_FILES['name_of_control']['tmp_name']);
    $data = mysql_real_escape_string($data);
    
    $query = "
      INSERT INTO table
        (`blob_column`)
      VALUES
        ('$data')
    ";
    
    mysql_query($query);
    

    If you really do want to Base64 encode it (in which case it could just be stored in a varchar), just just add a base64_encode() call:

    $data = file_get_contents($_FILES['name_of_control']['tmp_name']);
    $data = base64_encode($data);
    
    // There is an argument that this is unnecessary with base64 encoded data, but
    // better safe than sorry :)
    $data = mysql_real_escape_string($data);
    
    $query = "
      INSERT INTO table
        (`varchar_column`)
      VALUES
        ('$data')
    ";
    
    mysql_query($query);
    
    0 讨论(0)
提交回复
热议问题