character convertion with CSV file - php

I have faced a problem whenever exporting a CSV file with PHP. I have a MYSQL query like
SELECT `interest_id`,`interest_name`,`interested_user_id` FROM `interest_list` WHERE `interest_name` LIKE '%fashion%'
But whenever I am trying to export one PHP file by making use of the above MySQL Query then my query is turning to
SELECT `interest_id`,`interest_name`,`interested_user_id` FROM `interest_list` WHERE `interest_name` LIKE 'úshion%'
SO that it returns no record.
Please tell me how can I solve the issue.
In the export file, I have written the code like:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
//executed code
fputcsv($output, $blankArray);
Now please help me.
Actually, I make the query in one file like:
$search_sql = "SELECT `interest_id`,`interest_name`,`interested_user_id` FROM `interest_list`";
if(isset($_REQUEST['search_user_btn'])){
if($_REQUEST['search_intr'] != '')
$search_sql .= " WHERE `interest_name` LIKE '%".$_REQUEST['search_intr']."%' ";
}
Then in the same file I write like:
<button>Export to CSV</button>
Finally In the export.php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
I am trying to get the value of $_REQUEST['qur']. But unable to get the original value of $_REQUEST['qur'].
I think Now it is making sense.
Please help....

You can't insert random strings in a URL because there're some characters that have a special meaning in URLs. In PHP, you can encode the value of a URL parameter with rawurlencode(). Similarly, you can't insert random characters in a HTML string for the same reason.
<?php
$url = 'export.php?report=interest&qur=' = rawurlencode($search_sql);
?>
<button>Export to CSV</button>
Whatever, passing SQL in the URL is call to get hacked.

Related

PHP 7: Query output to Text File Questions (FIeld Headers and Skipping a Comma after last column)

I've very new to PHP and trying to re-create some code I had in another language. The current version of PHP I'm working with is 7.17.
Right now, I'm trying to re-create a simple function of opening a MySQL query as a comma deliminated text file where there is no comma after the last column (just a line break). I'm trying to figure out two things right now to finish this piece of code.
How do I insert the query column headers at the top of the data output (right now only the data is output, not the column headers).
At the line "fwrite($output, $value.',');", I'm trying to figure out how to not add the comma after the last field (how to skip adding the comma after the last column of data).
PHP:
if (isset($_POST['download'])) {
header('Content-Type: text/plain');
header('Content-Disposition: attachment;filename=cars.txt');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$output = fopen('php://output', 'w');
while ($row = getRow($result)) {
foreach ($row as $key => $value) {
fwrite($output, $value.',');
}
fwrite($output, "\r\n");
}
fclose($output);
exit;
}
Thank You!
It sounds like you are trying to create a CSV file, so why not use PHP's built in CSV handling functionality (fputcsv), like so:
$output = fopen('php://output', 'w');
while ($row = getRow($result)) {
fputcsv($output, $row);
}
fclose($output);
This way PHP does all the heavy lifting for you.
Edited based upon comment.
You could try using the answer from here to handle the encoding of the values before converting to CSV and then set the file encoding in the HTTP header to header('Content-Type: text/plain; charset=utf-8');.
Also fputcsv allows you to change the delimiter, enclosure and escape characters if they were causing you issues.
Otherwise just do:
$output = fopen('php://output', 'w');
while ($row = getRow($result)) {
$line = implode(', ', $row);
fwrite($output, $line);
}
fclose($output);

How to deal with unicode while exporting data in csv format using fputcsv in php?

I have following code to export data in csv format. It works fine in normal text, but didnot work if unicode exists means exported text are illegible even with the option of charset=utf-8, what should i do right here
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;
filename=magazine_subscribers'.date('Y-m-d').'.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Customer Id', 'Name', 'Company','Subscription Type','Address 1','Postal Code','City','Email','mobile','note','Invoice Receiver','Invoice Email','Invoice address','Invoice city','Invoice Postal Code'));
foreach($subscribers as $subscriber)
{
fputcsv($output,array($subscriber->customer_id,$subscriber->name,$subscriber->company,$subscriber->subscription_type,$subscriber->address_1,$subscriber->postal_code,$subscriber->city,$subscriber->email,$subscriber->mobile,$subscriber->note,$subscriber->invoice_receiver,$subscriber->invoice_email,$subscriber->invoice_address,$subscriber->invoice_city,$subscriber->invoice_zip));
}
thanks in advance

PHP I/O memory stream create empty line at the beginning of document

I'm new in php and I have question on you.
For now, I'm creating one php script where I want use this:
$file = fopen('php://memory','w');
Then, I use fputcsv where I add few arrays to fill into this document.
In the final part, I said that I want make downloadeble link
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="service.csv"');
My method look like this:
public function exportToCsv($Id){
$file = fopen('php://memory','w');
$someDetails = $this->some_model->getSomeDetail($Id);
$details = array(
array("Subject", "Start Date", "Start Time", "End Date", "End Time", "Where"),
array("test subject","test date","test time","test end date","etc..."));
foreach ($details as $detail) {
fputcsv($file, $detail);
}
fseek($file,0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="file.csv"');
fpassthru($file);}
When my browser download this file and when I open it, everything is great, but at the beginning of file, there is one empty line and I dont understand why it happend and how can I remove this line.
Thanks for describe.
Marek
1 ) You should check if there is any blank line / space before the PHP Tags ( <?php ?> )
2) Try adding ob_end_clean(); just before your fpassthru($file); , this will clear the buffer and you'll be sure there's nothing left in it.

Giving images random name in PHP

this way i load image using php:
header("Content-type: image/jpeg");
$image=imagecreatefromjpeg("http://i.imgur.com/zWaQJNCb.jpg");
imagejpeg($image);
but problem is, if i want to save the image manually from my web browser to my desktop then all the images has same name like ix.jpeg [here file name is: ix.php] but i cant understand what is the way to configure the header so that images will have random name.. like 25xc.jpeg, 36s5a2f.jpeg... while saving it on desktop.. any idea?
this is will do the job!
$dt = date(time());
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="'. $dt .'.jpg"');
$image=imagecreatefromjpeg("http://i.imgur.com/knNxDFnb.jpg");
imagejpeg($image);
Use the filename value in your header call. See Example 1.
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
I'll leave the "generate a random string" part up to you. I'd suggest basing it on the checksum of the file, but that's just me.
This is what you need to do if you would like to generate unique names for your users, all you need to do is to use actual time stamp and use the filename parameter in the header, you can do like below (if you use random generation there will be a very few cases where you will get the same name twice) :
$dt = date(time());
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'. $dt .'.jpg"');
The above will generate unique images names like below :
1362504465.jpg
I hope this helps.
There are dozens if not hundred ways to do that.
Append time() after file name. This way all the file names will
have a (unique)number.
Use a hashing function, like md5().
Use this code-
function generateRandomName(len) {
$out = '';
for($i=0; $i<len; $i++) {
$out.=chr(rand(65,122));
}
return $out;
}
Simply append rand function after your file name (But then the file names won't be of equal length).
Google is your friend.
This would make an 8 characters long name of letters a-z, but you could do some magic and/or use http://www.asciitable.com/
function randChar() {
return char(rand(97, 122);
// Then you could either do a random number from 97 to 122 for a-z or just make an array of all the characters you would like in the filename.
}
$filename = '';
$amountOfChars = 8;
for($i = 0; $i < $amountOfChars; $i++; ) $filename .= randChar();
Hope this helps

Export CSV from Mysql

I'm having a bit of trouble exporting a csv file that is created from one of my mysql tables using php.
The code I'm using prints the correct data, but I can't see how to download this data in a csv file, providing a download link to the created file. I thought the browser was supposed to automatically provide the file for download, but it doesn't. (Could it be because the below code is called using ajax?)
Any help greatly appreciated - code below, S.
include('../cofig/config.php'); //db connection settings
$query = "SELECT * FROM isregistered";
$export = mysql_query($query) or die("Sql error : " . mysql_error());
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . "\t";
}
while ($row = mysql_fetch_row($export)) {
$line = '';
foreach ($row as $value) {
if ((!isset($value) ) || ( $value == "" )) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
$data = str_replace("\r", "", $data);
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
//header("Content-type: application/octet-stream"); //have tried all of these at sometime
//header("Content-type: text/x-csv");
header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
//header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo 'Download Exported Data'; //want my link to go in here...
print "$header\n$data";
In essence, you can't output the CSV file and the link to it in one go. (You need to introduce the concept of a page "mode" and activate the download mode via a ...pagename.php?mode=download or similar. You could then use PHP's switch statement to switch on $_GET['mode'] in your script.)
That said, the text/csv content type header you were using is correct, although you may also want to output the Content-Length and Content-Disposition headers. After you've output the file data, also be sure to stop any additional script processing via PHP's exit function.
Additionally, it would probably be a lot less hassle (and will certainly be faster/more memory efficient) to use MySQL SELECT ... INTO OUTFILE facility (if you have the permissions) rather than use PHP to gather the data.
You can't have text and a download on the same page. You need to have a link to the download area, which could just be a GET parameter leading to a function, which then does all the processing, displays headers, and echoes the content of the CSV.
For example, you could have Click here to download CSV, then in your code have if ($_GET['action'] === 'download'), get the data from the database, format it, send the headers, and echo the data. And then die(), because that part of the script can accomplish no more.
You should not put the link in the same file that generates the csv, as the link will not be in the csv itself!
Do something like:
Download CSV
and it should work
Three things to consider:
You're sending headers indicating that the user is going to be downloading a CSV file, but then you send create a link to download it? This isn't correct, you should be linking to this page, and then only outputting the CSV data itself after the headers.
MySQL has the ability to generate CSV output, and you should definitely take advantage of this instead of trying to do it yourself. You can use SELECT INTO ... OUTFILE to do this.
If you must create the CSV using PHP, please use fputcsv to do so. This will handle all the complications of CSV such as escaping and proper formatting. Since fputcsv writes to a file, you could either write it to a temporary file and then output it after you send your headers, or use the following trick to output it directly:
Do this after sending headers:
$fp = fopen('php://output', 'w');
while( $row = mysql_fetch_row( $export ) ) {
fputcsv($fp, $row);
}
I think the mySQL => CSV is common problem which is part of each PHP forum.
I have try to solve this issue in a common way and implement an free export
lib for PHP which is very similar to the Google AppInventor philosophie.
DragDrop and hide the coding stuff.
Use the lib and create your Export via Click&Point.
Common Demos: http://www.freegroup.de/software/phpBlocks/demo.html
Link to editor: http://www.freegroup.de/test/editor/editor.php?xml=demo_sql.xml
worth a look
Greetings
Andreas

Categories