Storing pdf to varbinary(max) field with php and MS SQL - php

I'm working with MS SQL 2005 and PHP, and I got this code
move_uploaded_file($_FILES["file"]["tmp_name"],"temp/" . $_FILES["file"]["name"]);
$data = fopen("temp/"$_FILES["file"]["name"], "rb");
$content =fread($data,$_FILES['file']['size']);
$content=addslashes($content);
$sql = "INSERT INTO docs(file) value($content)";
if(!mssql_query($sql)){
die('MSSQL error: ' . mssql_get_last_message());
}
and I got this error: MSSQL error: Incorrect syntax near 'PDF'
PD: excuse my poor english
I found the solution: the code would look like:
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
-
move_uploaded_file($_FILES["file"]["tmp_name"],"temp/" . $_FILES["file"]["name"]);
$data = fopen("temp/"$_FILES["file"]["name"], "rb");
$content =fread($data,$_FILES['file']['size']);
$content=mssql_escape($content);//Call mssql_escape function
$sql = "INSERT INTO docs(file) value($content)";
if(!mssql_query($sql)){
die('MSSQL error: ' . mssql_get_last_message());
}

Use parameters. See the documentation - specifically the first example for mssql_bind - for instructions on how to do that.
You're trying to insert the contents of the PDF file as a string, and you have no quotes around that string. But even if you wrap $contents in quotes, it probably still will not work. There may be binary in the file contents that simply cannot be inserted in this way.
Also, it may be easier to just save the PDF file somewhere in your filesystem and save the path to the file in your database. That way you won't have huge (megabytes!) records in your database and the files will probably be quicker to access.

I found the solution: the code would look like:
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
-
move_uploaded_file($_FILES["file"]["tmp_name"],"temp/" . $_FILES["file"]["name"]);
$data = fopen("temp/"$_FILES["file"]["name"], "rb");
$content =fread($data,$_FILES['file']['size']);
$content=mssql_escape($content);//Call mssql_escape function
$sql = "INSERT INTO docs(file) value($content)";
if(!mssql_query($sql)){
die('MSSQL error: ' . mssql_get_last_message());
}

Related

PHP - copy() fails on URL with curly braces/brackets

I'm having an issue with the copy() function in PHP.
I need to copy a remote URL that looks like: https://example.co.uk/{8d988e90-a325-4a1c-a340-a489166286b8}/{14409287-2c29-4b51-91e4-0891b5619659}/main/imgnew-(2).jpg, to my local drive.
Here is the part of my code that fails, along with some context for the $RemoteURL variable:
$replace = array('%7B', '%7D','%28','%29');
$entities = array('{', '}','(',')');
$RemoteURL = str_replace($entities, $replace, "https://example.co.uk/{8d988e90-a325-4a1c-a340-a489166286b8}/{14409287-2c29-4b51-91e4-0891b5619659}/main/imgnew-(2).jpg");
$PicName = "new.jpg"
if(copy($RemoteURL,"C:\Users\Me\Downloads\Pictures\" . $PicName)){
echo "<script>console.log(\"(" . $RemoteURL . ") copied to waiting.\")</script>";
} else {
echo "<p class='float red'>READ ERROR</p>";
}
However, this throws the error:
Warning: copy(https://example.co.uk/%7B8d988e90-a325-4a1c-a340-a489166286b8%7B/%7B14409287-2c29-4b51-91e4-0891b5619659%7B/main/imgnew-%282%29.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
What is it exactly I'm missing here, or what is it that PHP doesn't like about the URL itself?
Turns out the issue that was producing the error above was that I had an accented character that was problematic.
è was giving an error, which was fixed by creating a function that replaced certain parts:
function URLEncodeRules($string) {
$replacements = array('%C3%A9','%C3%A8');
$entities = array('é','è');
return str_replace($entities, $replacements, $string);
}
$RemoteURL = URLEncodeRules($CaptureRow['URL']);
if(copy($RemoteURL,"image.jpg")){
echo "Success!;
}
Try using url_encode();
Hope this will help you.
Thanks,

Text file contents will echo but not return php

I've been working o this for the last few weeks and can't find an alternate route. What I need to do is return the contents of a text file after the file has been read. I have two different logs that use text files to log errors. The first log returns the correct variable that I ask for but for some reason, even though I use the exact same methods to call the variable, it doesn't return anything. If I echo the variable then the correct string is displayed but the variable returns nothing. Here is the function:
function GetNoticeLog($strDate){
$logdate = preg_replace("/[^0-9]/", "_", $strDate );
$strFileName = realpath('debuglogs/enotice_logs').'/ENOTICELOG_' . $logdate . '.txt';
if(is_readable($strFileName)){
$file = fopen($strFileName,"r");
$contents = fread($file, filesize($strFileName));
$fclose($file);
return nl2br($contents);
}
else if(!is_readable($strFileName)){
echo $strFileName." is unreadable";
}
}
Why does this function return the necessary string when executed in one function but has to be echoed to see content in the other is my question.
Try changing
$fclose($file);
to this
fclose($file);
I was able to get the code to work on my server. The only change I made here is the path to the file which is in the same directory as the PHP script.
<?php
function GetNoticeLog($strDate){
$logdate = preg_replace("/[^0-9]/", "_", $strDate );
//$strFileName = realpath('debuglogs/enotice_logs').'/ENOTICELOG_' . $logdate . '.txt';
$strFileName = "blah.txt";
if(is_readable($strFileName)){
$file = fopen($strFileName,"r");
$contents = fread($file, filesize($strFileName));
fclose($file);
return nl2br($contents);
}
else if(!is_readable($strFileName)){
echo $strFileName." is unreadable";
}
}
$stuff = GetNoticeLog("whatever");
echo $stuff;
?>

Set File Extension in CakeResponse

I'm trying to generate a CSV file on the fly, depending on what the user selects as report output. Retrieving the data and writing it to a file using CakeResponse is done, however I'm struggling to set the file extension to '.csv', the file get downloaded as a normal text file.
CakePHP documentation suggests I do this:
$this->response->type('csv');
..but even this is not working, I'm still getting a text file. Can anyone shed some light? Please note, I'm not looking for new methods to generate a CSV file, I just want to change the extension. Thank you.
This is how I download the file:
$this->response->body($this->constructFileBody($logs));
return $this->response;
This is the method 'constructFileBody', although I think its beyond the scope of this question:
public function constructFileBody($logs = array()){
$content = "";
for($i = 0; $i < count($logs); $i++){
$row = $logs[$i]['EventLog'];
$line = $row['description'] . "," . $row['user'] . "," . $row['affected_user'] . "," . $row['report_title'] . "," . $row['date_created'] . "\n";
$content = $content . $line;
}
return $content;
}
As i saw your code, I don't think you used the header anywhere, try this code:
//create a file
$filename = "export_".date("Y.m.d").".csv";
$csv_file = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$results = $this->ModelName->query($sql); // This is your sql query to pull that data you need exported
//or
$results = $this->ModelName->find('all', array());
// The column headings of your .csv file
$header_row = array("ID", "Received", "Status", "Content", "Name", "Email", "Source", "Created");//columns you want in csv file
fputcsv($csv_file,$header_row,',','"');
// Each iteration of this while loop will be a row in your .csv file where each field corresponds to the heading of the column
foreach($results as $result)
{
// Array indexes correspond to the field names in your db table(s)
$row = array(
$result['ModelName']['id'],
$result['ModelName']['received'],
$result['ModelName']['status'],
$result['ModelName']['content'],
$result['ModelName']['name'],
$result['ModelName']['email'],
$result['ModelName']['source'],
$result['ModelName']['created']
);
fputcsv($csv_file,$row,',','"');
}
fclose($csv_file);
Now look at your code and get the line of code mine which needs to be replaced.

postgresql query result to csv prints current page's html code also

I am trying to output the results of a PostgreSQL query to CSV format using PHP.
On the main page is a link that sends the SQL statements as a string to another function in another PHP class, which in turn takes the SQL and executes the query using pg_query() and return the result sets.
My problem is that when I open the CSV file, all the results of my query are there, but at the end of the file I see the HTML code from the page that sent the query.
I looked at several StackOverflow posts, but to no avail.
Here is my code:
Main class:
$o .= '<p>You can convert the result set to CSV format to be opened in Excel.</p>';
$link = array('op1' => 'PatternExport', 'op2' => 'outputToCSV', 'id' => $pattern_id, 'data' => $pattern_SQL);
$o .= 'Download Query Results as CSV File';
Receiving class:
function outputToCSV()
{
$ptid = $this->oQS->getValue('id');
$sql = $this->oQS->getValue('data');
$href = $this->oQS->buildEncryptedURL(array('op1'=>'PatternManager', 'op2'=>'listPatterns'),'/aatsc/index.php');
$result = pg_query($sql);
// filename for download
$filename = "query_results_" . date('Ymd') . "_" . $ptid . ".csv";
$output = fopen('php://temp/maxmemory:' . (12*1024*1024), 'rw+');
foreach(pg_fetch_assoc($result,0) AS $field=>$value)
{
$output .= '' . $field . ',';
}
$output = rtrim($output,',') . "\n";
for($i=0;$i<pg_num_rows($result);$i++)
{
foreach(pg_fetch_assoc($result,$i) AS $field=>$value)
$output .= '' . $value . ',';
$output = rtrim($output,',') . "\n";
}
header("Content-Type: application/vnd.ms-excel;");
header("Content-Disposition: attachment; filename=\"$filename\";");
header("Pragma: no-cache");
print($output);
//$href = $this->oQS->buildEncryptedURL(array('op1'=>'PatternManager', 'op2'=>'listPatterns'),'/aatsc/index.php');
//header("Location: $href");
}
Could you tell me whether I am using the right approach to export query results to CSV, and what in my code is causing the whole HTML code to be streamed?
Thanks
You're generating $output twice, if you remove the foreach loop & fopen line, it should work.
You merely just need to issue the SQL COPY statement as follows:
COPY (select * from tbl) to stdout with csv header
resulting in:
col1,col2,col3
2013-05-22 07:28:59.732,192.168.1.67,3

PHP fwrite writing empty file

I'm trying to make this save a file and it creates the file, but it's always empty. This is the code for it:
<?php
$code = htmlentities($_POST['code']);
$i = 0;
$path = 'files/';
$file_name = '';
while(true) {
if (file_exists($path . strval($i) . '.txt')) {
$i++;
} else {
$name = strval($i);
$file_name = $path . $name . '.txt';
break;
}
}
fopen($file_name, 'w');
fwrite($file_name, $code);
fclose($file_name);
header("location: index.php?file=$i");
?>
I echoed out $code to make sure it wasn't empty, and it wasn't. I also tried replacing
fwrite($file_name, $code);
with this:
fwrite($file_name, 'Test');
and it was still empty. I have written to files a couple of times before in PHP, but I'm still really new to PHP and I have no idea whats wrong. Could someone tell me what I'm doing wrong or how to fix this? Thanks
Reading/Writing to/from a file or stream requires a resource handle:
$resource = fopen($file_name, 'w');
fwrite($resource, $code);
fclose($resource);
The resource handle $resource is essentially a pointer to the open file/stream resource. You interact with the created resource handle, not the string representation of the file name.
This concept also exists with cURL as well. This is a common practice in PHP, especially since PHP didn't have support for OOP when these methods came to be.
Take a look of the samples on php.net

Categories