I have a script that uploads outside of the webroot. Through the website I then link users to images documents etc.
So for an image the link would be:
media.php?file=nameoffile.jpg&user=userid&folder=images
This is then used to display the image:
<img src="media.php?file=nameoffile.jpg&user=userid&folder=images" width="100" border="0">
This works fine for images and providing a link to download a document.
The problem I face is embedding, I use ffmpeg to convert all allowed videos types to flv (these videos are tested and working great), but when I try to embed the flv video it never works (it works with the direct link of the file just not through media.php). If possible I would also like to embed .swf.
I am using jwplayer to embed (works with the direct link of the file just not through media.php)
<!-- START OF THE PLAYER EMBEDDING TO COPY-PASTE -->
<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="328" height="200">
<param name="movie" value="player.swf" />
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="flashvars" value="media.php?file=nameoffile.flv&user=userid&folder=videos" />
<embed
type="application/x-shockwave-flash"
id="player2"
name="player2"
src="player.swf"
width="328"
height="200"
allowscriptaccess="always"
allowfullscreen="true"
flashvars="file=media.php?file=nameoffile.flv&user=userid&folder=videos"
/>
</object>
<script type="text/javascript" src="jwplayer.js"></script>
<!-- END OF THE PLAYER EMBEDDING -->
Here is media.php:
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$file = basename(urldecode($_GET['file']));
$user = basename(urldecode($_GET['user']));
$folder = basename(urldecode($_GET['folder']));
$ext = pathinfo($file, PATHINFO_EXTENSION);
$fileDir = 'pathoutsidewebroot';
$filePath = $fileDir . $file;
switch(
$ext) {
case "flv": $ctype="video/x-flv"; break;
// adobe
case "pdf": $ctype="application/pdf"; break;
// ms office
case "doc": $ctype="application/msword"; break;
case "rtf": $ctype="application/rtf"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
// open office
case "odt": $ctype="application/vnd.oasis.opendocument.text"; break;
case "ods": $ctype="application/vnd.oasis.opendocument.spreadsheet"; break;
default: $ctype = "application/force-download"; break;
}
if(in_array($ext, $valid_formats_vid)){
if (file_exists($filePath)) {
header('Content-Type: ' . mime_content_type($filePath));
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
}
else if(in_array($ext, $valid_formats_img)) {
if (file_exists($filePath)) {
header('Content-Type: ' . mime_content_type($filePath));
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
}
else if(in_array($ext, $valid_formats_docs)) {
if (file_exists($filePath))
{
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($filePath)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".#filesize($filePath));
set_time_limit(0);
#readfile($filePath) or die("File not found."); }
}
Header from embed that is through media.php
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Disposition:filename=encoded_2012-10-19_22.37.09_1359032866.flv
Content-Length:0
Content-Type:video/x-flv
Date:Thu, 24 Jan 2013 16:26:32 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=88
Pragma:no-cache
Server:Apache/2.2.20 (Ubuntu)
X-Powered-By:PHP/5.3.6-13ubuntu3.8
Header from direct link to file (the one that works)
Accept-Ranges:bytes
Connection:Keep-Alive
Content-Length:2428614
Content-Type:video/x-flv
Date:Thu, 24 Jan 2013 16:23:54 GMT
ETag:"26ca3d8-250ec6-4d4087c796500"
Keep-Alive:timeout=5, max=100
Last-Modified:Thu, 24 Jan 2013 13:07:00 GMT
Server:Apache/2.2.20 (Ubuntu)
Managed to change it to this through media.php (but still not working)
header("Content-Type: $ctype");
header('Content-Length: ' . filesize($filePath));
header('Accept-Ranges: bytes');
$now = time( );
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 365*86440);
header("Expires: $then");
ob_clean();
flush();
readfile($filePath);
Accept-Ranges:bytes
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:2428614
Content-Type:video/x-flv
Date:Thu, 24 Jan 2013 16:44:18 GMT
Expires:Fri, 24 Jan 2014 20:47:38 GMT
Keep-Alive:timeout=5, max=79
Pragma:no-cache
Server:Apache/2.2.20 (Ubuntu)
X-Powered-By:PHP/5.3.6-13ubuntu3.8
The problem is here:
flashvars="file=media.php?file=nameoffile.flv&user=userid&folder=videos"
flashvars receives a query string, so this is interpreted as
file : media.php?file=nameoffile.flv
user : userid
folder : videos
You need to urlencode the file parameter:
flashvars="file=media.php?file=nameoffile.flv&user=userid&folder=videos"
I managed to get it working with the following, I also included a thumb image for the player (this was taken on upload through ffmpeg):
header("Content-Type: $ctype");
header('Content-Length: ' . filesize($filePath));
header('Accept-Ranges: bytes');
$now = time( );
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 365*86440);
header("Expires: $then");
ob_clean();
flush();
readfile($filePath);
$flv_path = 'media.php?file='.$row['cur_image'].'&folder=videos&user='.$row["posted_by"];
$thumb = pathinfo($row['cur_image']);
$thumb_path = 'media.php?file='.$thumb['filename'].'.jpg&folder=videos&user='.$row["posted_by"];
?>
<!-- START OF THE PLAYER EMBEDDING TO COPY-PASTE -->
<div id="mediaplayer_<?php echo $row['p_id']; ?>">JW Player goes here</div>
<script type="text/javascript">
jwplayer("mediaplayer_<?php echo $row['p_id']; ?>").setup({
flashplayer: "jwplayer/jwplayer.flash.swf",
file: "<?php echo $flv_path; ?>",
image: "<?php echo $thumb_path; ?>",
controlbar: "bottom",
width: "380",
height: "200",
primary: "flash",
type: "mp4",
controls: true,
allowscriptaccess: 'always'
});
</script>
<!-- END OF THE PLAYER EMBEDDING -->
One of the file reading methods should work, please review this link: http://www.ibm.com/developerworks/library/os-php-readfiles/
Alter your code, this line: readfile($filePath); with other file reading function, I think streaming should work also with (PHP fread)
PHP Manual: fread : provides useful information, please also try to use first user note.
http://php.net/manual/en/function.fread.php
Related
I have tried to export the mysql data result to excel. After click the Export button, the form will send parameter's value into doexport.php.
The result was appeared in console.
<?php
session_start(); //Start the session
include('install_lang_japanese.php');
//connect to database
$dbc=mysqli_connect(_SRV,_ACCID,_PWD,"QPL");
if(!$dbc){
die('Connect Error: ' . mysqli_connect_error());
}
if(isset($_POST['action'])){
switch($_POST['action']){
case 'senddatacar':
$start = mysqli_real_escape_string($dbc,$_POST['startdate']);
$end = mysqli_real_escape_string($dbc,$_POST['enddate']);
$sqlex = "SELECT * FROM table";
$result =mysqli_query($dbc,$sqlex) or die(_ERROR30.":".mysqli_error($dbc));
$filename="cardata".date('ymd').".xls";
header("Content-type: application/vnd.ms-excel; name='excel'");
header(sprintf("Content-Disposition: attachment; filename=$filename"));
header("Pragma: no-cache");
header("Expires: 0");
//Then echo table
break;
}
mysqli_close($dbc);
}
My problem is : i don't see any file has downloaded as excel
Response Header at console :
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Disposition:attachment; filename=cardata170929.xls
Content-Length:2988
Content-Type:application/vnd.ms-excel; name='excel'
Date:Fri, 29 Sep 2017 05:02:19 GMT
Expires:0
Pragma:no-cache
Server:Apache/2.2.22 (Ubuntu)
I'm trying to load an mp3 into JW Player 5 using php to retrieve the actual file. This is the javascript code for the player:
jwplayer('mediaplayer').setup({
'flashplayer': 'player.swf',
'id': 'playerID',
'type': 'mp3',
'width': '600',
'height': '49',
'file': '/get_mp3/<?php echo $filename; ?>',
});
The file attribute has the URL to the PHP function (I use CakepHP, the part after the last / is the variable that the function gets passed).
This is the PHP function:
function get_mp3($filename) {
$file_path = '/path/to/files/' .$filename. '.mp3';
header("pragma : no-cache");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: audio/mpeg3");
header("Content-Disposition: inline; filename=" .$filename. ".mp3");
header("Content-Location: " .$filename. ".mp3");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file_path));
readfile($file_path);
}
If I call that function via web browser (for example mydomain.com/get_mp3/test_file) it prompts to download the right file, which seems to show that the PHP code is working.
However, when I use it on JW PLayer's file attribute it doesn't load anything or shows any kind of error.
I've tried adapting what's shown in this SO question but I couldn't make it work, I don't know if it's because for video it's different or because that mentoins JW PLayer 6 and mine is 5.
EDIT: test if it's an issue with CakePHP
So test if the issue is that for some reason CakePHP isn't working with JW Player I've put the following PHP code in an external PHP file:
$filename= 'my_filename';
$file = $_SERVER['DOCUMENT_ROOT']. '/path/to/files/' .$filename. '.mp3';
header("pragma : no-cache");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: audio/x-mp3");
header("Content-Disposition: inline; filename=" .$filename. ".mp3");
header("Content-Location: " .$filename. ".mp3");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
readfile($file);
So now, the file line in the JW Player declaration reads like:
'file': '/get_mp3.php',
With that it still doesn't work. If I access the get_mp3.php page directly I get prompted to download the file, so again looks like the PHP code works...
EDIT 2
SO I've found the culprit of the issue: the path of the audio file. If I put the file in the root folder of the website, and I use the file path variable like $file_path = $filename. '.mp3'; it works fine.
The problem is that the audio files are in a different folder in the same server, and I can't move them... How can I change the PHP script to find the files in their current path? I've already tried with $file = '/path/to/files/' .$filename. '.mp3'; and $file = $_SERVER['DOCUMENT_ROOT']. '/path/to/files/' .$filename. '.mp3'; but it doesn't work...
Change your content type to ("Content-Type: audio/x-mp3");
So it turns out my problem was in the path to the file in the PHP script. I was using $_SERVER['DOCUMENT_ROOT'] and just / for the paths and it wasn't working, but then I realized that moving the file to the same folder as the script would work. In my case I still needed to find a way to access those files from a different folder, and using a relative path did the trick. Something like:
$filename= 'my_filename';
$file = '../../../path/to/files/' .$filename. '.mp3';
header("pragma : no-cache");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: audio/x-mp3");
header("Content-Disposition: inline; filename=" .$filename. ".mp3");
header("Content-Location: " .$filename. ".mp3");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
readfile($file);
Since you are using JW5.
Under:
'file': '/get_mp3/<?php echo $filename; ?>',
Add:
'provider': 'sound',
I'm trying to code a function in PHP to export some data to Excel file.
The problem is if I save it to the server it does work, but if I try to send to the browser using php://output it just doesn't work. It doesn't even show the download window. I' ve been getting these as response:
PK����a�B%���a��������[Content_Types].xml͔]K�0���%��f�
"�v��R���kX�����m��+����4�<�'��2�jgs6�,+��v����Sz���a�����tr5^�=Bb�9+c����,��9��.T"�kXr/�J,���[.��`ck6�?h�\��,���ܠ}3�c�C+��9�-E��|c�j�BKPN�+�d��u��O1�
o��Ba +���G�
The headers are:
Response Headers
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection Keep-Alive
Content-Disposition attachment;filename="Report.xlsx"
Content-Type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date Wed, 29 May 2013 10:08:10 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive timeout=15, max=78
Last-Modified Wed, 29 May 2013 10:08:11 GMT
Pragma no-cache
Server Apache/2.2.14 (Ubuntu)
Transfer-Encoding chunked
X-Powered-By PHP/5.3.2-1ubuntu4.19
Request Headers
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cookie PHPSESSID=075r4aaqrvcnbca5sshjvm0jq7; 87293ba76812d31889be0901b086dd73=5h4jriq5c7r9vdt3m2u2u9up43; d82d00149fafbe651c9ba75a9804bbc9=en-GB
Host 150.145.139.3:8889
Referer
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:20.0) Gecko/20100101 Firefox/20.0
X-Requested-With XMLHttpRequest
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/Rome');
require_once 'Classes/PHPExcel.php';
/** PHPExcel_IOFactory */
include 'Classes/PHPExcel/IOFactory.php';
$target ='templates/';
$fileType = 'Excel2007';
$InputFileName = $target.'richiesta.xlsx';
$OutputFileName = $target .'Richiesta_'.$_SESSION['User'].'_'.$_SESSION['Last'].'_'.$dat.'.xlsx';
//Read the file (including chart template)
$objReader = PHPExcel_IOFactory::createReader($fileType);
//$objReader->setIncludeCharts(TRUE);
$objPHPExcel = $objReader->load($InputFileName);
//Change the file
$objPHPExcel->setActiveSheetIndex(0)
// Add data
->setCellValue('C3','10' )
->setCellValue('C4','20' )
->setCellValue('C5','30')
->setCellValue('C5','40' );
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
//$objWriter->save($OutputFileName); //This one WORKS FINE!!!
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Report.xlsx"');
$objWriter->save('php://output'); //NOT WORKING :-(
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
exit;
I'm getting depressed about this problem once I have to finish the project this week.
I really appreciate any kind of help!
That's just from my code, as a hint, the problem seems to be with the Content-Type HTTP header:
if (strtolower($type) == 'excel2003') {
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $outFileName . '"');
header('Cache-Control: max-age=0');
} else {
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
header('Content-Type: application/xlsx');
header('Content-Disposition: attachment;filename="' . $outFileName . '"');
header('Cache-Control: max-age=0');
}
Try using these header() calls:
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=Report.xlsx");
header("Content-Transfer-Encoding: binary ");
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$filename = '1111';
ob_end_clean();
header("Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet");
header('Content-Disposition:attachment;filename="'.$filename.'.xlsx"');
header("Cache-Control: max-age=0");
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit();
I had the same problem, and it seems that a download must be opened in a different tab instead of just downloading in the same tab. Meaning you need to redirect into a new tab before initializing the download.
I've created a .php file that write out js code like that:
<?
//my_js.php
// javascript header
header('Content-type: text/javascript');
// Date in the past
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// always modified
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// HTTP/1.1
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
?>
//
// js code here
//
then i include the script above in my index.php file like this:
<script type="text/javascript" src="my_js.php?id=<? echo $id ?>">
</script>
This works perfect in Firefox, but SAFARI and CHROME doesn't include my_js.php file at all!
What i'm doing wrong?
**edit:
this is the rendered html in index.php:
<script type="text/javascript" src="my_js.php?id=new"></script>
and this is the my_js.php code:
(it's a very big file so i write out only the first few lines)
var g = { sitepath: "myNullUrl" }
function getBrowserWidth(){
if (window.innerWidth){
return window.innerWidth;}
else if (document.documentElement && document.documentElement.clientWidth != 0){
return document.documentElement.clientWidth; }
else if (document.body){return document.body.clientWidth;}
return 0;
}
that's a strange problem 'cos while i'm viewing source code from Crome/Safari i can access the js file and it seems to be error free!
I'm using Chrome 6.04 and Safari 5, both for mac.
It may be because it is expecting the file-extension to be my_js.js. If this is the case, save your PHP file as my_js.js, then, assuming you're using Apache, use the Apache Directive: ForceType:
Like so:
<Location /your/path/my_js.js>
ForceType application/x-httpd-php
</Location>
Good luck!
Maybe set Content-Disposition: inline; header?
<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Content-type: text/javascript");
header("Content-Disposition: inline; filename=\"download.js\"");
header("Content-Length: ".filesize("my-file.js"));
} else {
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"download.js\"");
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
}
include("my-file.js
");
?>
It should work. Or you can change this:
header('Content-type: text/javascript');
to this
header('Content-type: application/javascript');
Note:
application/javascript: JavaScript; Defined in RFC 4329 but not accepted in IE 8 or earlier
text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support
Here is my issue. I am trying to call a page: foo.php?docID=bar and return a PDF to the screen which is stored as a BLOB in the DB.
Here is the portion of my code which actually returns the PDF:
$docID = isset($_REQUEST['docID']) ? $_REQUEST['docID'] : null;
if ($docID == null){
die("Document ID was not given.");
}
$results = getDocumentResults($docID);
if (verifyUser($user, $results['ProductId'])){
header('Content-type: application/pdf');
// this is the BLOB data from the results.
print $results[1];
}
else{
die('You are not allowed to view this document.');
}
This works perfectly fine in Firefox.
However, in IE, it doesn't show anything at all. If i'm on another page (i.e. google.com), and I type in the URL to go to this page, it will say it's done, but I will still have google.com on my screen.
I checked the headers for the responses from both firefox and IE. They are identical.
Does anyone have any suggestions? Need more information?
EDIT: If it helps at all, here's the response header and the first line of the content:
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 349930
Content-Type: application/pdf
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: PHP/5.1.2
Set-Cookie: PHPSESSID=cql3n3oc13crv3r46h2q04dvq4; path=/; domain=.example.com
Content-Disposition: inline; filename='downloadedFile.pdf'
X-Powered-By: ASP.NET
Date: Tue, 21 Apr 2009 16:35:59 GMT
%PDF-1.4
EDIT: Also, the page which pulls out the pdf file actually uses HTTPS instead of HTTP.
Thanks in advance,
~Zack
I figured out what the issue was. It's an IE bug dealing with IE, HTTPS and addons. (See here)
It was a caching issue. When I set:
header("Cache-Control: max-age=1");
header("Pragma: public");
(see here), the PDF was in cache long enough for the adobe reader add-on to grab it.
I had this issue too, i used the following which seems to work fine
header("Content-type: application/pdf");
header("Content-Length: $length");
header("Content-Disposition: inline; filename='$filename'");
Try this:
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=foo.pdf");
header("Accept-Ranges: bytes");
header("Content-Length: $len");
header("Expires: 0");
header("Cache-Control: private");
Also, if you are using sessions, you can try setting
session_cache_limiter("none");
or
session_cache_limiter("private");
if ( USR_BROWSER_AGENT == 'IE' ) {
header( 'Content-Disposition: inline; filename="' . $name . '"');
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Pragma: public' );
} else {
header( 'Content-Disposition: attachment; filename="' . $name . '"' );
header( 'Expires: 0' );
header( 'Pragma: no-cache' );
}
This was the only header I needed to change:
header("Pragma: public");
I think you need to add more headers.
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=THEFILENAME.pdf;");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($results[1]));