how to convert the file content to byte array with php

13,449

PHP doesn't have a "byte array" data type. What it has is a string type, which is a byte array for all intents and purposes. To read the binary content of a file into a variable which is as close to a byte array as you'll ever get in PHP, do:

$content = file_get_contents($_FILES['my_file']['tmp_name']);

Yup, that's it. Nothing more to do.

I'm not particular familiar with the sqlsrv API, but perusing its documentation it appears that you can (need to?) set a flag this way to flag the data as being binary:

sqlsrv_query($conn, 'INSERT INTO files (file_data) VALUES (?)', array(
    array($content, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING, SQLSRV_SQLTYPE_BINARY)
));
Share:
13,449

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to save (insert) a uploaded file to a database with PHP, which the type of the database filed is varbinary.
    Finally I want to have the content of VarBinary (output) like when file is read in C# and then is stored in byte array and array is inserted to VarBinary.
    Also my connection to the database is with sqlsrv.
    The type of my files are just PDF and images.
    I try this code but my output is different with the output of C#:

    $handle=@fopen($_FILES["my_file"]["tmp_name"], 'rb');
    $content= file_get_contents($_FILES["my_file"]["tmp_name"]);
    $content = unpack("N*",$content);
    $content=  implode($content);
    $sql = "INSERT INTO files (file_data) VALUES (CONVERT(varbinary(MAX)?)";
    $params=array();
    array_push($params,$content);
    $table=sqlsrv_query( $conn, $sql, $params);
    

    "$conn" is the name of my connection that works correctly.

    • Botonomous
      Botonomous over 7 years
      Why is this tagged c#?
    • Admin
      Admin over 7 years
      @Botonomous because I want output like the output of C#.
    • Lidaranis
      Lidaranis over 7 years
      I think what he is going for is PHP# ?
    • Botonomous
      Botonomous over 7 years
      @yasaman-ghassemi What do you mean 'output like the output of C#' Do you mean console output?
    • Admin
      Admin over 7 years
      @Botonomous no, my mean is the content that is stored in database.The content of that varbinary field.