Here is my code..
<?php
ob_clean();
$params = Zend_Controller_Front::getInstance()->getRequest()->getParams();
// block any attempt to the filesystem
if (isset($params['file']) && basename($params['file']) == $params['file']) {
$filename = $params['file'];
} else {
$filename = NULL;
}
// define error message
$err = '<div class="right-panel fl">
<h1> Download Question </h1> <a href="JavaScript:void(0)" class="button" onclick="javascript:history.go(-1)" > Back </a>
<div class="gradient-box" style="margin-top:20px;" ><p style="color:#990000">Sorry, the file you are requesting is unavailable.</p></div></div>';
if (!$filename) {
// if variable $filename is NULL or false display the message
echo $err;
} else {
// define the path to your download folder plus assign the file name
$path = BASE_PATH.QUESTIONS_FILE_PUBLIC.$filename;
$path2 = REL_PATH.QUESTIONS_FILE.$filename;
// check that file exists and is readable
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header("Content-type: video/flv");
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
echo file_get_contents($path);
//#readfile($path);
exit;
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo $err;
}
}
?>
Try to use function from this comment to force browser to open download file dialog. It must help.
Related
I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}
if($_POST) {
$mysql_pass = '';
$connect = #mysql_connect($_POST['dbHost'], $_POST['dbUser'], $mysql_pass);
if($connect) {
if(#mysql_select_db($_POST['dbName'])) {
$dir = $_SERVER['SERVER_NAME']. $_SERVER['REQUEST_URI'];
$redirectUrl = str_replace("configForm.php","site/index", $dir);
print $redirectUrl; exit;
$dbConf = dirname(__FILE__).'/dbConfig/dbconf.php';
$handle = fopen($dbConf, 'w') or die('Cannot open file: '.$dbConf);
$data = '<?php $userName="'.$_POST['dbUser'].'";'."\n";
$data .= '$passWord=" ";'."\n";
$data .= '$dbName="'.$_POST['dbName'].'";'."\n";
$data .= '$host="'.$_POST['dbHost'].'"; ?>';
fwrite($handle, $data);
header('Location: site/index');
}
else {
$error = 'Could not select database.';
}
}
else
$error = 'Not connected';
}
when the code above was executed, my webpage just displayed "localhost/www-edusec/site/index". i do not know where i do it wrong. my form action is like below:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
The action attribute defaults to the current page anyway, so that piece of code is surely redundant.
The problem is PHP_SELF returns the path to the file too. Just get rid of the action line completely and it should work fine.
EDIT:
Also, the reason your script is cutting off half way, you have an exit; after it prints out the directory.
i got this code in attaching a pdf file to my site in order for the viewers to download such pdf file..
$fullPath = "../public/pdffiles/FolioPlusUserGuide(v3.0).pdf";
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
html code:
baseUrl().'/DownloadPdf'?>">DOWNLOAD BROCHURE
this code only accommodates 1 file path, I have more pdf files with different filename and different buttons for each to handle the download event. how can i achieve this?..thanks ahead!..=)
You can pass PDF file name via HTTP request, like this:
DownloadPDF.php?filename=test1.pdf
Then in your DownloadPDF file have something like this:
$pdfdir = "/pdffiles/folder/location/here";
$pdffilename = $_GET['filename'];
$fullPath = $pdfdir.$pdffilename;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Now your code is dynamic and you can download any PDF with links like this:
<a href=downloadpdf.php?filename=something.pdf>Something</a>
<a href=downloadpdf.php?filename=something2.pdf>Something2</a>
etc.
I am using zend frame works . I want to include file download section in my application. I am using this code
> header('Content-Type: application/doc'); header('Pragma: no-cache');
> header('Content-Disposition: attachment; filename="'.$resume.'"');
> readfile(RESUME_PATH_WS . $resume);
But this code is not working .It return file with 0byte . Please help me how to i download files in zend frame work
public function downloadAction() {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$filename = $this->_request->getParam('filename');
$filePath = folder/path to file/ . $filename;
if (file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: " . $fileSize);
header("Content-Disposition: attachment; filename=" . $fileName);
readfile($filePath);
exit();
} else {
die('The provided file path is not valid.');
}
}
Simply in your html side
Download
I am new to php. have a task to ftp only todays files from the server containing files for over a week. how do i select or filter the files based on date and ftp to my local folder.
Help is much appreciated !!
Soloman
If you already have the filenames to check, use filemtime
Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.
To compare that today, you can use date('Y-m-d') to get today compare to date('Y-m-d', filemtime($filename))
To get the filenames, you could use readdir to read each one in turn.
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($filename = readdir($handle))) {
echo "$filename\n";
}
closedir($handle);
}
?>
The manual also has an FTP example which should show you how to ftp the file once found.
So, combining all this, you could get something like:
<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
if ($handle = opendir('/path/to/files')) {
while (false !== ($filename = readdir($handle))) {
if (date('Y-m-d') == date('Y-m-d', filemtime($filename))) {
// upload the file
$upload = ftp_put($conn_id, $destination_file, $filename, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
}
}
closedir($handle);
// close the FTP stream
ftp_close($conn_id);
?>
Of course, you will need to fill in the dummy values as appropriate.
Disclaimer: I typed this in notepad++ and it is not tested for any mistakes!
link :
http://www.php.net/manual/en/function.ftp-rawlist.php
you connect to the server ,
get the list of the files with ftp_rawlist()
and get only file you want via ftp_fget()
example
<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// get the file list for /
$rawfiles = ftp_rawlist($conn_id, '/');
foreach ($rawfiles as $rawfile) {
# parse the raw data to array
if(!empty($rawfile)) {
$info = preg_split("/[\s]+/", $rawfile, 9);
$arraypointer[] = array(
'text' => $info[8],
'isDir' => $info[0]{0} == 'd',
'size' => byteconvert($info[4]),
'chmod' => chmodnum($info[0]),
'date' => strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]),
'raw' => $info
// the 'children' attribut is automatically added if the folder contains at least one file
);
// pseudo code check the date
if($arraypointer['date'] is today)
ftp_fget(file);
}
// close the connection
ftp_close($conn_id);
// output the buffer
var_dump($buff);
?>