function deliverFile($file, $contentEncoding) { if (file_exists($file) && ($filehandle = fopen($file, 'r'))) { $fileCTime = filectime($file); // We don't need to deliver the file, if it hasn't been modified // since the last time it has been requested. if (array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) { $sinceTime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']); if ($sinceTime !== false && $sinceTime >= $fileCTime) { # header('Debug-Requested-File: ' . $file); header('Debug-Last-Modified: ' . date('r', $fileCTime)); header('Debug-If-Modified-Since: ' . date('r', $sinceTime)); header('HTTP/1.0 304 Not Modified'); exit; } } header('Last-Modified: ' . date('r', $fileCTime)); # header('Debug-Requested-File: ' . $file); header('Content-Type: application/x-java-archive'); header('Content-Length :' . filesize($file)); if ($contentEncoding != null) { header('Content-Encoding: ' . $contentEncoding); } fpassthru($filehandle); fclose($filehandle); } else { header('HTTP/1.0 404 Not Found'); } exit; }
public function index() { $this->auto_render = FALSE; if ($this->service == "" && $this->host == "") { url::redirect("graph", 302); } $this->data->readXML($this->host, $this->service); if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE) { header('Content-Type: application/xml'); print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"; print "<NAGIOS>\n"; print "<ERROR>not authorized</ERROR>\n"; print "</NAGIOS>\n"; exit; } else { $xmlfile = $this->config->conf['rrdbase'] . $this->host . "/" . $this->service . ".xml"; if (is_readable($xmlfile)) { $fh = fopen($xmlfile, 'r'); header('Content-Type: application/xml'); fpassthru($fh); fclose($fh); exit; } else { header('Content-Type: application/xml'); print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"; print "<NAGIOS>\n"; print "<ERROR>file not found</ERROR>\n"; print "</NAGIOS>\n"; } } }
function graph_error($string) { global $vars, $config, $debug, $graphfile; $vars['bg'] = 'FFBBBB'; include 'includes/graphs/common.inc.php'; $rrd_options .= ' HRULE:0#555555'; $rrd_options .= " --title='" . $string . "'"; rrdtool_graph($graphfile, $rrd_options); if ($height > '99') { shell_exec($rrd_cmd); d_echo('<pre>' . $rrd_cmd . '</pre>'); if (is_file($graphfile) && !$debug) { header('Content-type: image/png'); $fd = fopen($graphfile, 'r'); fpassthru($fd); fclose($fd); unlink($graphfile); exit; } } else { if (!$debug) { header('Content-type: image/png'); } $im = imagecreate($width, $height); $px = (imagesx($im) - 7.5 * strlen($string)) / 2; imagestring($im, 3, $px, $height / 2 - 8, $string, imagecolorallocate($im, 128, 0, 0)); imagepng($im); imagedestroy($im); exit; } }
/** * Dump the contents of the file using fpassthru(). * * @return void * @throws Exception if no file or contents. */ function dump() { if (!$this->data) { // hmmm .. must be a file that needs to read in if ($this->inFile) { $fp = @fopen($this->inFile, "rb"); if (!$fp) { throw new Exception('Unable to open file: ' . $this->inFile); } fpassthru($fp); @fclose($fp); } else { throw new Exception('No data to dump'); } } else { $realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']); $docuroot = explode('/', $realdocuroot); array_pop($docuroot); $pathhome = implode('/', $docuroot) . '/'; array_pop($docuroot); $pathTrunk = implode('/', $docuroot) . '/'; require_once $pathTrunk . 'gulliver/system/class.inputfilter.php'; $filter = new InputFilter(); $data = $filter->xssFilterHard($this->data); echo $data; } }
private function download($dir, $file) { chdir($dir); // if the filename is in the array if (preg_match("/\\.zip\$/", $file)) { // and it exists if (file_exists($file)) { // and is readable if (is_readable($file)) { // get its size $size = filesize($file); // open it for reading if ($fp = @fopen("{$file}", 'r')) { // send the headers header('Content-type: application/zip'); header("Content-Length: {$size}"); header("Content-Disposition: attachment; filename=\"{$file}\""); // send the file content fpassthru($fp); // close the file fclose($fp); // and quit exit; } } } } }
public function ShowAction($id = '') { global $CONFIG; $id += 0; if (!$id) { throw new ApplicationException("404 File Not Found"); } $size = reqs('size'); $is_preview = reqi('preview'); if ($is_preview) { $item = $this->model->one($id); if ($item['is_image']) { $this->model->transmit_file($id, $size, 'inline'); } else { #if it's not an image and requested preview - return std image $filepath = $CONFIG['site_root'] . '/img/att_file.png'; # TODO move to web.config or to model? header('Content-type: ' . UploadUtils::get_mime4ext($item['ext'])); $fp = fopen($filepath, 'rb'); fpassthru($fp); } } else { $this->model->transmit_file($id, $size, 'inline'); } }
/** * Output json * * @param array data to output * @return void * @author Dmitry (dio) Levashov **/ protected function output(array $data) { $header = isset($data['header']) ? $data['header'] : $this->header; unset($data['header']); $headers = array(); if ($header) { foreach ((array) $header as $headerString) { if (strpos($headerString, ':') !== false) { list($key, $value) = explode(':', $headerString, 2); $headers[$key] = $value; } } } if (isset($data['pointer'])) { $this->response = new StreamedResponse(function () use($data) { if (stream_get_meta_data($data['pointer'])['seekable']) { rewind($data['pointer']); } fpassthru($data['pointer']); if (!empty($data['volume'])) { $data['volume']->close($data['pointer'], $data['info']['hash']); } }, 200, $headers); } else { if (!empty($data['raw']) && !empty($data['error'])) { $this->response = new JsonResponse($data['error'], 500); } else { $this->response = new JsonResponse($data, 200, $headers); } } }
/** * Output a file to the browser * * @param string $file The file to output * * @since 1.0.0 */ public function output($file) { @error_reporting(E_ERROR); $name = basename($file); $type = $this->getContentType($name); $size = @filesize($file); $mod = date('r', filemtime($file)); while (@ob_end_clean()) { } // required for IE, otherwise Content-disposition is ignored if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } // set header header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Expires: 0"); header("Content-Transfer-Encoding: binary"); header('Content-Type: ' . $type); header('Content-Disposition: attachment;' . ' filename="' . $name . '";' . ' modification-date="' . $mod . '";' . ' size=' . $size . ';'); header("Content-Length: " . $size); // set_time_limit doesn't work in safe mode if (!ini_get('safe_mode')) { @set_time_limit(0); } // output file $handle = fopen($file, 'rb'); fpassthru($handle); fclose($handle); }
function streamContent($file, $type) { if ($type == "image") { $file_bits = preg_split('/\\./', $file); if (count($file_bits) == 2) { if ($file_bits[1] == "png") { $content = "image/png"; } else { if ($file_bits[1] == "gif") { $content = "image/gif"; } } } } if (!isset($content)) { errorOut("Invalid Static Content", 404, array("Type specified - {$type}", "File specified - {$file}")); } $real_file = BASEPATH . "static/{$type}/" . $file; if (is_file($real_file)) { header("Content-Length:" . filesize($real_file)); header("Content-Type: " . $content); $fh = fopen($real_file, "r"); fpassthru($fh); fclose($fh); } else { errorOut("Invalid Static Content", 404, array("Filename - {$real_file}")); } exit; }
public function execute(InputInterface $input, OutputInterface $output) { $solrRoot = $this->getContainer()->getParameter('room13.solr.config.solr_root'); $schemaRoot = $this->getContainer()->getParameter('room13.solr.config.schema_root'); $p = popen("cd {$solrRoot} && java -Dsolr.solr.home={$schemaRoot} -jar start.jar", "r"); fpassthru($p); }
protected function generate_csv() { extract($this->args); $csv = fopen('php://memory', 'w'); $col_names = array(); $count = 0; // Generate CSV lines foreach ($data as $line) { if ($column_names && $count < 1) { foreach ($line as $col_name => $col_value) { array_push($col_names, $col_name); } fputcsv($csv, $col_names, $delimiter); } fputcsv($csv, $line, $delimiter); $count++; } // Rewind the CSV file fseek($csv, 0); // Set CSV file headers header('Content-Type: application/csv'); header('Content-Disposition: attachement; filename="' . $filename . '.csv"'); header('Content-Cache: no-cache, must-revalidate'); header('Pragma: no-cache'); // Send the generated CSV to the browser fpassthru($csv); exit; }
function handle_file_cache($file_cache_r, $isThumbnail = FALSE) { if ($file_cache_r !== FALSE) { if ($file_cache_r['cache_type'] == 'ITEM') { if ($isThumbnail) { $file = file_cache_open_thumbnail_file($file_cache_r); } // fallback on big image if (!$file) { if ($file_cache_r['upload_file_ind'] != 'Y') { $file = file_cache_open_file($file_cache_r); } } } else { $file = file_cache_open_file($file_cache_r); } if ($file) { header("Content-disposition: inline; filename=" . $file_cache_r['cache_file']); header("Content-type: " . $file_cache_r['content_type']); fpassthru($file); fclose($file); } else { // final fallback output_cache_file($file_cache_r['url']); } return TRUE; } else { return FALSE; } }
function testRequestToOutputFile() { $client = new ProxyClient(); $client->URL = df_absolute_url('tests/test_ProxyClient/test1.html'); $outputFile = tempnam(sys_get_temp_dir(), 'test_ProxyClient'); $client->outputFile = $outputFile; $client->process(); $this->assertEquals(null, $client->content, 'Content should be written to output file, not saved to variable.'); $expected = file_get_contents('tests/test_ProxyClient/test1.html'); $doc = new DOMDocument(); @$doc->loadHtml($expected); $expected = $doc->saveHtml(); $actual = file_get_contents($outputFile); $actual = ''; $fh = fopen($outputFile, 'r'); while (!feof($fh) and trim($line = fgets($fh, 1024))) { // We skip the headers } ob_start(); fpassthru($fh); fclose($fh); $actual = ob_get_contents(); ob_end_clean(); unset($doc); $doc = new DOMDocument(); @$doc->loadHtml($actual); $actual = $doc->saveHtml(); unset($doc); $this->assertEquals($expected, $actual); }
function makethumbnail($src_file, $newSize, $method) { global $CONFIG; $content_type = array(IMAGETYPE_GIF => 'gif', IMAGETYPE_JPEG => 'jpeg', IMAGETYPE_PNG => 'png'); // Checks that file exists and is readable if (!filesize($src_file) || !is_readable($src_file)) { header("Content-type: image/gif"); fpassthru(fopen(READ_ERROR_ICON, 'rb')); exit; } // find the image size, no size => unknow type $imginfo = getimagesize($src_file); if ($imginfo == null) { header("Content-type: image/gif"); fpassthru(fopen(UNKNOW_ICON, 'rb')); exit; } // GD can't handle gif images if ($imginfo[2] == IMAGETYPE_GIF && ($method == 'gd1' || $method == 'gd2') && !function_exists('imagecreatefromgif')) { header("Content-type: image/gif"); fpassthru(fopen(GIF_ICON, 'rb')); exit; } // height/width $ratio = max(max($imginfo[0], $imginfo[1]) / $newSize, 1.0); $dest_info[0] = intval($imginfo[0] / $ratio); $dest_info[1] = intval($imginfo[1] / $ratio); $dest_info['quality'] = intval($CONFIG['jpeg_qual']); require_once 'includes/imaging/imaging.inc'; if (!Graphic::show($src_file, $dest_info)) { return false; } }
public function send() { $fp = fopen($this->content, 'rb'); header("Content-Type:" . $this->contentType, true, $this->status); header("Content-Length: " . filesize($this->content)); fpassthru($fp); }
function get_VM($user, $mid, &$errors) { global $config, $lang_str; if (!$this->connect_to_db($errors)) { return false; } $q = "select subject, file from " . $config->data_sql->table_voice_silo . " where mid=" . $mid . " and " . $this->get_indexing_sql_where_phrase_uri($user); $res = $this->db->query($q); if (DB::isError($res)) { log_errors($res, $errors); return false; } if (!$res->numRows()) { $errors[] = $lang_str['err_voice_msg_not_found']; return false; } $row = $res->fetchRow(DB_FETCHMODE_OBJECT); $res->free(); @($fp = fopen($config->voice_silo_dir . $row->file, 'r')); if (!$fp) { $errors[] = $lang_str['err_can_not_open_message']; return false; } Header("Content-Disposition: attachment;filename=" . RawURLEncode(($row->subject ? $row->subject : "received message") . ".wav")); Header("Content-type: audio/wav"); @fpassthru($fp); @fclose($fp); return true; }
protected function output(array $data) { $header = isset($data['header']) ? $data['header'] : $this->header; unset($data['header']); if ($header) { if (is_array($header)) { foreach ($header as $h) { header($h); } } else { header($header); } } if (isset($data['pointer'])) { rewind($data['pointer']); fpassthru($data['pointer']); if (!empty($data['volume'])) { $data['volume']->close($data['pointer'], $data['info']['hash']); } return; } else { if (!empty($data['raw']) && !empty($data['error'])) { return $data['error']; } else { return $data; } } }
/** * Function exports the report in a Excel sheet * @param Vtiger_Request $request */ function GetXLS(Vtiger_Request $request) { $recordId = $request->get('record'); error_reporting(0); //error_reporting(63);ini_set("display_errors",1); if (ITS4YouReports::isStoredITS4YouReport() === true) { $ogReport = ITS4YouReports::getStoredITS4YouReport(); } else { $ogReport = new ITS4YouReports(); } $generateObj = new GenerateObj($ogReport); $report_data = $generateObj->GenerateReport($recordId, "XLS"); //ITS4YouReports::sshow($report_data); //exit; $rootDirectory = vglobal('root_directory'); $tmpDir = vglobal('tmp_dir'); $tempFileName = tempnam($rootDirectory . $tmpDir, 'xls'); $fileName = $ogReport->reportname . '.xls'; $default_charset = vglobal("default_charset"); $fileName = html_entity_decode($fileName, ENT_QUOTES, $default_charset); $generateObj->writeReportToExcelFile($tempFileName, $report_data); //ITS4YouReports::sshow($report_data); //exit; if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) { header('Pragma: public'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); } header('Content-Type: application/x-msexcel'); header('Content-Length: ' . @filesize($tempFileName)); header('Content-disposition: attachment; filename="' . $fileName . '"'); $fp = fopen($tempFileName, 'rb'); fpassthru($fp); //unlink($tempFileName); //echo "<pre>";print_r($report_data);echo "</pre>"; }
public function acaodownload() { $trb_cod = Sistema_Variavel::get('trb_cod'); $file = UPLOAD_DIR . $trb_cod . ".PDF"; if (file_exists($file)) { $arq = $file; $ext = ".pdf"; } $file = UPLOAD_DIR . $trb_cod . ".DOC"; if (file_exists($file)) { $arq = $file; $ext = ".doc"; } if ($arq != "") { header("Content-Type: application/save"); header("Content-Length:" . filesize($arq)); header('Content-Disposition: attachment; filename="' . Sistema_Variavel::get('trb_cod') . $ext); header("Content-Transfer-Encoding: binary"); header('Expires: 0'); header('Pragma: no-cache'); // nesse momento ele le o arquivo e envia $fp = fopen("{$arq}", "r"); fpassthru($fp); fclose($fp); } else { $msg = Sistema_Mensagem::instanciar(); $msg->setErro("Não foi submetido arquivo para este trabalho"); } }
public function getAction() { $this->getHelper('layout')->disableLayout(); $this->getHelper('viewRenderer')->setNoRender(true); $media = $this->getInvokeArg('bootstrap')->getOption('media'); if (!(null != ($fileRow = $this->_getParam('file')) && $fileRow instanceof Media_Model_DbTable_Row_File)) { $mediaAdapter = Media_Model_Adapter::factory($media['adapter'], $media['params']); $id = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('id'))); $key = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('key'))); $fileRow = $this->_helper->getObjectOr404('media/file', array('id' => $id)); $this->forward404If(!$mediaAdapter->isValidKey($fileRow, $key, '', $media['key_lifetime'])); } $source = $media['uploads_dir'] . DIRECTORY_SEPARATOR . $fileRow->local_filename; if (null == $this->_getParam('noAdapter', null)) { $isSaved = $mediaAdapter->save($source, $fileRow->getRelativePath(null, false, true), true); if ($isSaved) { Centurion_Db::getSingleton('media/duplicate')->insert(array('file_id' => $fileRow->id, 'adapter' => $media['adapter'], 'params' => serialize($media['params']), 'dest' => $fileRow->getRelativePath(null, false, true))); return $this->getHelper('redirector')->gotoUrlAndExit($fileRow->getStaticUrl()); } } $offset = 24 * 60 * 60 * 365; $this->getResponse()->setHeader('Content-type', $fileRow->mime)->setHeader('Content-Length', filesize($source))->setHeader('Content-Disposition', sprintf('inline; filename="%s";', $fileRow->filename))->setHeader('Cache-Control', sprintf('max-age=%d, public', $offset))->setHeader('Expires', sprintf('%s GMT', gmdate('D, d M Y H:i:s', time() + $offset)))->sendHeaders(); while (@ob_end_flush()) { } $fp = fopen($source, 'rb'); fpassthru($fp); fclose($fp); $this->getResponse()->clearHeaders(); }
public function Map() { $this->Route('GET', '', function () { if (AuthRepository::Autherize()) { $mediaRepository = new MediaRepository(); $this->Send($mediaRepository->LoadAll([["UploadUserId" => "user"]])); } }); $this->Route('GET', '/[i:id]', function ($id) { $mediaRepository = new MediaRepository(); $media = $mediaRepository->LoadWhere("Id = {$id}")[0]; $path = "images/gallery/full/" . $media["Path"]; $imageRepository = new ImageRepository(); $imageRepository->CacheImage($path); header("Content-Type: image/" . pathinfo($path)["extension"]); header("Content-Length: " . filesize($path)); $fp = fopen($path, 'rb'); fpassthru($fp); exit; }); $this->Route('GET', '/[i:id]/thumbnail', function ($id) { $mediaRepository = new MediaRepository(); $media = $mediaRepository->LoadWhere("Id = {$id}")[0]; $path = "images/gallery/thumbnail/" . $media["Path"]; $imageRepository = new ImageRepository(); $imageRepository->CacheImage($path); header("Content-Type: image/" . pathinfo($path)["extension"]); header("Content-Length: " . filesize($path)); $fp = fopen($path, 'rb'); fpassthru($fp); exit; }); }
function download_file($db_object,$common,$user_id,$uid,$default,$err) { if($uid!="") { $user_id =$uid; } $path = $common->path; $file = $path."performance/status_report/performance_status_report_$user_id.txt"; if(file_exists($file)) { $len = filesize($file); $filename = "performance_status_report_$user_id.txt"; header("content-type: application/stream"); header("content-length: $len"); header("content-disposition: attachment; filename=$filename"); $fp=fopen($file,"r"); fpassthru($fp); exit; } else { $str=<<<EOD <script> alert( '$err[cEmptyrecords]' ); window.location=document.referrer; </script> EOD; echo $str; } }
public function export(\Contao\DC_Table $dc) { $database = \Contao\Database::getInstance(); $stage_id = $database->query("SELECT s.id FROM tl_beachcup_stage AS s WHERE s.start_date >= UNIX_TIMESTAMP() ORDER BY s.start_date ASC LIMIT 1")->fetchAssoc()["id"]; $data = $database->query("select tl_beachcup_registration.id as ANMELDUNG_ID, tl_beachcup_tournament.name_de AS TURNIER, DATE_FORMAT(from_unixtime(tl_beachcup_registration.tstamp), '%d.%m.%Y') as DATUM_ANMELDUNG,\n p1.surname as NACHNAME_1, p1.name as VORNAME_1, p1.tax_number as STEUER_NR_1, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p1.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_1, p1.birth_place as GEB_ORT_1, p1.gender as GESCHLECHT_1, p1.address as ADRESSE_1, p1.zip_code as PLZ_1, p1.city as ORT_1, p1.country as LAND_1, p1.email as EMAIL_1, p1.phone_number as TEL_1, p1.shirt_size as SHIRT_1, p1.has_shirt as SHIRT_ERHALTEN_1, p1.is_fipav as FIPAV_1, p1level.description_de as SPIELER_LEVEL_1, p1.has_medical_certificate as AERZTL_ZEUGNIS_1, p1.is_confirmed as EIGENERKLAERUNG_1,\n p2.surname as NACHNAME_2, p2.name as VORNAME_2, p2.tax_number as STEUER_NR_2, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p2.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_2, p2.birth_place as GEB_ORT_2, p2.gender as GESCHLECHT_2, p2.address as ADRESSE_2, p2.zip_code as PLZ_2, p2.city as ORT_2, p2.country as LAND_2, p2.email as EMAIL_2, p2.phone_number as TEL_2, p2.shirt_size as SHIRT_2, p2.has_shirt as SHIRT_ERHALTEN_2, p2.is_fipav as FIPAV_2, p2level.description_de as SPIELER_LEVEL_2, p2.has_medical_certificate as AERZTL_ZEUGNIS_2, p2.is_confirmed as EIGENERKLAERUNG_2,\n tl_beachcup_registration_state.code as STATUS_ANMELDUNG\n from tl_beachcup_registration\n join tl_beachcup_team on tl_beachcup_team.id = tl_beachcup_registration.team_id\n join tl_beachcup_player p1 on p1.id = tl_beachcup_team.player_1\n join tl_beachcup_player_level p1level on p1level.id = p1.player_level\n join tl_beachcup_player p2 on p2.id = tl_beachcup_team.player_2\n join tl_beachcup_player_level p2level on p2level.id = p2.player_level\n join tl_beachcup_tournament on tl_beachcup_tournament.id = tl_beachcup_registration.tournament_id\n join tl_beachcup_registration_state on tl_beachcup_registration_state.id = tl_beachcup_registration.state_id\n join tl_beachcup_stage on tl_beachcup_stage.id = tl_beachcup_tournament.stage_id\n where tl_beachcup_stage.id = {$stage_id} and tl_beachcup_registration_state.code != 'REJECTED'\n order by tl_beachcup_tournament.date, tl_beachcup_tournament.name_de, tl_beachcup_registration.tstamp;")->fetchAllAssoc(); if (count($data) > 0) { $headers = array(); foreach ($data[0] as $key => $value) { $headers[] = $key; } $file = fopen("php://memory", "w"); fputcsv($file, $headers, ";"); foreach ($data as $record) { fputcsv($file, $record, ";"); } fseek($file, 0); header('Content-Encoding: iso-8859-1'); header('Content-Type: application/csv; charset=iso-8859-1'); header('Content-Disposition: attachement; filename="Anmeldungen.csv";'); echo ""; fpassthru($file); exit; } \Contao\Controller::redirect('contao/main.php?do=registration'); }
private function execute($args, $pipe_stdout, $cwd_override = null) { $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $cwd = $cwd_override != NULL ? $cwd_override : $this->cwd; $cmd = join(' ', array_map('escapeshellarg', $args)); $proc = proc_open($cmd, $descriptorspec, $pipes, $cwd, array('LANG' => 'en_US.UTF-8')); if (!is_resource($proc)) { $errors = error_get_last(); $this->log->error("{$cmd} failed: {$errors['type']} {$errors['message']}"); throw new Exception($errors['message']); } fclose($pipes[0]); if ($pipe_stdout) { $output = stream_get_contents($pipes[1]); } else { fpassthru($pipes[1]); $output = null; } $err = stream_get_contents($pipes[2]); $retval = proc_close($proc); if ($retval != 0) { $this->log->error("{$cmd} failed: {$retval} {$output} {$err}"); throw new Exception($err); } return $output; }
/** * Lets the browser render an image file * @param String $path The path to the image file * @param String $timestamp Cache timestamp - if not provided, this will have to be found out (at the cost of disk access) * @param String $mime The image mimetype - if not provided, this will have to be found out (at the cost of disk access) * @return Void */ public function show($path, $timestamp = null, $mime = null) { $headers = function_exists('apache_request_headers') ? apache_request_headers() : array(); if (is_null($timestamp)) { $timestamp = $this->_readTimestampFromFile($path); } if (is_null($mime)) { $mime = $this->_readMimeTypeFromFile($path); } header("Content-Type: {$mime}"); header("Cache-Control: maxage=" . 24 * 60 * 60 . ', must-revalidate'); //In seconds header("Pragma: public"); // Checking if the client is validating his cache and if it is current. if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since']) == $timestamp) { // Client's cache IS current, so we just respond '304 Not Modified'. header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $timestamp) . ' GMT', true, 304); } else { // Image not cached or cache outdated, we respond '200 OK' and output the image. header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $timestamp) . ' GMT', true, 200); header('Content-Length: ' . filesize($path)); $resource = fopen($path, 'rb'); rewind($resource); fpassthru($resource); fclose($resource); } }
/** * Handles the GetAttachment command * * @param int $commandCode * * @access public * @return boolean */ public function Handle($commandCode) { $attname = Request::GetGETAttachmentName(); if (!$attname) { return false; } try { $attachment = self::$backend->GetAttachmentData($attname); $stream = $attachment->data; ZLog::Write(LOGLEVEL_DEBUG, sprintf("HandleGetAttachment(): attachment stream from backend: %s", $stream)); // need to check for a resource here, as eg. feof('Error') === false and causing infinit loop in while! if (!is_resource($stream)) { throw new StatusException(sprintf("HandleGetAttachment(): No stream resource returned by backend for attachment: %s", $attname), SYNC_ITEMOPERATIONSSTATUS_INVALIDATT); } header("Content-Type: application/octet-stream"); self::$topCollector->AnnounceInformation("Starting attachment streaming", true); $l = fpassthru($stream); fclose($stream); if ($l === false) { throw new FatalException("HandleGetAttachment(): fpassthru === false !!!"); } self::$topCollector->AnnounceInformation(sprintf("Streamed %d KB attachment", round($l / 1024)), true); ZLog::Write(LOGLEVEL_DEBUG, sprintf("HandleGetAttachment(): attachment with %d KB sent to mobile", round($l / 1024))); } catch (StatusException $s) { // StatusException already logged so we just need to pass it upwards to send a HTTP error throw new HTTPReturnCodeException($s->getMessage(), HTTP_CODE_500, null, LOGLEVEL_DEBUG); } return true; }
public function createICal($nid) { $node = \Drupal\node\Entity\Node::load($nid); $eventdate = $node->get('field_event_date')->getValue(); $title = $node->get('title')->getValue(); $title = $title[0]['value']; $startdate = $eventdate[0]['value']; $enddate = $eventdate[1]['value']; if (empty($enddate)) { $enddate = $startdate; } $startdate = self::convertDateToICal($startdate); $enddate = self::convertDateToICal($enddate); $filecontents = self::buildICSFile($startdate, $enddate, $title, $nid); // open raw memory as file so no temp files needed, you might run out of memory though $file = fopen('php://memory', 'w'); fwrite($file, $filecontents); // reset the file pointer to the start of the file rewind($file); // tell the browser it's going to be a calendar file header('Content-Type: text/calendar; charset=utf-8'); // tell the browser we want to save it instead of displaying it header('Content-Disposition: attachment; filename="calendar.ics";'); header('Cache-Control: store, no-cache, must-revalidate, post-check=0, pre-check=0'); // make php send the generated file to the browser fpassthru($file); exit; /* return array( '#type' => 'markup', '#markup' => $this->t('Hello, ical World!<pre>' . $filecontents . "</pre>"), ); */ }
function servicio__descargar() { $encontre = false; $seleccionado = toba::memoria()->get_parametro('fila'); $obj_data = null; $index = 0; while (!$encontre && $index < count($this->s__datos)) { if ($this->s__datos[$index]['x_dbr_clave'] == $seleccionado) { $obj_data = $this->s__datos[$index]['adjunto']; $encontre = true; } $index++; } if (!is_null($obj_data)) { $archivo = toba::proyecto()->get_www_temp($obj_data['name']); header("Content-type:{$obj_data['type']}"); header("Content-Disposition: attachment; filename=\"{$obj_data['name']}\""); $handler = fopen($archivo['path'], 'r'); if ($handler !== false) { fpassthru($handler); } } else { echo 'No funciono como debia, REVISAME!'; } }
public function print_proxy($site_key, $file_id) { // This function retrieves the full-sized image for fotomoto. // As this function by-passes normal Gallery security, a private // site-key is used to try and prevent people other then fotomoto // from finding the URL. // If the site key doesn't match, display a 404 error. if ($site_key != module::get_var("fotomotorw", "fotomoto_private_key")) { throw new Kohana_404_Exception(); } // Load the photo from the provided id. If the id# is invalid, display a 404 error. $item = ORM::factory("item", $file_id); if (!$item->loaded()) { throw new Kohana_404_Exception(); } // If the image file doesn't exist for some reason, display a 404 error. if (!file_exists($item->file_path())) { throw new Kohana_404_Exception(); } // Display the image. header("Content-Type: {$item->mime_type}"); Kohana::close_buffers(false); $fd = fopen($item->file_path(), "rb"); fpassthru($fd); fclose($fd); }
function download($file, $name = '') { $fileName = $name ? $name : pathinfo($file, PATHINFO_FILENAME); $filePath = realpath($file); $fp = fopen($filePath, 'rb'); if (!$filePath || !$fp) { header('HTTP/1.1 404 Not Found'); echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->"; exit; } $fileName = $fileName . '.' . pathinfo($filePath, PATHINFO_EXTENSION); $encoded_filename = urlencode($fileName); $encoded_filename = str_replace("+", "%20", $encoded_filename); header('HTTP/1.1 200 OK'); header("Pragma: public"); header("Expires: 0"); header("Content-type: application/octet-stream"); header("Content-Length: " . filesize($filePath)); header("Accept-Ranges: bytes"); header("Accept-Length: " . filesize($filePath)); $ua = $_SERVER["HTTP_USER_AGENT"]; if (preg_match("/MSIE/", $ua)) { header('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); } else { if (preg_match("/Firefox/", $ua)) { header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"'); } else { header('Content-Disposition: attachment; filename="' . $fileName . '"'); } } // ob_end_clean(); <--有些情况可能需要调用此函数 // 输出文件内容 fpassthru($fp); exit; }