jPlayer Safari 5.0.6 not playing audio (PHP download script) - php

I am having problems with jPlayer. Audio is playing fine in the latest version of Safari on Lion but I cannot get it to work in Safari 5.0.6.
I have the audio located outside of httpdocs for security, so have implemented a script to download the audio.
function playSong(id,title){
$("#jquery_jplayer").jPlayer("setMedia", { mp3: "/download.php?id=" + id });
$("#jp_container .track-name").text(title);
$("#jquery_jplayer").jPlayer("play", 0);
}
Download.php currently looks like this, and is a solution I found from another user on stackoverflow.
// array of support file types for download script and there mimetype
$mimeTypes = array(
'doc' => 'application/msword',
'pdf' => 'application/pdf',
'mp3' => 'audio/mpeg'
);
// set the file here (best of using a $_GET[])
$file = "../song_files/mp3/$_GET[id].mp3";
// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);
// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);
$fsize = filesize($file);
// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header('Accept-Ranges: bytes');
header('Content-Range: bytes');
header("Content-Length: ".$fsize);
// reads file and send the raw code to browser
while (! feof($fp)) {
$buff = fread($fp,4096);
echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);
I understand that this may be something to do with the headers I am sending and the older version of Safari isn't processing them correctly, however, I can successfully download the file if I browse to download.php?id=1.
Any idea how I can see what jPlayer is doing, I.E. returning an error such as cannot find file? If somebody can point me in the right direction that would be appreciated.

Related

How to create a pdf file from encoded string content - Codeigniter

I am getting response from cURL which is an encoded string format of pdf(i guess) - see attached image.
I am getting pdf file if i directly put the url in browser. Since its asking for api credentials for viewing the pdf, its not user friendly and i am looking for another way to directly download the file.
So i am trying to get the string content of the pdf file with cURL and i am getting exactly what in the image attached(only small portion attached).
Using that string content, i tried to save it as a plain txt file and from there i tried to decode the string text and to create a pdf file newly. After creating i need to download the same.
I could create text file with the string data i got from cURL and could create pdf also. But the downloaded file showing Failed to load PDF document.
Below is the code i have tried and i am not sure whether i tried correctly or not.
function pdf_download(){
$this->load->helper('file');
$curl = $this->api_call->callapi('GET',APIURL."carts/96171/tickets");
$content = $curl;
$my_file = FCPATH . '/document/text.txt';
if (write_file($my_file, $content) == FALSE)
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
$pdf_base64 = $my_file;
//Get File content from txt file
$pdf_base64_handler = fopen($pdf_base64,'r');
$pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64));
fclose ($pdf_base64_handler);
//Decode pdf content
$pdf_decoded = base64_decode ($pdf_content);
//Write data back to pdf file
$pdf_file=FCPATH . '/document/ticket.pdf';
$pdf = fopen ($pdf_file,'w');
fwrite ($pdf,$pdf_decoded);//Creating a pdf from the encoded content in txt file
fclose ($pdf);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=tickets.pdf");
ob_clean(); flush();
readfile($pdf_file);//downloading the pdf file
exit();
}
Since streaming a download to the browser requires sending headers, you must not output anything before sending headers. Therefore, you must get rid of:
if (write_file($my_file, $content) == FALSE)
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
If you definitely need to check if the file was written (for debugging purposes, I assume) you may use CI's log_message() to write a debug entry in the logs or just set a control variable. For example:
if (write_file($my_file, $content) == FALSE)
{
log_message('debug', "Unable to write file");
$file_written = false;
}
else
{
log_message('debug', "File succesfully written");
$file_written = true;
}
Also, there's some headers missing to ensure the file is not streamed to the browser but sent for download, as well as some required to make sure the file is correctly downloaded
header('Content-Description: File Transfer');
header('Content-Type: '. mime_content_type($pdf_file)); // since you're using Codeigniter, this will try to use the correct mimetype
header('Content-Disposition: attachment; filename="ticket.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($pdf_file));
readfile($pdf_file);
The wrong line in the above given code is $pdf_decoded = base64_decode ($pdf_content);.
It should be changed to $pdf_decoded = $pdf_content;
Since string in encoded format is already getting which is needed for creating PDF. So no need to decode it.
Also the above code is reduced as below.
function pdf_download(){
$this->load->helper('file');
$this->load->helper('download');
$cart_id=$this->input->get('cart_id');
$curl = $this->api_call->callapi('GET',APIURL."cart/'.$cart_id.'/tickets");
$pdf_file=FCPATH . 'document\voucher-'.$cart_id.'.pdf';
if (write_file($pdf_file, $curl))
{
force_download($pdf_file, NULL);
}
}

Problem with generating fopen file in imagick

In Imagick I am trying to do the following:
When accessing .php already begins the download of .jpg, I do not even need a preview just the multiple download because this .pdf in question will always have two pages, with that fopen I can download only the first page, for some reason it does not download the second page.
pdf_file = './programming/'.$date.'.pdf';
$mpdf->Output($pdf_file);
$img = new imagick();
$img->setResolution(200,200);
$img->readImage($pdf_file);
$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$img->setImageFormat('jpg');
$img->setImageCompressionQuality(85);
$pages = $img->getNumberImages();
if ( $pages ) {
foreach($img as $i => $img_file){
$img_file->writeImage('./programming/('.$i.') '.$date.'.jpg');
$img_path = './programming/('.$i.') '.$date.'.jpg';
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="('.$i.') '.$date.'.jpg"');
header("Content-Length: " . filesize($img_path));
$fp = fopen($img_path, "rb");
fpassthru($fp);
fclose($fp);
}
} else {
echo '<h2>Not Found.</h2>';
}
$img->clear();
$img->destroy();
If anyone can guide me, I may have missed something!
Thank you in advance for your attention!
Note: The images that represent page 1 and 2 of the .pdf are already saved in ./programming/ folder, the code works well in that case, then the foreach did what I expected, created two images and stored them but only download one with fopen

How to download all file types using php header

I want to make a force download file to download files from server with saved urls in database and also i don't want to show download links to clients and i know it's possible to make links hidden with htaccess but i want to make limit my links just for clients that paid the cost for each link.
I used php header() function to do my target but the problem is related to mime types i have below script and i don't want to define mime type for each url(based file type and extension) in array or something like that, because i have a wide various of file types in my files and i want to share this files with my users and i can't define one mime type for each file type separately.
I need to a good function to get mime types from file name (automatic) like mime_content_type() but it's related to a php extension and i don't have access to php.ini in my sharing host and also this function is deprecated.
Below codes working good with some extensions like mp3 and zip files but mp4 files that downloaded via this script are damaged and not playable in media player
php codes:
<?php
require 'includes/connection.php';
$connection=newconnection();
if(isset($_GET['fileid']) && is_numeric($_GET['fileid'])){
$file_id=input_security($_GET['fileid']);
$linkque=mysqli_query($connection,"SELECT * FROM download_segments WHERE ds_id='".$file_id."'");
$checkexist=mysqli_num_rows($linkque);
$f_row=mysqli_fetch_array($linkque);
if($checkexist==0){
echo 'Invalid file id';
}else if($checkexist>=1 && $f_row['payment_model']=="free"){
$path=$f_row['url'];
$sep_parts = pathinfo($path);
$file_name = $sep_parts['basename'];
$file_ext = $sep_parts['extension'];
if (file_exists($path)) {
$mimetypes = array(
"avi" => "video/x-msvideo",
"exe" => "application/octet-stream",
"mp4" => "video/mp4",
"zip" => "application/zip",
"mp3" => "audio/mpeg",
"mpg" => "video/mpeg"
);
$mimedefault = "video/mp4";
$mtype=isset($mimetypes[$file_ext]) ? $mimetypes[$file_ext] : $mimedefault;
header('Content-Description: File Transfer');
header("Content-Type: " . $mtype);
header('Content-Disposition: attachment; filename="'.basename($path).'"');
//header('Content-Length: ' . filesize($path) );
//header("Pragma: no-cache");
//header('Expires: 0');
//header('Cache-Control: must-revalidate');
//header('Pragma: public');
readfile($path);
exit;
}else{
echo 'not exist';
}
}
}
?>

Download multiple images into zip

I am trying to add functionality to my website where users can download multiple image files via a single .zip folder. Currently I have this code executing but when i open the downloaded zip file it extracts another zip file my-archive (3) 2.zip.cpgz and every time I try to open it, it extracts yet another zip file.
Here is my basic code using php native zip feature.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
$files = array($image1, $image2);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
EDIT
I am trying hard to get the provided answer to work. I just tried the most recent edit and got this error
]
You should download external files and then archive them.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
$files = array($image1, $image2);
$tmpFile = tempnam('/tmp', '');
$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
// download file
$fileContent = file_get_contents($file);
$zip->addFromString(basename($file), $fileContent);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=file.zip');
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
unlink($tmpFile);
In example above I used file_get_contents function, so please enable allow_url_fopen or use curl to download the files.
Hi guys above code worked perfectly. Images download worked only on live server (only if we use https or http). But it is not worked in local (if we use https or http)..
If you use local follow this -> Only change below lines.
For local use below img's
$image1 = "C:/Users/User/Pictures/Saved Pictures/chandamama.jpg";
$image2 = "C:/Users/User/Pictures/Saved Pictures/beautifull.jpg";
Do not use below img's for local.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";

Downloading a file from server to client's computer

I have a folder in my root dir called files.
This folder contains files ranging from 1 Kb-1 GB.
I want a php script that can simply download a file asynchronously using AJAX.
This codes initiates download scripts when a file is clicked:
JQUERY
$('.download').click(function(){
var src =$(this).attr('src');
$.post('download.php',{
src : src //contains name of file
},function(data){
alert('Downloaded!');
});
});
PHP
<?php
$path = 'files/'.$_POST['src'];
//here the download script must go!
?>
Which would be the best, fastest and secure way to download a file?
<?php
/**
* download.php
*/
if (!empty($_GET['file'])) {
// Security, down allow to pass ANY PATH in your server
$fileName = basename($_GET['file']);
} else {
return;
}
$filePath = '???/files/' . $fileName;
if (!file_exists($filePath)) {
return;
}
header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: application/pdf");
readfile($filePath);
And actually AJAX request is unnecessary, when using Content-disposition: attachment:
File1
To continue on the original answer, I've added a few php functions to make it a bit more programmatic:
$filePath = $_GET['path'];
$fileName = basename($filePath);
if (empty($filePath)) {
echo "'path' cannot be empty";
exit;
}
if (!file_exists($filePath)) {
echo "'$filePath' does not exist";
exit;
}
header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: " . mime_content_type($filePath));
readfile($filePath);
If your sever requires strong security, do not use this function without pre-validating the user in the same script. Or use the security measures posted by the original answer. This script will allow any file on your server to be downloaded by a user.

Categories