PHP Download File Script (doesn't work) - file

I have never written an PHP Download File Script neither have any experience with it and I am really not a pro. I got the snippet of code you can see below from another website and tried to make use of it. I understand what is written in the script but I just don't get the message of the errors or rather said, I don't know how to prevent these.
Here is the download.php script - I have put it into the /download/ folder below my main domain:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Now in the /download/ folder, which contains the download.php I have a folder /downloads, which contains the .pdf that should be downloaded.
The link I use on my webpage is:
PHP download file (why isn't it displayed, included the 4 white spaces :
Now I get the following errors when I click on the link:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(/downloads/test.pdf): failed to open stream: No such file or directory in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
If I use an absolute path (https://www.my-domain.de/downloads/) for the $path variable, I get these errors:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /var/www/xxx/html/download/download.php on line 12
Warning: fopen(https://www.my-domain.de/downloads/test.pdf): failed to open stream: no suitable wrapper could be found in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
I am thankful for any advices!

<?php
ignore_user_abort(true);
//set_time_limit(0); disable the time limit for this script
$path = "downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
?>
Try this code
Your server is probably not allowing you for a maximum execution time limit for infinite seconds. Check it in php.ini file
Also the relative path was wrong, and "https://www.my-domain.de/downloads/" is not a path, it's a url for the server

Related

Error loading physionet ECG database on MATLAB

I'm using this code to load the ECG-ID database into MATLAB:
%% Initialization
clear all; close all; clc
%% read files from folder A
% Specify the folder where the files live.
myFolder = 'Databases\ECG_ID';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder;)
uiwait(warndlg(errorMessage);)
myFolder = uigetdir(; % Ask for a new one.)
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '**/rec_*'; % Change to whatever pattern you need.)
theFiles = dir(filePattern;)
for k = 1 : length(theFiles)
baseFileName = theFiles(k.name;)
fullFileName = fullfile(theFiles(k.folder, baseFileName);)
fprintf(1, 'Now reading %s\n', fullFileName;)
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
[sig, Fs, tm] = rdsamp(fullFileName, [1],[],[],[],1;)
end
But I keep getting this error message:
Now reading C:\Users\******\Documents\MATLAB\Databases\ECG_ID\Person_01\rec_1.atr
Error using rdsamp (line 203)
Could not find record: C:\Users\******\Documents\MATLAB\Databases\ECG_ID\Person_01\rec_1.atr. Search path is set to: '.
C:\Users\******\Documents\MATLAB\mcode\..\database\ http://physionet.org/physiobank/database/'
I can successfully load one signal at a time (but I can't load the entire database using the above code) using this command:
[sig, Fs, tm] = rdsamp('Databases\ECG_ID\Person_01\rec_1');
How do I solve this problem? How can I load all the files in MATLAB?
Thanks in advance.

Perl: Getting UTF-8 file with Mechanize content_file

Creating a perl script (Strawberry Perl v5.32.0 on W10) to download my Google Calendar. Google provides a 'private' (no login required) url to a 'basic.ics' file.
When opening this url in my browser (firefox), a window pops up to download this 'basic.ics' file. When saved, the file is UTF-8 encoded.
In my script I'm using WWW::Mechanize get ":content_file" to download the file:
#!/usr/bin/perl -w
use WWW::Mechanize;
# URL modified for obvious reasons ...
my $url = 'https://calendar.google.com/path-to-private-calendar-file/basic.ics';
my $local_file_name = 'Calendar.ics';
my $mech = WWW::Mechanize->new();
$mech->get( $url, ":content_file" => $local_file_name );
The file received with $mech->get however, is written ANSI-encoded and contains 'gibberich' (not 'translated' UTF-8 data, I suppose).
How can I make the get :content_file create the local file UTF-8 encoded ?
Or do I just download the file as is and convert it to UTF-8 later ?
If so please point me in the right direction, because reading the ANSI-encoded file as UTF-8 does not do the trick ...
This has nothing to do with UTF-8 or character encodings. You are getting a gzip-compressed response.
If Compress::Zlib is available, WWW::Mechanize provides the following header by default:
Accept-Encoding: gzip
This allows the remote end to compress the response. If it does, the remote end will provide the following header in the response:
Content-Encoding: gzip
This is happening here, and you are saving the compressed response.
You could use :content_cb instead of :content_file to provide a callback that decompresses the data and stores it. Or you could simply request an uncompressed version by providing the following header:
Accept-Encoding: identity
This is done using
$mech->get($url,
Accept_Encoding => 'identity',
":content_file" => $local_file_name,
);
If you don't otherwise need the overhead of WWW::Mechanize, why not use its base class LWP::UserAgent. It doesn't provide an Accept-Encoding by default, so the server is unlikely to gzip the response
my $ua = LWP::UserAgent->new();
# Will work 99.999% of the time.
$ua->get($url, ":content_file" => $local_file_name);
# Definitely works.
$ua->get($url,
Accept_Encoding => 'identity',
":content_file" => $local_file_name,
);
Sorry for my late reply, but I had some other items to handle.
Thanks to ikegami and Hakon for your replies and solutions.
From your replies, I have distilled 4 methods that get a readable UTF-8 encoded non-zipped result file:
Mechanize + Content_file and encoding
UserAgent + Content_file, no encoding
UserAgent + Content_file and encoding
UserAgent + print content to file
In the last case, however, there was an extra CR at the end of each line (CRCRLF instead of CRLF), but nothing a little regex can't solve ...
Here is the result of my tests:
CASE 1: Mechanize + Content_file and encoding ...
Get: $mech1->get($url, Accept_Encoding => 'identity', ":content_file" => $fn1)
Calendar1.ics received, size = 78564 bytes
CASE 2: UserAgent + Content_file, no encoding ...
Get: $ua2->get($url, ":content_file" => $fn2);
Calendar2.ics received, size = 78564 bytes
CASE 3: UserAgent + Content_file and encoding ...
Get: $ua3->get($url, Accept_Encoding => 'identity', ":content_file" => $fn3);
Calendar3.ics received, size = 78564 bytes
CASE 4: UserAgent + print content to file ...
Get: my $res4 = $ua4->get($url);
...
my $content = $res4->content;
$content =~ s/\r[\n]*/\n/gm;
print $fh $content;
...
Calendar4.ics received, size = 78564 bytes
Yes, I also get some sort of encrypted file when using WWW::Mechanize, however LWP::UserAgent works fine for me:
use feature qw(say);
use strict;
use warnings;
use LWP::UserAgent;
my $fn = 'Calendar.ics';
my $url = 'https://calendar.google.com/calendar/XXXXXXXX/basic.ics';
my $ua = LWP::UserAgent->new();
my $res = $ua->get( $url );
if ($res->is_success) {
say "Saving file: '$fn'";
open ( my $fh, '>', $fn ) or die "Could not open file '$fn': $!";
print $fh $res->content;
close $fh;
}
else {
die $res->status_line;
}

how to get filename by file_id in telegram

for my new bot i need to get real file name.
when i get the file_id and requesting for generate download link with "get file" commend, the file name is look like "file_370.mp3" but the real file name is:"michaeljackson.mp3".
i tried this code:
$mp3name = $result['message']['audio']['title'];
$mp3fileid = $result['message']['audio']['file_id'];
file_get_contents( $url."/sendaudio?chat_id=118718802&audio=$mp3fileid&performer=awaperformer&title=awatitle");
$bot_url = "https://api.telegram.org/bot".$botToken;
$file_path_gen_url = $bot_url."/getfile?file_id=".$mp3fileid;
// file_get_contents( $url."/sendmessage?chat_id=118718802&text=lastfileid:filegen:$file_path_gen_url");
$file_path_result = file_get_contents($file_path_gen_url);
// echo "last file id: $last_file_id <br>";
$file_path_result = json_decode($file_path_result, TRUE);
$file_path = $file_path_result['result']['file_path'];
// echo "file_path: $file_path <br>";
$file_url = "https://api.telegram.org/file/bot".$botToken."/".$file_path;
how can i get real file name?
You can't get original file name for audio object.
here avaliable attributes : https://core.telegram.org/bots/api#audio
You can get original file name for document object.

Handling Hebrew files and folders with Python 3.4

I used Python 3.4 to create a programm that goes through E-mails and saves specific attachments to a file server.
Each file is saved to a specific destination depending on the sender's E-mail's address.
My problem is that the destination folders and the attachments are both in Hebrew and for a few attachments I get an error that the path does not exsist.
Now that's not possible because It can fail for one attachment but not for the others on the same Mail (the destination folder is decided by the sender's address).
I want to debug the issue but I cannot get python to display the file path it is trying to save correctly. (it's mixed hebrew and english and it always displays the path in a big mess, although it works correctly 95% of the time when the file is being saved to the file server)
So my questions are:
what should I add to this code so that it will proccess Hewbrew correctly?
Should I encode or decode somthing?
Are there characters I should avoid when proccessing the files?
here's the main piece of code that fails:
try:
found_attachments = False
for att in msg.Attachments:
_, extension = split_filename(str(att))
# check if attachment is not inline
if str(att) not in msg.HTMLBody:
if extension in database[sender][TYPES]:
file = create_file(str(att), database[sender][PATH], database[sender][FORMAT], time_stamp)
# This is where the program fails:
att.SaveAsFile(file)
print("Created:", file)
found_attachments = True
if found_attachments:
items_processed.append(msg)
else:
items_no_att.append(msg)
except:
print("Error with attachment: " + str(att) + " , in: " + str(msg))
and the create file function:
def create_file(att, location, format, timestamp):
"""
process an attachment to make it a file
:param att: the name of the attachment
:param location: the path to the file
:param format: the format of the file
:param timestamp: the time and date the attachment was created
:return: return the file created
"""
# create the file by the given format
if format == "":
output_file = location + "\\" + att
else:
# split file to name and type
filename, extension = split_filename(att)
# extract and format the time sent on
time = str(timestamp.time()).replace(":", ".")[:-3]
# extract and format the date sent on
day = str(timestamp.date())
day = day[-2:] + day[4:-2] + day[:4]
# initiate the output file
output_file = format
# add the original file name where needed
output_file = output_file.replace(FILENAME, filename)
# add the sent date where needed
output_file = output_file.replace(DATE, day)
# add the time sent where needed
output_file = output_file.replace(TIME, time)
# add the path and type
output_file = location + "\\" + output_file + "." + extension
print(output_file)
# add an index to the file if necessary and return it
index = get_file_index(output_file)
if index:
filename, extension = split_filename(output_file)
return filename + "(" + str(index) + ")." + extension
else:
return output_file
Thanks in advance, I would be happy to explain more or supply more code if needed.
I found out that the promlem was not using Hebrew. I found that there's a limit on the number of chars that the (path + filename) can hold (255 chars).
The files that failed excided that limit and that caused the problem

Groovy - create file issue: The filename, directory name or volume label syntax is incorrect

I'm running a script made in Groovy from Soap UI and the script needs to generate lots of files.
Those files have also in the name two numbers from a list (all the combinations in that list are different), and there are 1303 combinations
available and the script generates just 1235 files.
A part of the code is:
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
where $file is actually that part of the file name which include those 2 combinations from that list:
file = "abc" + "-$firstNumer"+"_$secondNumber"
For those file which are not created is a message returned:"The filename, directory name or volume label syntax is incorrect".
I've tried puting another path:
filename = "D:\\rez\\" + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
and also:
File parentFolder = new File("D:\\rez\\");
File targetFile = new File(parentFolder, "$file"+"_OK.txt");
targetFile.createNewFile();
(which I've found here: What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect")
but nothing worked.
I have no ideea where the problem is. Is strange that 1235 files are created ok, and the rest of them, 68 aren't created at all.
Thanks,
My guess is that some of the files have illegal characters in their paths. Exactly which characters are illegal is platform specific, e.g. on Windows they are
\ / : * ? " < > |
Why don't you log the full path of the file before targetFile.createNewFile(); is called and also log whether this method succeeded or not, e.g.
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
println "attempting to create file: $targetFile"
if (targetFile.createNewFile()) {
println "Successfully created file $targetFile"
} else {
println "Failed to create file $targetFile"
}
When the process is finished, check the logs and I suspect you'll see a common pattern in the ""Failed to create file...." messages
File.createNewFile() returns false when a file or directory with that name already exists. In all other failure cases (security, I/O) it throws an exception.
Evaluate createNewFile()'s return value or, additionally, use the File.exists() method:
File file = new File("foo")
// works the first time
createNewFile(file)
// prints an error message
createNewFile(file)
void createNewFile(File file) {
if (!file.createNewFile()) {
assert file.exists()
println file.getPath() + " already exists."
}
}

Resources