Ok so I found this off somewhere this website and I tried this but it is just spamming my console with a ton of errors, I don't get what I'm doing wrong
<?php
set_time_limit(0);
$dirPath = "masked on purpose";
$songCode = $_REQUEST['c'];
$filePath = $dirPath . "/" . $songCode . ".mp3";
$bitrate = 128;
$strContext=stream_context_create(
array(
'http'=>array(
'method'=>'GET',
'header'=>"Accept-language: en\r\n"
)
)
);
header('Content-type: audio/mpeg');
header ("Content-Transfer-Encoding: binary");
header ("Pragma: no-cache");
header ("icy-br: " . $bitrate);
$fpOrigin=fopen($filePath, 'rb', false, $strContext);
while(!feof($fpOrigin)){
$buffer=fread($fpOrigin, 4096);
echo $buffer;
flush();
}
fclose($fpOrigin);
?>
What I'm trying to do is to make an online radio stream that scans a folder, and loops all the .mp3 files in it
An edit here:
I've changed the script to look like this
<?php
set_time_limit(0);
$dirPath = "...";
$bitrate = 128;
$strContext=stream_context_create(
array(
'http'=>array(
'method'=>'GET',
'header'=>"Accept-language: en\r\n"
)
)
);
header('Content-type: audio/mpeg');
header ("Content-Transfer-Encoding: binary");
header ("Pragma: no-cache");
header ("icy-br: " . $bitrate);
$list = scandir($dirPath);
foreach($list as $file)
{
if($file== '.' or $file== '..')
continue; // skip, not a file or a folder
if(is_dir($file))
continue; // skip, not a file
echo $file . "<br>";
// define the file path
$filePath = $dirPath . '/' . $file;
// read the file
$fh = fopen($filePath, "r") or die("Could not open file.");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
echo $buffer;
flush();
}
fclose($fh);
}
}
?>
The code works fine but the problem is that I want the stream to continue even when no one is listening to it, it restarts each time someone tries to listen to it.
The fopen function will return a resource to the opened file or a FALSE boolean value if it fails. Looks like your file is failing to open. Check if the $filePath is correct and that $songCode has a value.
Here is a code to read all files in a folder:
// get a list of all files/folders in a path
$list = scandir($dirPath);
foreach($list as $file)
{
if($file== '.' or $file== '..')
continue; // skip, not a file or a folder
if(is_dir($file))
continue; // skip, not a file
// define the file path
$filePath = $dirPath . '/' . $file;
// read the file
$fh = fopen($filePath, "r") or die("Could not open file.");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
// Do something with the buffer here...
}
fclose($fh);
}
}
Related
I want to download my zip file by a variable ($direccion) that I want to assign to it and when I try to do it, it comes out that the file is corrupted.
$file_name = basename('C:/xampp/htdocs/issv/upload/26908557.zip');
header("Content-Type: application/Zip");
header("Content-Disposition: attachment; filename=26908557.zip");
header("Content-Length: " . filesize('C:/xampp/htdocs/issv/upload/26908557.zip'));
readfile('C:/xampp/htdocs/issv/upload/26908557.zip');
exit;
that's my code and it only works that way, but I want to put the $direccion path to it
$direccion='c:/xampp/htdocs/issv/upload/'.trim($cedula);
this is what my variable $cédula means $cedula=$_POST['cedula'];
There many ways of zip file creation which are;
$zip_file = '(path)/filename.zip';$dir = plugin_dir_path( __FILE__ );
$zip_file = $dir . '/filename.zip';$zip = new ZipArchive();
if ( $zip->open($zip_file, ZipArchive::CREATE) !== TRUE) {
exit("message");
} $zip->addFile('full_path_of_the_file', 'custom_file_name); $download_file = file_get_contents( $file_url );
$zip->addFromString(basename($file_url),$download_file); $zip->close();
Or simply do this:
$url = "http://anysite.com/file.zip";$zip_file = "folder/downloadfile.zip";$zip_resource = fopen($zipFile, "w");$ch_start = curl_init();curl_setopt($ch_start, CURLOPT_URL, $url);curl_setopt($ch_start,CURLOPT_FAILONERROR, true);curl_setopt($ch_start,CURLOPT_HEADER, 0);curl_setopt($ch_start,CURLOPT_FOLLOWLOCATION, true);curl_setopt($ch_start,CURLOPT_AUTOREFERER, true);curl_setopt($ch_start,CURLOPT_BINARYTRANSFER,true);curl_setopt($ch_start,CURLOPT_TIMEOUT, 10);curl_setopt($ch_start,CURLOPT_SSL_VERIFYHOST, 0);curl_setopt($ch_start,CURLOPT_SSL_VERIFYPEER, 0);curl_setopt($ch_start,CURLOPT_FILE,$zip_resource);$page =curl_exec($ch_start);if(!$page){echo "Error :- ".curl_error($ch_start);}curl_close($ch_start);$zip = new ZipArchive;$extractPath = "Download File Path";if($zip->open($zipFile) != "true"){echo "Error :- Unable to open the Zip File";}$zip->extractTo($extractPath);$zip->close();
class FileNotFound extends RuntimeException {}
$downloadUploadedZip = function(string $filename): void {
$directory = 'C:/xampp/htdocs/issv/upload';
if (dirname($filename) !== '.') {
$directory = dirname($filename);
}
$filename = basename($filename);
$filepath = sprintf('%s/%s', $directory, $filename);
if (file_exists($filepath)) {
header("Content-Type: application/zip");
header(sprintf("Content-Disposition: attachment; filename=%s", $filename));
header(sprintf("Content-Length: %d", filesize($filepath)));
readfile($filepath);
exit;
}
throw new FileNotFound(sprintf('File %s not found.', $filepath));
};
$downloadUploadedZip('26908557.zip');
$downloadUploadedZip('C:/xampp/htdocs/issv/upload/26908557.zip');
I'm currently making a controller to download files from the server.
It all happens in the index action:
public function indexAction() {
$schuurName = $this->_getParam('storageID');
$fileName = $this->_getParam('fileName');
$name = explode('.', $fileName)[0];
$path = '..' . DIRECTORY_SEPARATOR . 'schuren' . DIRECTORY_SEPARATOR . $schuurName . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($path)) {
$mimeType = mime_content_type($fileName);
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($path));
header('Content-Disposition: attachment; filename=' . $name . ';');
$resource = fopen($path, 'r');
while (!feof($resource)) {
$chunk = fread($resource, 4096);
echo $chunk;
}
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
else {
echo 'file doesn\'t exist';
}
}
So the downloading works right now, I'm testing it with an image of 725 bytes. The problem is.. The image is corrupted so it couldn't be seen/edited. What am I doing wrong in my code?
Thanks!
You should use binary mode. Use the 'rb' flag.
From the php Manual : If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.
http://www.php.net/manual/en/function.fopen.php
I'm new to SO and new to PHP. I found a script online to zip a directory and I've edited it so that it sends the zip to the browser for download and then deletes the file from the server.
It works fine, however I would like to zip multiple directories instead of just one.
How would I need to alter my script to accomplish this?
$date = date('Y-m-d');
$dirToBackup = "content";
$dest = "backups/"; // make sure this directory exists!
$filename = "backup-$date.zip";
$archive = $dest.$filename;
function folderToZip($folder, &$zipFile, $subfolder = null) {
if ($zipFile == null) {
// no resource given, exit
return false;
}
// we check if $folder has a slash at its end, if not, we append one
$folder .= end(str_split($folder)) == "/" ? "" : "/";
$subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";
// we start by going through all files in $folder
$handle = opendir($folder);
while ($f = readdir($handle)) {
if ($f != "." && $f != "..") {
if (is_file($folder . $f)) {
// if we find a file, store it
// if we have a subfolder, store it there
if ($subfolder != null)
$zipFile->addFile($folder . $f, $subfolder . $f);
else
$zipFile->addFile($folder . $f);
} elseif (is_dir($folder . $f)) {
// if we find a folder, create a folder in the zip
$zipFile->addEmptyDir($f);
// and call the function again
folderToZip($folder . $f, $zipFile, $f);
}
}
}
}
// create the zip
$z = new ZipArchive();
$z->open($archive, ZIPARCHIVE::CREATE);
folderToZip($dirToBackup, $z);
$z->close();
// download the zip file
$file_name = basename($archive);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($archive));
readfile($archive);
// delete the file from the server
unlink($archive);
exit;
Thanks for any help!
Irma
set $dirToBackup to
$dirToBackup = array("restricted","ci");
and then :
foreach($dirToBackup as $d){
folderToZip($d, $z, $d);
}
Thats all.
Regards,
This script successfully generated the pdfs to a folder tmp/....
However the ZIP output to the browser is empty and I don't know what I have done wrong.
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();
// Zip will open and overwrite the file, rather than try to read it.
$zip->open($file, ZipArchive::OVERWRITE);
foreach( explode( ',', $_POST["ids"]) as $Client_ID)
{
$sql_qry="select *
from ca_client_statement
where client_id='".$Client_ID."' and trading_period_month like '".$TP_Month."'";
$sql_err_no=sql_select($sql_qry,$sql_res,$sql_row_count,$sql_err,$sql_uerr);
//echo $sql_qry;
//echo '<br/>';
$row = mysql_fetch_assoc($sql_res);
$file_content = $row['pdf_statement'];
$file_name = 'tmp/'.$Client_ID.'statement.pdf';
$pdf=file_put_contents($file_name, $file_content);
$zip->addFile($pdf);
}
$zip->close();
// Stream the file to the client
header("Content-Type: application/zip");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"a_zip_file.zip\"");
readfile($file);
unlink($file);
file_put_contents() returns the number of bytes written, not the file name. Try changing the line right after it to this:
$zip->addFile($file_name);
Part of our web app has a little Ajax method that will load a page in an iFrame or allow you to download it.
We store a bunch of search results from search engines and we have script opens the file containing our info and the search html. We strip out the stuff we don't need from the top (our info) and then we serve that up either by echo'ing the $html variable or putting it in a temporary file and dishing it off to download.
The problem: I load the page in the iFrame and it's loaded in UTF-8 because everything else is. If I download the file manually it is fine and FF tells me the endoding is x-gbk.
I've tried using mb_convert_encoding to no avail. We are using PHP4 on this server.
Thoughts?
EDIT: Code that drives this
f(!isset($_GET['file']) || $_GET['file'] == '')
{
header("location:index.php");
}
$download = false;
if(!isset($_GET['view']) || $_GET['view'] != 'true')
{
$download = true;
}
$file = LOG_PATH . $_GET['file'];
$fileName = end(explode("/", $file));
$fh = fopen($file, "rb");
if(!$fh)
{
echo "There was an error in processing this file. Please retry.";
return;
}
// Open HTML file, rip out garbage at top, inject "http://google.com" before all "images/"
$html = fread($fh, filesize($file));
fclose($fh);
// Need to trim off our headers
$htmlArr = explode("<!", $html, 2);
$htmlArr[1] = "<!" . $htmlArr[1];
if(strstr($file, "google"))
{
$html = str_replace('src="/images/', 'src="http://google.com/images/', $htmlArr[1]);
$html = str_replace('href="/', 'href="http://google.com/', $html);
}
else if(strstr($file, "/msn/"))
{
$html = str_replace('src="/images/', 'src="http://bing.com/images/', $htmlArr[1]);
$html = str_replace('href="/', 'href="http://www.bing.com/', $html);
}
else
{
$html = $htmlArr[1];
}
if(strstr($file, "baidu"))
{
$html = mb_convert_encoding($html, 'utf-8'); // Does not work
}
if($download)
{
// Write to temporary file
$fh = fopen("/tmp/" . $fileName, 'w+');
fwrite($fh, $html);
fclose($fh);
$fh = fopen("/tmp/" . $fileName, "rb");
header('Content-type: application/force-download;');
header("Content-Type: text/html;");
header('Content-Disposition: attachment; filename="' . $fileName . '"');
fpassthru($fh);
fclose($fh);
unlink("/tmp/" . $fileName);
}
else // AJAX Call
{
echo $html;
}
You may want to try iconv() instead of mb_convert_encoding()--it has support for a much broader set of encodings.