Is it possible to create file.txt on the fly download it?
The file should be stored in backup/process/_pro_links_date.txt
but when I download the file, it has no .txt extension and it was store on my folder.
HTML
File
PHP
if ( $_GET['down'] == 'load' ) {
$date = date( 'Y-m-d H:i:s' );
$myFile = "backup/process/_pro_links_$date.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Title - Url - Live Date - Process Date \r";
fwrite($fh, $stringData);
$sql = mysql_query("SELECT * FROM k_addlinks WHERE user_code = '".$_SESSION['user_code']."' ") or die (mysql_error());
while ($row = mysql_fetch_array($sql)){
$dated = date("m/j/y g:i",strtotime( $row["date"] ));
if($row["spider_date"] == 'never'){
$sdate = $row["spider_date"];
}else{
$sdate = date("m/j/y g:i",strtotime( $row["spider_date"] ));
}
$stringData = $row['pro_name'] . $row['customDomain'] . $dated . $sdate . '\r';
}
fwrite($fh, $stringData);
fclose($fh);
$path = "backup/process/_pro_links_$date.txt";
$name = "_pro_links_$date.txt";
header("Content-Type: text/plain");
header("Content-Length: " . filesize($path));
header('Content-Disposition: attachment; filename='.$name);
readfile($path);
}
what is wrong with my codes?
I see the issue. In your Content-Disposition header, you set the filename, but your filename contains spaces since you created it using date("Y-m-d H:i:s"). So you need to surround the filename with quotes in that header:
// $name contains a space, in the format _pro_links_Y-m-d H:i:s.txt
$name = "_pro_links_$date.txt";
// Surround the filename with quotes...
header('Content-Disposition: attachment; filename="'.$name . '"');
Alternatively, remove the spaces from $date before using it in the filename:
$date = str_replace($date, " ", "_");
$name = "_pro_links_$date.txt";
Instead of saving it to a file, just echo it after you send the headers.
$content = "Hello world !!!";
$name = "name.txt";
$file = fopen($name,"wb");
fwrite($file, $content);
fclose($file);
header('Content-Type: charset=utf-8');
header("Content-disposition: attachment; filename=$name");
print $content;
Related
I have this code that uploads a PDF into a SQL Server database
$attach_Name = $_FILES['aFile']['name'];
$attach_Name = str_replace("'","",$attach_Name);
$attach_Name = str_replace("\"","",$attach_Name);
$attach_Data = file_get_contents($_FILES['aFile']['tmp_name']);
$attach_Data = base64_encode($attach_Data);
And the SQL is:
INSERT INTO [dB].[dbo].[Doc_Data] ([DocInfoId],[DocData]) VALUES ('1',CAST('".$attach_Data."' AS
VARBINARY(MAX)))
Then to retrieve and display it I use the following:
$dbh = new PDO ('sqlsrv:server='.$dbServer.';database='.$dbName.'',''.$dbUN.'',''.$dbPass.'');
$result = $dbh->prepare("SELECT [Doc_Data].[DocData]
FROM [dB].[dbo].[Doc_Data]
WHERE [Doc_Info].[KeyID] ='1'
");
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
$attach_Data = base64_decode($row['DocData']);
$myfile = $row['DocName'];
$myfile = str_replace(" ", "_", $myfile);
$handle = fopen($myfile, "w+") ;//or die("Unable to open file!");
$disp = fwrite($handle, $attach_Data);
$type = filetype($myfile);
$mode = "inline";
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $myfile . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// Read the file
#readfile($myfile);
fclose($handle);
unlink($myfile);
exit;
$dbh = null;
This works perfectly on Apache (XAMPP) but the client has moved to IIS and now my code fails to render the PDF anymore.
Any suggestions?
I'm trying to create a code that, based on informations from BD, creates a bibtex archive. That's what I got:
<?php
include("classe/conexao.php");
session_start();
$_SESSION[id_tese_especifica] = $_GET['id'];
$result = pg_query("SELECT titulo, id, data, autor_nome FROM teses ORDER BY data DESC");
$arr = pg_fetch_array($result);
echo "#phdthesis{phpthesis,
author={" . $arr[0] . "},
title={" . $arr[6] . " " . $arr[3] . "},
month={" . $arr[2] . "}";
$name = $_GET['id'] . ".bib";
$file = fopen($name, 'a');
$text = "test (it doesn't appears on archive and I don't know why, so I used the echo above and worked, but this is what should be on archive, or isn't?)";
fwrite($file, $text);
readfile($file);
fclose($fp);
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
?>
After that, it downloads an archive named 'Resource id #6', why? The name should be based on this: $name = $_GET['id'] . ".bib".
Thanks!
Because filename is stored in a $name variable in your code:
header('Content-Disposition: attachment; filename="' . $name . '"');
And $file variable is a resource, connected with open file.
And by the way - you don't close the file properly.
fclose($fp); // $fp is NOT defined, your pointer is in $file variable
Proper code for closing is:
fclose($file);
Next, rearrange your code.
First of all - headers should be sent BEFORE any output.
What you currently have is some mix of errors, which accidentally show you something that you want.
Proper code should be:
$name = $_GET['id'] . ".bib";
// first of all - set proper headers:
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Expires: 0');
// next - do a query
$result = pg_query("SELECT titulo, id, data, autor_nome FROM teses ORDER BY data DESC");
$arr = pg_fetch_array($result);
// use echo for testing purposes only
// cause echo considered as a content of your file
echo "#phdthesis{phpthesis,
author={" . $arr[0] . "},
title={" . $arr[6] . " " . $arr[3] . "},
month={" . $arr[2] . "}";
$fp = fopen($name, 'a');
$text = "test (it doesn't appears on archive and I don't know why, so I used the echo above and worked, but this is what should be on archive, or isn't?)";
fwrite($fp, $text);
fclose($fp); // don't forget to close file for saving newly added data
readfile($name); // readfile takes a filename, not a handler.
die(); // end your script cause in other case all other data will be outputted too
Here, I want to fetch record from mysql to textfile that I am writing into textfile.
But textfile is creating as blank.
Where is the problem?
My code:
$myFile = 'abctest.txt';
//echo $myFile;exit;
$fo = fopen('com_order/order_textfile/'.$myFile, 'w+') or die("can't open file");
$data_query=mysql_query("SELECT order_id from tbl_order") or die(mysql_error());
while($data=mysql_fetch_array($data_query))
{
$stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
}
fwrite($fo, $stringData);
fclose($fo);
header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);
readfile() call is missing:
readfile($myFile);
So it should look like this:
header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);
readfile($myFile);
Here readfile() is the function which actually performs all the hard work (reads the file, writes to output).
More on the topic:
readfile()
Force download
UPDATE
Also you have a file path problem
Note that you create file in com_order/order_textfile/'.$myFile but then use $myFile without the path. When referencing file you should use path instead:
$myFile = 'abctest.txt';
$filePath = 'com_order/order_textfile/'.$myFile;
$fo = fopen($filePath, 'w+') or die("can't open file");
$data_query=mysql_query("SELECT order_id from tbl_order") or die(mysql_error());
while($data=mysql_fetch_array($data_query))
{
$stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
}
fwrite($fo, $stringData);
fclose($fo);
header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$filePath);
readfile($filePath);
It seems like there is a problem with the way you execute your query but try the code below it's working.
$link = mysqli_connect("localhost", "username", "password", "database name") or die("error unable to connect to database". mysqli_error($link));
$myFile = 'abctest.txt';
//echo $myFile;exit;
$fo = fopen('com_order/order_textfile/'.$myFile, 'w+') or die("can't open file");
$data_query=$link->query("SELECT order_id from tbl_order") or die(mysql_error());
while($data=mysqli_fetch_array($data_query))
{
$stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
//echo("$stringData");
}
fwrite($fo, $stringData);
fclose($fo);
header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);
I would like to query a table to a .csv file and automatically download it. The file is created with the appropriate data but the file that is downloaded displays wrong data.
$filename = 'file.csv';
$i=0;
try {
$stmt = $conn->prepare("SELECT DATE, TYPE, AMOUNT, BALANCE FROM TRANSACTIONS WHERE USERNAME=? ORDER BY DATE ASC");
$stmt->execute(array($user));
$num_rows = $stmt->rowCount();
$handle = fopen($filename, 'w+') or die("can't open file");
fputcsv($handle, array('Date','Type','Amount','Balance'));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row2[$i][0] = $row['DATE'];
$row2[$i][1] = $row['TYPE'];
$row2[$i][2] = $row['AMOUNT'];
$row2[$i][3] = $row['BALANCE'];
$i++;
echo $i;
fputcsv($handle, array($row['DATE'], $row['TYPE'], $row['AMOUNT'], $row['BALANCE']));
}
fclose($handle);
header('Content-disposition: attachment; filename='.$filename);
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($filename));
header("Connection: close");
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
This is how the file looks like when it is downloaded in my browser:
Sometimes it looks like this:
And this is how it looks like when it is created on the server:
The file that is created on the server always contain the appropriate structure and data. The file that is downloaded for the user is different and wrong for some reason.
What is wrong with the code?
I typed
$handle = fopen($filename, 'w+') or die("can't open file");
instead of
$handle = fopen("php://output", "w");
i wrote code for downloading rar file it work's fine but
$name = 'file.rar';
$data = file_get_contents("file.rar");
$fh = fopen("$name", 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$name").";");
header("Content-Disposition: attachment; filename=$name");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($name);
exit;
after downloading , it shows an error unexpected end of archive while open that file,
it won't extract completely give me some suggestions thank you in advance
you can make ZIP file using following code on your web server
<?php
$za = new ZipArchive();
$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
$za->addFile('index.txt', 'newname.txt'); // original file , file to be added in zip
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";
for ($i=0; $i<$za->numFiles;$i++) {
echo "index: $i\n";
print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>
After that you can give link for download..
This file.rar is generating via code?
I have tried your code without these code
$data = file_get_contents("file.rar");
$fh = fopen("$name", 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
Its working fine for me.