I have several php files which contain different queries to a postgresql database. There about sixteen of these files. Each of these files returns a different set of data based on the query within the file. After a query is made, you can download the file and the download is into an excel file.
My question is how can i trigger a download in php such that i can have just one link and upon clicking it, all these sixteen files are downloaded at once. I dont want to download each file on its on. Or better still i could have checkboxes and i select the files i would like to download. I hope my question is clear enough.
For example i have this file named export_a.php with this code
<?php require_once('connections/pgconn.php');
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "eastafrica_revenue_daily" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = pg_query("SELECT to_char (a.CALLDATE,'yyyymmdd') as transdate,
sum(a.alltaxcost::integer) AS revenue,
COUNT (DISTINCT a.IDENTIFIANT) AS distinct_callers,
a.zoneiddest as country_code,b.country
FROM cdr_data a, COUNTRY_CODES b
WHERE a.CALLSUBCLASS = '002'
AND a.CALLCLASS = '008'
and a.zoneiddest::integer > 0
AND SUBSTR (a.CALLEDNUMBER, 1, 2) NOT IN
('77', '78', '75', '70', '71', '41', '31', '39', '76','79')
and substr(a.zoneiddest,1,3) in ('254','255','211','257','250')
and trim(a.zoneiddest) = trim(b.country_code)
GROUP BY to_char (a.CALLDATE,'yyyymmdd') ,a.zoneiddest,b.country
ORDER BY 1") or die('Query failed!');
while(false !== ($row = pg_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>
Then i have another file say export_b.php with another query. When a link is clicked on a certain page say a.php where this query is made, it exports to excel.
My question is how can i trigger a download in php such that i can have just one link and upon clicking it, all these sixteen files are downloaded at once. I dont want to download each file on its on. Or better still i could have checkboxes and i select the files i would like to download.
If you want to download Excel files, why not download a single Excel file containing 16 worksheets (one for each of your datasets);
Alternatively zip all the files together, and download the zip
Related
I have a folder of images that I am trying to change to be the date and time the picture was taken. I managed to make it work for the most part, however if the image has the same DateTimeOriginal (to the second), the subsequent images are deleted and replaced with the last one. This is a problem when I use burst on my camera.
I am trying to have the code add "_1" after each file name, unless the file name exists, then I want the "_1" to increase by 1. So far, the code I have will catch the first duplicate name and work properly, but every other matching filename after just deletes the file before it that has the same name (which was just renamed by the code).
In case it makes a difference, I am using XAMPP to run the PHP code in a local directory on my windows 10 PC, but I do test it online as well and have the same outcome.
The following is the code I have come up with by piecing together other code that I have found, and then attempting to customize it. I have a general understanding of PHP through trial and error, but have no education. I feel like I should be using a "while" statement while(file_exists('pictures/'.$timestamp.'_'.$count.'.jpg')) instead of or in conjunction with the current if statement I have if (file_exists('pictures/'.$timestamp.'_'.$count.'.jpg'))
The entire code I am using is here:
<?php
$count=1;
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
date_default_timezone_set('America/Edmonton');
$dirloc = "pictures/$file";
$newdirloc = "NewPictures/$file";
$exif_data = exif_read_data ($dirloc, $file, 0, true);
$exifString = $exif_data['DateTimeOriginal'];
$exifPieces = explode(":", $exifString);
$newExifString = $exifPieces[0] . "-" . $exifPieces[1] . "-" . $exifPieces[2] . ":" . $exifPieces[3] . ":" . $exifPieces[4];
$exifTimestamp = strtotime($newExifString);
$timestamp = date("y-m-d_H-i-s", $exifTimestamp);
if (file_exists('pictures/'.$timestamp.'_'.$count.'.jpg')) {
$ExistingFile = 'pictures/'.$timestamp.'_'.$count.'.jpg';
$delimiters = ['-', '_', '.'];
$newStr = str_replace($delimiters, $delimiters[0], $ExistingFile);
$NamePieces = explode("-", $newStr);
$count = $NamePieces[6];
++$count;
echo ($file.' has now been changed to '.$timestamp.'_'.$count.'.jpg (Increased count from existing file)<br>');
rename('pictures/'.$file, 'pictures/'.$timestamp.'_'.$count.'.jpg');
}
else {
echo ($file.' has now been changed to '.$timestamp.'_1.jpg (Unique File)<br>');
rename('pictures/'.$file, 'pictures/'.$timestamp.'_1.jpg');
}
}
}
?>
Thanks for helping this newbie figure this out!
Edit:
I think I've narrowed it down to a simpler question.
If it is possible to see if $ANY_NUMBER is in fact any number, what would I say $ANY_NUMBER is = to? With this change, I should be able to get rid of the count=1 at the start, and if it is true that it is any number in that [6] spot, than I should be able to say that count= that [6] spot. Does that make sense?
if (file_exists('pictures/'.$timestamp.'_'.$ANY_NUMBER.'.jpg')) {
$ExistingFile = 'pictures/'.$timestamp.'_'.$ANY_NUMBER.'.jpg';
$delimiters = ['-', '_', '.'];
$newStr = str_replace($delimiters, $delimiters[0], $ExistingFile);
$NamePieces = explode("-", $newStr);
$count = $NamePieces[6];
++$count;
echo ($count);
}
Iam creating a simple PHP application, where is a csv file upload then an .stm(its a simple text file) file download. The records must be write at given byte position. For example: 1st record position 1, length 2, 2nd record, etc.Records
So Im trying to use fwrite, fseek to get to given position, for example I dont need 2 record to be filled, so I jump to position 11 but there are NUL characters in the file.
Code:
$input = $sFileName;
//a nevbol kiszedni a datumot, majd EEEEHHNN verziora konvertalni
$get_date_from_name = str_replace(".","",substr($sFileName,0,10));
$output = $get_date_from_name . '_mpl_tensoft_import.stm';
$_SESSION['file_name'] = $output;
if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w+b');
//Create first line of the file 11 record type
fwrite($oh,"11");
fseek($oh, 11);
fwrite($oh,"120967120159857100100007");
/*while (false !== ($data = fgetcsv($ih,0,";"))) {
// this is where you build your new row
//Interne cislo, Dodavatel, Dodavacie c.faktury Celk.suma, Dátum prijatia, Dátum splat. = Datum uhrady, Predmet
$outputData = array($data[0], $data[1], $data[2], $data[3], $data[12], $data[13], $data[36] );
fputcsv($oh, $outputData);
}*/
fclose($ih);
fclose($oh);
unlink($input);
}
Result is:
11NULNULNULNULNULNULNULNULNUL120967120159857100100007
Visual Studio Code gives an error that the file is binary or to large or uses an unsupported encoding.
Notepad++ adds the NUL characters.
Should I just use a whitespace character? 1 whitespace character equals 1 byte? The file should be in CP852 encoding
Thanks for the help and pointing in to the right direction.
Your seek() offset seems to be "out of range".
Documentation said :
In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0.
EDIT :
If you want to put the second number at offset 13, using spaces, you could do something like this :
$ban_pos = 13 ;
$num = "11" ;
$pos = $ban_pos - strlen($num) ;
$ban = "120967120159857100100007" ;
$oh = fopen($output, 'w+');
fwrite($oh, $num);
fwrite($oh, str_repeat(' ', $pos));
fwrite($oh, $ban);
fclose($oh);
The file will contains :
11 120967120159857100100007
How can i perform auto cut on Epson TMT82 from PHP File? bellow is my config file.
Config:
$tmpdir = sys_get_temp_dir();
$file = tempnam($tmpdir, 'ctk');
$handle = fopen($file, 'w');
$condensed = Chr(27) . Chr(33) . Chr(4);
$bold1 = Chr(27) . Chr(69);
$bold0 = Chr(27) . Chr(70);
$initialized = chr(27) . chr(64);
$condensed1 = chr(15);
$condensed0 = chr(18);
$Data = $initialized;
$Data .= $condensed1;
Printing:
fwrite($handle, $Data);
fclose($handle);
copy($file, "//localhost/printer"); # printing
unlink($file)
Try to write chr(29) + 'V' (or chr(86)), and then the values for m and n, depending on the exact function you want to use as per the manual below (if you just want to cut without feeding at all, you want to use function A, which means you can just follow with a 0 (or 48, not sure why they mentioned both numbers in the manual...!?), like so:
chr(29) . "V" . 0
https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=87
(you need to be logged on to read this reference, but registering is free)
Edited: the chr() code for 'V' is 86, not 56
Edit2: Just to comment on what Matt Gibson said; chr(27) . chr(105) should also work on your model (just checked, also chr(27) . chr(109)), but it's an obsolete command, you should be using chr(29) . "V". In any case, some printers like to receive these sorts of commands on their own instead of having them along with the rest of the string.
Once you get this right, you should probably define a variable with the type of cut that you want. Ex. $cutPaper = chr(29) . "V" . 0;
This file stores the number of item ordered to date. Therefore, I will need to read from the file for current number ordered and add it to the current quantity ordered and write it back.
I am new to PHP, so I am not sure what is the best approach here.
The format of the file is as follows:
$filename = "ordersToDate.txt";
if (!file_exists($filename))
{
$file = fopen($filename, "w");
$toWrite = "Total quantity ordered to date
\r\nTotal number of apples: ".$appleQty.
"\r\nTotal number of oranges: ".$orangeQty.
"\r\nTotal number of bananas: ".$bananaQty;
fwrite($file, $toWrite);
fclose($file);
}
else
{
// read individual item QTY ordered to date, add it with current ordered QTY and write back
}
If the file already exists, I need to read the QTY from it and update it. Is there a quick and easy way to get it (i.e., current QTY to date), provided that I know the string before it?
When you open a file like that you can specify "or die" like this:
$filename = fopen("ordersToDate.txt", "w") or die ("Can't open file.");
Then you can write to the file like you're doing and then close it. If the file exists already it will just open the existing one. If it doesn't exist PHP will create the file.
<?php
// can add another one for 'bananas: ' etc.
$re = "/(?!apples: )(\\d)/"; // for apples
// $str = file_get_contents($filename);
$str = "Total quantity ordered to date\r\nTotal number of apples: 3\r\nTotal number of oranges: 4\r\nTotal number of bananas: 3";
$subst = "5"; // $subst = $new_number;
// replace the number after 'apples: ' with whatever you want
$result = preg_replace($re, $subst, $str, 1);
echo var_dump($result);
// file contents, with apple number replaced with 5 (from 3) can now be written to file
?>
I have an upload functionality wherein I want to check whether there is a duplicate filename in the database. If there is, I would like to rename the jpg so that the photo to be uploaded will still be uploaded.
Here's the lines of codes that I came up with:
$shuffled = "qwertyuiopasdfghjkZxcvbnm";
$shuffled = str_shuffle($shuffled);
$shuffled = $shuffled.".jpg";
rename($this->filename,$shuffled);
I am using the shuffle function here to somehow give a random new filename,
I have tried using some other steps like preg_replace, but the jpg file itself gets corrupted. Any ideas?
Your code is:
$shuffled = "qwertyuiopasdfghjkZxcvbnm";
$shuffled = str_shuffle($shuffled);
$shuffled = $shuffle.".jpg";
rename($this->filename,$shuffled);
The third line looks like it should be $shuffled = $shuffled.".jpg";
use this:
copy($oldfilename,rand(10000000000,99999999999).".jpeg");
unlink($oldfilename);
the file name (without extension) will be a number greater than 10000000000 and smallet than 99999999999
Where is the extension in your new filename???
Exmple
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
If you are going to use a random filename, use microtime() to generate a random string.
A nicer solution would be:
if(is_file($filename))
{
$filenameSplit = explode('.', $filename);
$i = 1;
while(is_file($filenameSplit[0] . "($i)." . $filenameSplit[1]))
{
$i++;
}
$newFilename = $filenameSplit[0] . "($i)." . $filenameSplit[1];
rename($filename, $newFilename);
}