Trying to fwrite the pdf results from PrinceXML to the server (in a new pdf file) instead of exporting via headers to acrobat. The below code displays the results on the browser.
require_once("../library/Prince/prince.php");
$princeSettings = $this->getInvokeArg('bootstrap') >getOption('prince');
$prince = new Prince($princeSettings['path']);
$prince->setHTML(true);
$result = $prince->convert_string_to_passthru($this->htmlView);
$fp = fopen("./files/reports/report.pdf", "w");
fwrite($fp, $result);
fclose($fp);
Figured this out for anyone who want to know...
require_once("../library/Prince/prince.php");
$princeSettings =$this->getInvokeArg('bootstrap')->getOption('prince');
$prince = new Prince($princeSettings['path']); $prince->setHTML(true);
$pdfPath =realpath(APPLICATION_PATH . "/../public/files/reports/report.pdf");
$prince->convert_string_to_file($this->htmlView, $pdfPath);
Related
I have some PHP code that successfully exports a MySQL table to a CSV file.
I would like to add to that code, so instead of saving locally the CSL file is exported to/saved on an external FTP server.
My current code:
//open database connection
require ('../database-config.php');
//name the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
//SQL Query for Data
$sql = "SELECT * FROM data;";
//Prepare Query, Bind Parameters, Excute Query
$STH = $dbh->prepare($sql);
$STH->execute();
//Export to .CSV
$fp = fopen('php://output', 'w');
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);
I know I'll need to add some new variables;
$ftp_server="ftp.remotersite.com";
$ftp_path="/path/to/somefile";
$ftp_username="username";
$ftp_userpass="password";
But, I'm not sure the best way to use ftp_put (or should it be ftp_fput?) to transfer to the external destination.
Thanks in advance.
If you have ftp:// URL wrappers enabled, just open the file directly on FTP server:
$fp = fopen('ftp://username:password#ftp.example.com/path/to/somefile', 'w');
If you do not have the wrapers enabled, see:
Creating and uploading a file in PHP to an FTP server without saving locally
I need to generate a CSV file from a MySQL query and save the file to an SFTP server. I have tried the code below. The CSV file gets created, but it is empty. I also receive an error message in the browser that says Warning: is_file() expects parameter 1 to be a valid path, resource given in regard to this line $sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);. If I move fclose($fp); to the last line, I don't get the error but data still doesn't appear in the file. Could someone please let me know how to get the data to save in the file that was created?
$fileName = 'dataFiles/reports/Report Summary/Report Summary.csv';
$sql = mysqli_query($db, "
SELECT *
FROM reports
WHERE reportID = 1
");
$fp = fopen('php://output', 'w');
$first = true;
while($row = mysqli_fetch_assoc($sql)){
if ($first) {
fputcsv($fp, array_keys($row));
$first = false;
}
fputcsv($fp, $row);
}
fclose($fp);
$sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);
Try something like this:
<?php
$fp = fopen('php://temp', 'r+');
// do stuff
rewind($fp);
$sftp->put($filename, $fp);
phpseclib (assuming you're using a new enough version) will detect that the second parameter is a stream resource and will try to read from it accordingly.
The second argument is not a handle but the content directly.
I think you could do: stream_get_contents($fp); in the second argument.
$content = stream_get_contents($fp);
fclose($fp);
$sftp->put($fileName, $content, NET_SFTP_LOCAL_FILE);
I recently installed Apache, PHP and started working on a small project.
I have the following code.
<?php
$tim=time();
$ip=$_SERVER['REMOTE_ADDR'];
$ipadd=$tim."IPaddress".$ip;
$fp="user_log.txt";// file address
$myfilea = fopen($fp,"a");//open file
fwrite($myfilea,$ipadd.PHP_EOL);//add data to file
echo fread($myfilea,filesize($fp));//read file
fclose($myfilea);//close file
?>
Here is what I can do... I can either use "a" mode to add text or I can use "r" mode to read text. I cant do both. I tried using "a+","r+","ar" etc.
Did I miss something during my setup ???
I am running this on windows 8.1.
Thanks for your help.
You need to rewind the file pointer.
$tim = time();
$ip = $_SERVER['REMOTE_ADDR'];
$ipadd = $tim.'IPaddress'.$ip;
// file address
$fp = 'user_log.txt';
//open file
$myfilea = fopen($fp, 'a+');
//add data to file
fwrite($myfilea, $ipadd.PHP_EOL);
// your file pointer is at the end of the file now
// so rewind before you read
rewind($myfilea);
//read file
echo fread($myfilea, filesize($fp));
//close file
fclose($myfilea);
Try this code, use file_put_contents
file_put_contents = Write a string to a file
$fp="user_log.txt";
$tim=time();
$ip=$_SERVER['REMOTE_ADDR'];
$ipadd=$tim."IPaddress".$ip;
$myfile = file_put_contents($fp, $ipadd.PHP_EOL , FILE_APPEND | LOCK_EX);
And for your code try this, it will check able to open file or not
fopen("logs.txt", "a") or die("Unable to open file!");
how do i open/view for editing an uploaded file in php?
i have tried this but it doesn't open the file.
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
i've also tried this but it wont work.
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);
what i have in mind is like when you want to view an uploaded resume,documents or any other ms office files like .docx,.xls,.pptx and be able to edit them, save and close the said file.
edit: latest tried code...
<?php
// Connects to your Database
include "configdb.php";
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM employees") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
//Outputs the image and other data
//Echo "<img src=localhost/uploadfile/images".$info['photo'] ."> <br>";
Echo "<b>Name:</b> ".$info['name'] . "<br> ";
Echo "<b>Email:</b> ".$info['email'] . " <br>";
Echo "<b>Phone:</b> ".$info['phone'] . " <hr>";
//$file=fopen("uploadfile/images/".$info['photo'],"r+");
$file=fopen("Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt","r") or exit("unable to open file");;
}
?>
i am getting the error:
Warning: fopen(Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt): failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/uploadfile/view.php on line 17
unable to open file
the file is in that folder, i don't know it wont find it.
It might be either:
A permissions issue on the server. If it's a linux machine, try chmod 754 Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt (you may need root).
An issue with apache (or whatever webserver you might be using). Make sure you've defined a directory entry in the config file for that site. Documentation here.
Although, if I recall properly, an odt file will just be binary data rather than the text information. That might be what you're looking for, I don't know. If you just want to read the actual text, and you aren't interested in using some library to extract it, you need to save it as plain text. If you're actually trying to edit these files in the browser, you're gonna need a lot more than just fopen.
For text based files you can use file_get_contents and file_put_contents
However, ODT files are zip compressed XML files so you need to decompress them first:
$zip = new ZipArchive;
$res = $zip->open('Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt');
if ($res === TRUE) {
$zip->extractTo('/tmp/myOdt.xml');
$zip->close();
}
$data = file_get_contents('/tmp/myOdt.xml');
$data .= 'add this to the end';
file_put_contents('path/to/file.txt', $data);
However, it seems your problem regards the actual path of the file. Try using a relative path instead: "images/file.odt"
I have been trying for a few hours now to no avail. I have successfully output my CSV as a download in the browser using:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
However I want that output to now go to an FTP server instead, I have got the connection and temp file part sorted but cannot seem to edit the file to output my results.
// create empty variable to be filled with export data
$csv_export = '';
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).',';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'",';
}
$csv_export.= '
';
}
Above is the part that gets the query data and puts it into the CSV, I have tried incorporating both fputs and fputcsv in the loops to write the rows to the file.
//Upload the temporary file to server
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
$fp = fopen('var/www/vhosts/.../abandoned.csv', 'w');
fputs($fp, '$csv_export');
fclose($fp);
echo($csv_export);
So, echoing the output works absolutely fine - all I want is that echo'd data written into a CSV file and uploaded to the FTP.
The error I've been given is:
Array ( [type] => 2 [message] => fclose() expects parameter 1 to be resource,
boolean given
So the fp is causing the problem... is it at the open stage or at the writing of csv_export?
Thanks in advance.
Try this
//Write the contents to the temp file
fputs($temp, $csv_export);
//upload the temp file
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
//close the temp file
fclose($temp);
Your current code is creating an empty file, uploading it, and then creating a separate file. Even if you get it working on a local server, it is an unnecessary step.
Try this, not tested:
$filename = 'abandoned.csv';
$content = $csv_export;
$host = 'yourhost';
$user = 'youruser';
$password = 'yourpass';
//open connection to your ftp server
$stream = stream_context_create(array('ftp' => array('overwrite' => true)));
//authenticate to your ftp server, normal uri syntax
$uri = sprintf('ftp://%s:%s#%s/%s', $user, $password, $host, $filename);
file_put_contents($uri, $content, 0, $stream);
In phpinfo(); you can look for Registered PHP Streams and just use this in most of any cases:
file_put_contents('ftp://user:password#server/your/directory/file.csv', $csvData);
ftp_fput is a right way here.
But you have to prepare FTP connection and authenticate first. Assuming you have $csv_export string in memory:
// connect
$ftp_conn = ftp_connect('ftp.yourserver.net');
// authenticate
$login_result = ftp_login($conn_id, 'ftp_username', 'password');
// prepare output stream
$stream = fopen('data://text/plain,' . $csv_export, 'r');
// try to upload
if (ftp_fput($ftp_conn, '/httpdocs/.../abandoned.csv', $stream, FTP_ASCII)) {
echo "Successfully uploaded\n";
} else {
echo "There was a problem while uploading\n";
}
// close the connection and the file handler
ftp_close($ftp_conn);
fclose($stream);
You're receiving that error because fopen is returning false, which indicates that it was unable to open the file.
If I'm understanding your code, you're uploading abandoned.csv (which presumably exists) to the ftp after opening it in $temp. Is $temp pointing at your local copy of abandon.csv? Because if so, you should close the file stream pointing to it before opening a second one with fopen.
If that's not the issue, then abandoned.csv may not actually exist, in which case you may just be trying to fopen a missing file.