i am try to download a specific file using PHP, if i specify the code like so:
<?php
$file = '/home/myhome/public_html/myfolder/940903105955.txt';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
it works, however notice that the file name is specified.
However, if i do this:
<?php
$file_name = $_GET['file_name'];
$file = '/home/myhome/public_html/myfolder/' + $file_name;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
it doesnt work, why is it so?
This is the java code to handle the download to my pc:
public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(fileUrl).openStream());
fout = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
System.out.print(data);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
This is how i call the function:
private void btn_downloadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String url = "http://myurl.com/download_resubmission_file.php?file_name="+ "940903105955.txt";
try {
saveFileFromUrlWithJavaIO(path_to_save_file, url);
} catch (IOException ex) {
Logger.getLogger(InsuranceMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
Try to change this line:
$file = '/home/myhome/public_html/myfolder/' + $file_name;
to:
$file = '/home/myhome/public_html/myfolder/' . $file_name;
in your PHP file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.