0

I have this code that uploads a PDF into a SQL Server database

$attach_Name = $_FILES['aFile']['name'];
$attach_Name = str_replace("'","",$attach_Name);
$attach_Name = str_replace("\"","",$attach_Name);
$attach_Data = file_get_contents($_FILES['aFile']['tmp_name']);
$attach_Data = base64_encode($attach_Data);

And the SQL is:

INSERT INTO [dB].[dbo].[Doc_Data] ([DocInfoId],[DocData]) VALUES ('1',CAST('".$attach_Data."' AS 
VARBINARY(MAX)))

Then to retrieve and display it I use the following:

 $dbh = new PDO ('sqlsrv:server='.$dbServer.';database='.$dbName.'',''.$dbUN.'',''.$dbPass.'');
 $result = $dbh->prepare("SELECT [Doc_Data].[DocData]
                    FROM [dB].[dbo].[Doc_Data] 
                    WHERE [Doc_Info].[KeyID] ='1' 
 ");
 $result->execute();
 $row = $result->fetch(PDO::FETCH_ASSOC);

 $attach_Data = base64_decode($row['DocData']);
 $myfile = $row['DocName'];
 $myfile = str_replace(" ", "_", $myfile);
 $handle = fopen($myfile, "w+") ;//or die("Unable to open file!");
 $disp = fwrite($handle, $attach_Data);
 $type = filetype($myfile);
 $mode = "inline";
 header('Content-type: application/pdf');  
 header('Content-Disposition: inline; filename="' . $myfile . '"'); 
 header('Content-Transfer-Encoding: binary');
 header('Accept-Ranges: bytes');

// Read the file
@readfile($myfile);

fclose($handle);
unlink($myfile);
exit;

$dbh = null;

This works perfectly on Apache (XAMPP) but the client has moved to IIS and now my code fails to render the PDF anymore.

Any suggestions?

Dale K
  • 25,246
  • 15
  • 42
  • 71
  • Its not going to be relevant to SQL Server since you are already able to handle that side of things. Inspect the response in client side developer tools and see what is different/wrong. – Dale K Feb 01 '22 at 19:15
  • I strongly suspect that it could be the manner in which Apache and IIS handle the base64_decode, but I can't seem to find anything of value on the web about it, so was hoping someone else has had a similar issue – Garreth Holmes Feb 01 '22 at 20:32
  • It should be obvious from inspecting the response that arrives at the browser. – Dale K Feb 01 '22 at 20:34
  • When I use fopen($myfile, "w+") or die(error_get_last()); to try get an error message all it displays is the word "Array" – Garreth Holmes Feb 01 '22 at 20:47
  • I Changed "fopen($myfile, "w+") or die(error_get_last());" to "fopen($myfile, "w+") or die(print_r(error_get_last()));" AND it actually gave me some useable info in the error message. failed to open stream: Permission denied [file] => C:\inetpu... Searched that and found this: https://stackoverflow.com/questions/9210823/php-iis-failed-to-open-stream-permission-denied I will give feedback once I have applied the fix to see if it works. – Garreth Holmes Feb 02 '22 at 06:33

0 Answers0