Equivalent FileInputStream in PHP

1

I would like to pass a PDF file to a binary text string to store it in a field of a SQL Server database (VarBinary).

The Java code that is responsible for storing it is the following:

FileInputStream   fis = new FileInputStream(doc);
stmt.setBinaryStream(7, fis, (int) image.length());
System.out.println((int) image.length());
stmt.execute();

What would be the equivalent in PHP? I'm using the file_get_contents () function but it has nothing to do with what I get in Java with this.

To view it from PHP I do the following:

$content = sqlsrv_get_field( $result, 1,SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
file_put_contents($path, $content); 
    
asked by Daniel Valencia Hernandez 21.11.2018 в 14:11
source

1 answer

0

What you are doing is correct, file_get_contents () is the equivalent of the code java you have In java you have to indicate which byte to which byte to read the file, in PHP it is not necessary. file_get_contents () returns all the binary of the file to a variable as if it were a text string. Now what you have to do to save it is an insert as if you were saving a text string. The difference is that that variable you have to escape with real_escape_string of the mysqli object or use statements prepared if you use PDO . Example of mysqli:

$pdf=file_get_contents($path);
$pdfStr = $mysqli->real_escape_string($pdf);

if ($mysqli->query("INSERT into pdf (Name) VALUES ('$pdfStr')")) {
   printf("%d fila insertada.\n", $mysqli->affected_rows);
}

You can also review how to insert and recover binary data using PDO and PHP . If you want to read byte byte the file you have to use fopen and fread

Update: Sorry I had not noticed that it is for sql server and I put code for mysql. But if you use sqlsrv here are examples . Although towards sql server there is only the option of prepared statements.

    
answered by 21.11.2018 / 19:06
source