Trying to do so that you can download. With sftp in php - php

I try to do so that I can download files but I have a problem and don't know how to fix it can you help me find the error?
Nothing happens. And help me to get this to work. I don't know how to fix this so need all the help I can get.
<?php
require("configuration.php");
require("include.php");
require_once('./libs/phpseclib/SFTP.php');
require_once("./libs/phpseclib/Crypt/AES.php");
if(!isset($_SESSION['clientid']))
{
//DON'T KNOW HOW THE REQEUSTOR IS!!
die();
}
$clientid = $_SESSION['clientid'];
$serverid = '';
$extendedPath = '';
$action = '';
if(!isset($_GET['serverid']) or !isset($_GET['path']) or !isset($_GET['action']))
{
die();
}
$serverid = $_GET['serverid'];
$extendedPath = $_GET['path'];
$action = $_GET['action'];
$boxDetailsSQL = sprintf("SELECT box.boxid, box.ip, box.login, box.password, box.sshport, srv.path
FROM %sbox box
JOIN %sserver srv ON box.boxid = srv.boxid
JOIN %sgroupMember grpm ON (grpm.groupids LIKE CONCAT(srv.groupid, ';%%')
OR grpm.groupids LIKE CONCAT('%%;', srv.groupid, ';%%'))
WHERE srv.serverid = %d
AND grpm.clientid = %d;", DBPREFIX, DBPREFIX, DBPREFIX, $serverid, $clientid);
$boxDetails = mysql_query($boxDetailsSQL);
$rowsBoxes = mysql_fetch_assoc($boxDetails);
$aes = new Crypt_AES();
$aes->setKeyLength(256);
$aes->setKey(CRYPT_KEY);
$sftp= new Net_SFTP($rowsBoxes['ip'], $rowsBoxes['sshport']);
if(!$sftp->login($rowsBoxes['login'], $aes->decrypt($rowsBoxes['password'])))
{
echo 'Failed to connect';
die();
}
//ACTION SELECTOR
if($action == 'list')
{
getlist($rowsBoxes, $extendedPath, $sftp);
}
if($action == 'fileUpload')
{
fileUpload($rowsBoxes, $extendedPath, $sftp);
}
if($action == 'download')
{
delete($rowsBoxes, $extendedPath, $sftp);
}
//ACTION FUNCTIONS
function download($rowsBoxes, $extendedPath, $sftp)
{
$remoteFile = dirname($rowsBoxes['path']).'/'.trim($extendedPath.'/');
$downloadfile $sftp->put($remoteFile);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($downloadfile));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($downloadfile));
readfile($downloadfile);
}
This code I need help to fix.
function download($rowsBoxes, $extendedPath, $sftp)
{
$remoteFile = dirname($rowsBoxes['path']).'/'.trim($extendedPath.'/');
$downloadfile $sftp->put($remoteFile);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($downloadfile));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($downloadfile));
readfile($downloadfile);
}

You're calling getList, fileUpload or delete, depending on the value of $_GET['action'] but you're not calling download at all. You've defined that function but you aren't calling it in your code snippet. And in your download function...
$downloadfile $sftp->put($remoteFile);
You should probably be doing this instead:
$downloadfile = $sftp->get($remoteFile);
Also, instead of doing filesize($downloadfile) do strlen($downloadfile) and instead of readfile($downloadfile) do echo $downloadfile;. If you want to save to a local file do $sftp->get($remoteFile, $downloadfile);
Updated code:
function download($rowsBoxes, $extendedPath, $sftp)
{
$remoteFile = dirname($rowsBoxes['path']).'/'.trim($extendedPath.'/');
$downloadfile = $sftp->get($remoteFile);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($downloadfile));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($downloadfile));
echo $downloadfile;
}
If you want to do something like display an image do this:
function download($rowsBoxes, $extendedPath, $sftp)
{
$remoteFile = dirname($rowsBoxes['path']).'/'.trim($extendedPath.'/');
$downloadfile = $sftp->get($remoteFile);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default:
}
header('Content-type: ' . $ctype);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo $downloadfile;
}

Related

Adding another URL into a download script

I have a video streaming website which also allows users to download videos. This runs over a download script that loads the videos id on the server and initiates a direct file transfer.
Now I want to put another URL in front of it instead of having the direct file transfer. I tried to make a mod_rewrite rule, but it causes a loop and redirects on that URL forever. Its a link shortening service which allows monetarization.
So, how do I archieve this? Is it possible to archieve it with a mod_rewrite rule?
Trying the mod_rewrite rule, realizing I can't change the base_url variable in PHP because it would not find the file anymore.
$vid = intval($_GET['id']);
$label = intval($_GET['label']);
$sql = "SELECT * FROM video WHERE VID = ".$vid." LIMIT 1";
$rs = $conn->execute($sql);
$formats = $rs->fields['formats'];
$server = $rs->fields['server'];
$formats_arr = explode(',', $formats);
if ($server != '') {
$sql = "SELECT * FROM video v, servers s WHERE v.VID = ".$vid." AND v.server = s.video_url LIMIT 1";
$rs = $conn->execute($sql);
$video_root = $rs->fields['video_url'];
}
if (!$video_root) {
$video_root = $config['BASE_DIR']."/media/videos";
}
foreach ($formats_arr as $format) {
$f = explode('.', $format);
if ($label == $f[1]) {
if ($f[0] >= 481) {
$condition = $new_permisions['hd_downloads'];
} else {
$condition = $new_permisions['sd_downloads'];
}
$file = $video_root.'/h264/'.$vid.'_'.$f[1].'.'.$f[2];
$file_name = $vid.'_'.$f[1].'.'.$f[2];
break;
}
}
if ($condition == 1) {
ini_set('memory_limit', '-1');
if (!$server) {
if (file_exists($file) && is_file($file) && is_readable($file)) {
$conn->execute("UPDATE video SET download_num = download_num+1 WHERE VID = ".$vid." LIMIT 1");
#ob_end_clean();
if(ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Cache-control: private');
header('Pragma: private');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-Length: ' .filesize($file));
readfile($file);
exit();
} else {
VRedirect::go($config['BASE_URL']. '/error');
}
} else {
$conn->execute("UPDATE video SET download_num = download_num+1 WHERE VID = ".$vid." LIMIT 1");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: chunked');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
$stream = fopen('php://output', 'w');
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_READFUNCTION, function($ch, $fd, $length) use ($stream) {
return fwrite($stream, fread($fd, $length));
});
The download button should open URL/download.php with my link shortener URL in front of it, so it will load and redirect to the file download URL.

CSV file getting downloaded twice

I am using following code to download csv file.
static function download(){
$wooe_download = filter_input(INPUT_GET, 'woooe_download', FILTER_DEFAULT);
$wooe_filename = filter_input(INPUT_GET, 'filename', FILTER_DEFAULT);
if( !empty($wooe_filename) && !empty($wooe_download) && file_exists(path_join( self::upload_dir(), $wooe_filename.'.csv'))
&& wp_verify_nonce($wooe_download, 'woooe_download')
)
{
$charset = get_option('blog_charset');
$csv_file = path_join( self::upload_dir(), $wooe_filename.'.csv');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=". self::filename());
header("Expires: 0");
header('Cache-Control: must-revalidate');
header('Content-Encoding: '. $charset);
header('Pragma: public');
//header('Content-type: text/csv; charset='. $charset);
header('Content-Length: ' . filesize($csv_file));
//header("Pragma: public");
readfile($csv_file);
//unlink($csv_file);
exit;
}
}
File is getting downloaded twice in browser. I am not sure how to restrict it to only once?

Unable to download my CSV file on Safari using PHP

I am facing with strange problem while exporting my csv file on safari it is just displaying on browser instead of downloading .While same code is working with Firefox and Crome.I have searched but nothing is working for me. Please help. Here is my code-
<?php
ob_clean();
ob_start();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
function exportData() {
$fp = fopen('php://output', 'w');
fputcsv($fp, array('Market ID', 'Market Name', 'Suburb', 'State', 'Start Time', 'End Time', 'Status',"~"));
include "database.php";
$dbquery = #$_POST['query'];
$queryAllUser = $dbquery;
$resultAllUser = mysql_query($queryAllUser);
$countAllUser = mysql_num_rows($resultAllUser);
if($countAllUser > 0)
{
while($rowMarketId= mysql_fetch_assoc($resultAllUser))
{
$marketId = $rowMarketId['mrkt_id'];
$isCancel = $rowMarketId['is_cancel'];
$openning_tim = $rowMarketId['openning_time'];
$closing_tim = $rowMarketId['closing_time'];
$suburb = $rowMarketId['suburb'];
$name = $rowMarketId['name'];
$state = $rowMarketId['state'];
if($isCancel == 0)
{
$status_type = "Open";
}
else
{
$status_type = "Close";
}
$val = array();
$val[] = $marketId;
$val[] = $name;
$val[] = $suburb;
$val[] = $state;
$val[] = $openning_tim;
$val[] = $closing_tim;
$val[] = $status_type;
$val[] = "~";
fputcsv($fp, $val);
}
}
}
exportData();
?>
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' .urlencode(basename($filename)));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
Try With this Headers........ This should Work..

Alamofire download file with progress issue

I want to download a file from server with progress. Here is the code I've tried:
let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
(temporaryURL, response) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
let path = directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
return path
}
return temporaryURL
}
Alamofire.download(.GET, fileUrls[button.tag], destination: destination)
.progress { _, totalBytesRead, totalBytesExpectedToRead in
dispatch_async(dispatch_get_main_queue()) {
println("\(Float(totalBytesRead)) - \(Float(totalBytesExpectedToRead))")
if totalBytesRead == totalBytesExpectedToRead {
println("******************************")
println("finished")
println("******************************")
}
}
}
.response { (_, _, data, error) in
println(data)
println(error)
}
But totalBytesExpectedToRead is always -1. I've searched this issue and found that Content-Length on server side isn't set.
I've tried to set it but it doesn't seem to work:
$attachment_location = $_GET["filepath"];
if (file_exists($attachment_location)) {
header('Content-Description: File Transfer');
header('Content-Type:' . mime_content_type($attachment_location));
header('Content-Disposition: attachment; filename='.basename($attachment_location));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($attachment_location));
readfile($attachment_location);
die();
} else {
die("Error: File not found.");
}
Can some one tell me what I'm doing wrong? Thanks.
Solved by changing the code to this:
$attachment_location = $_GET["filepath"];
if (file_exists($attachment_location)) {
header('Content-Description: File Transfer');
header('Content-Type:' . mime_content_type($attachment_location));
header('Content-Disposition: attachment; filename='.basename($attachment_location));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Encoding: chunked');
header('Content-Length: ' . filesize($attachment_location), true);
readfile($attachment_location);
die();
} else {
die("Error: File not found.");
}

force file download code work on localhost but not working on actual server in php

I'm php programmer of beginner. I have write code to download file of any type.
When I click on download link it goes to download.php file. I work on local server but not working on server.
My code is:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); //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();
Is my code wrong or does server need some settings?
this is code tested online its working fine. u can try this
$folder_name = $_GET['fol_name'];
$file_directory = "../img/files/$folder_name"; //Name of the directory where all the sub directories and files exists
$file = $_GET['file_name']; //Get the file from URL variable
$file_array = explode('/', $file); //Try to seperate the folders and filename from the path
$file_array_count = count($file_array); //Count the result
$filename = $file_array[$file_array_count-1]; //Trace the filename
$file_path = dirname(__FILE__).'/'.$file_directory.'/'.$file; //Set the file path w.r.t the download.php... It may be different for u
if(file_exists($file_path)) {
header("Content-disposition: attachment; filename={$filename}"); //Tell the filename to the browser
header('Content-type: application/octet-stream'); //Stream as a binary file! So it would force browser to download
readfile($file_path); //Read and stream the file
}
else {
echo "Sorry, the file does not exist!";
}
thank u !!
by using code written by me. this problem is solved.
if anybody have same issue. please try this code. it works for me very good.
$file_name ='../img/files'.DS.$_GET['file'];
if(is_file($file_name)) {
if(ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'ON');
}
switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
case 'pdf': $mime = 'application/pdf'; break; // pdf files
case 'zip': $mime = 'application/zip'; break; // zip files
case 'jpeg': $mime = 'image/jpeg'; break;// images jpeg
case 'jpg': $mime = 'image/jpg'; break;
case 'mp3': $mime = 'audio/mpeg'; break; // audio mp3 formats
case 'doc': $mime = 'application/msword'; break; // ms word
case 'avi': $mime = 'video/x-msvideo'; break; // video avi format
case 'txt': $mime = 'text/plain'; break; // text files
case 'xls': $mime = 'application/vnd.ms-excel'; break; // ms excel
default: $mime = 'application/force-download';
}
header('Content-Type:application/force-download');
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
//header('Content-Length: '.filesize($file_name)); // provide file size
header('Connection: close');
readfile($file_name);
exit();
}
thank u!!!
I recently got this problem and discovered that this was being caused by ob_clean();
and flush(); These are causing the program to download garbage.
I tried various combinations to flush the buffer and the only one which worked on the hosting server was
ob_end_clean();
print $object->body;
It might work with echo as well but i didn't try it
use this
public function loadfile($fl)
{
$mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($fl).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile($fl); // push it out
exit();
}

Categories