Giving images random name in PHP - 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

Related

PHPExcel not download or no process at all

i'm trying to export from mysql to excel using PHPExcel, i create a button to start exporting proses. It's loading but return with blank white page, i check every line from the code and didn't found any problem. Calling data from table is normal, check it with echo. so i think there is a problem with exporting process, here is the code
require_once 'PHPExcel/PHPExcel.php';
$excel=new PHPExcel();
$excel->getProperties()->setCreator('Flora Sitinjak')
->setLastModified('Flora Sitinjak')
->setTittle('Laporan Pendapatan')
->setSubject('Pendapatan')
->setDescription('Laporan Semua Pendapatan')
->setKeywords('Data Pendapatan');
$exp=$excel->setActiveSheetIndex(0);
$exp->setCellValue('A1', "Tanggal");
$exp->setCellValue('B1', "EKS");
$exp->setCellValue('C1', "BIS");
$exp->setCellValue('D1', "EKO");
$exp->setCellValue('E1', "L.EKO");
$exp->setCellValue('F1', "Total");
$line=2;
$x=0;
for($i=1;$i<=$tgl[11];$i++){
$exp->setCellValue("A".$line, $i);
$carTL=count($arTL);
$gTGLO=substr($arTL[$x],-2);
if(empty($gTGLO)){
$x=0;
}else{
if($i==$gTGLO){
if(($x+1)>=$carTL){
$x=$carTL-1;
$exp->setCellValue("B".$line, $arLUEKS[$x]);
$exp->setCellValue("C".$line, $arLUBIS[$x]);
$exp->setCellValue("D".$line, $arUEKO[$x]);
$exp->setCellValue("E".$line, $arLEKO[$x]);
$exp->setCellValue("F".$line, $arTot[$x]);
}else{
$exp->setCellValue("B".$line, $arLUEKS[$x]);
$exp->setCellValue("C".$line, $arLUBIS[$x]);
$exp->setCellValue("D".$line, $arUEKO[$x]);
$exp->setCellValue("E".$line, $arLEKO[$x]);
$exp->setCellValue("F".$line, $arTot[$x]);
$x++;
}
}else{
$exp->setCellValue("B".$line, '-');
$exp->setCellValue("C".$line, '-');
$exp->setCellValue("D".$line, '-');
$exp->setCellValue("E".$line, '-');
$exp->setCellValue("F".$line, '-');
}
}
$line++;
}
$excel->getActiveSheet()->setTitle('Laporan');
$excel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="Data Laporan Pendapatan.xlsx');
header('Cache-Control: max-age=0');
$write=PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$write->save('php://output');
Every array like $arLUEKS[$x] is called from database and works, checked with echo
The output is a table with shows data a month from 1 to 31, if the data doesn't exist then it show a -
Anyone can solve this? please help me
I do not know what exactly could be wrong but here are some helpful things you can do that can help you identify your problem .
Turn on error reporting by adding these two to the top of your script
ini_set("display_errors",1);
error_reporting(E_ALL);
This may point you to the cause. Maybe the script is timing out or something

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.

mysqli export to xls issue

I have troble geting this work and I can't figure it out what is the issue.
I download a xls file, but it doesent opens.
I had a mysql script like this, working, and I tried to convert it into mysqli and probably something is wrong...
Thanks in advance
$sqlExp = "SELECT * FROM table";
$countQryExp = mysqli_query($link, $sqlExp );
$filename = "sampledata.xls"; // File Name
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while($row=mysqli_fetch_array($countQryExp,MYSQLI_ASSOC))
{
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
There's a lot more to generating an Excel file than giving it a content type of application/vnd.ms-excel. Excel is a very particular format, whereas you're generating a TSV file - tab separated values, and in a pretty breakable manner (what happens if someone puts a \t in one of your site's fields, or a new line?).
If you want to generate real Excel files, you'll want one of the various libraries for doing so. If a CSV/TSV are fine, just export a .csv/.tsv file with proper headers.

character convertion with CSV file

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.

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