/** * コンストラクタ * 副作用が大量にあるので注意 */ public function __construct(ClientInterface $client, $filename = 'stamp.json', $span = 0, $mark_limit = 10000, $back_limit = 3600) { // ヘッダの送出 if (!headers_sent()) { header('Content-Type: text/html; charset=UTF-8'); } // エラー表示の設定 error_reporting(-1); ini_set('log_errors', PHP_SAPI === 'cli'); ini_set('display_errors', PHP_SAPI !== 'cli'); // 重複起動防止 $file = new \SplFileObject($filename, 'a+b'); if (!$file->flock(LOCK_EX | LOCK_NB)) { throw new \RuntimeException('Failed to lock file.'); } // JSONとして保存してあるデータを取得 clearstatcache(); $json = $file->getSize() > 0 ? json_decode($file->fread($file->getSize()), true) : []; // JSONに前回実行時刻が保存されていた時 if (isset($json['prev'])) { // 十分に時間が空いたかどうかをチェック if (!static::expired($json['prev'], $span)) { throw new \RuntimeException('Execution span is not enough.'); } } // JSONにマーク済みステータス一覧が記録されていたとき復元する if (isset($json['marked'])) { $this->marked = array_map('filter_var', (array) $json['marked']); } $this->client = $client; $this->file = $file; $this->prev = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('r'); $this->mark_limit = $mark_limit; $this->back_limit = $back_limit; }
/** * {@inheritdoc} */ public function write(\SplFileObject $file, $text, $newLineAtEnd = false) { $originalSeek = $file->ftell(); // Refresh file size clearstatcache($file->getFilename()); if ($file->getSize() - $file->ftell() > 0) { $contentAfter = $file->fread($file->getSize() - $file->ftell()); } else { $contentAfter = ''; } $file->fseek($originalSeek); $file->fwrite($text . ($newLineAtEnd ? PHP_EOL : '')); $file->fwrite($contentAfter); return $file; }
private function readComplexRSS() { $filename = $this->createComplexRSS(); $file = new \SplFileObject($filename, "r"); $contentToTest = $file->fread($file->getSize()); $filename = 'tests/RSS/ComplexRSS.rss'; $file = new \SplFileObject($filename, "r"); $content = $file->fread($file->getSize()); return array($contentToTest, $content); }
public function finalizeFile(\SplFileObject $fileObject) { if ($this->headers !== null) { // Create tmp file with header $fd = fopen('php://temp', 'w+b'); fputcsv($fd, $this->headers); // Copy file content into tmp file $fileObject->rewind(); fwrite($fd, $fileObject->fread($fileObject->getSize())); // Overwrite file content with tmp content rewind($fd); $fileObject->rewind(); $fileObject->fwrite(stream_get_contents($fd)); clearstatcache(true, $fileObject->getPathname()); fclose($fd); } // Remove last line feed $fileObject->ftruncate($fileObject->getSize() - 1); }
/** * {@inheritdoc} */ public function countLines(\SplFileObject $file) { // Refresh file size clearstatcache($file->getFilename()); $previous = $file->key(); $file->seek($file->getSize()); $count = $file->key(); $file->seek($previous); return $count; }
/** * @Route("/download/{filename}/{file}", name="app_download") * @Route("/load/{filename}/{file}", name="app_load") * @ParamConverter("file", converter="file_converter") * @Method("GET") * @param string $filename * @param \SplFileObject $file * @return Response */ public function loadAction($filename, \SplFileObject $file) { $response = new Response($file->fpassthru()); $response->headers->set('Content-Type', 'octet/stream'); $response->headers->set('Content-disposition', 'attachment; filename="' . $filename . '.' . $file->getExtension() . '";"'); $response->headers->set('Content-Length', $file->getSize()); $response->headers->set('Cache-Control', 'max-age=31536000, public'); // 1 year $response->sendHeaders(); return $response->send(); }
/** * Adds the coverage contained in $coverageFile and deletes the file afterwards * @param string $coverageFile Code coverage file * @throws \RuntimeException When coverage file is empty */ public function addCoverageFromFile($coverageFile) { if ($coverageFile === null || !file_exists($coverageFile)) { return; } $file = new \SplFileObject($coverageFile); if (0 === $file->getSize()) { throw new \RuntimeException("Coverage file {$file->getRealPath()} is empty. This means a PHPUnit process has crashed."); } $this->addCoverage($this->getCoverageObject($file)); unlink($file->getRealPath()); }
/** * Read all classes from path * * @return array $classes */ protected function readClasses() { $classes = array(); $directory = new RecursiveDirectoryIterator($this->pathTop, RecursiveDirectoryIterator::SKIP_DOTS); $fileIterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::LEAVES_ONLY); foreach ($fileIterator as $file) { $fileClass = new SplFileObject($file->getPathname()); $fileExtension = new SplFileInfo($file->getPathname()); if ($fileExtension->getExtension() == $this->fileExt) { $classes[] = $fileClass->fread($fileClass->getSize()); } } return $classes; }
public function download($path) { if (is_null($path) || empty($path)) { throw new InvalidArgumentException('You must specify the item to download.', 400); } else { if (!$this->exists($path) || !is_file($this->realRootDirectory . DIRECTORY_SEPARATOR . $path)) { throw new FileNotFoundException('The specified file does not exist.', 404); } } $fileObject = new \SplFileObject($this->realRootDirectory . DIRECTORY_SEPARATOR . $path); HttpResponse::setContentDisposition($fileObject->getBasename()); HttpResponse::setContentType('application/octet-stream'); HttpResponse::setHeader('Content-Length', $fileObject->getSize()); $fileObject->fpassthru(); exit(0); }
/** * It skips the file headers * @return boolean * @access private * @final */ private final function skipHead() { if ($this->fileObject->getSize() < 0) { return false; } $this->fileObject->rewind(); $this->fileObject->fseek(7, SEEK_CUR); $mainHead = $this->fileObject->fread(7); if (ord($mainHead[2]) != 0x73) { return false; } $headSize = $this->getBytes($mainHead, 5, 2); $this->fileObject->fseek($headSize - 7, SEEK_CUR); unset($mainHead, $headSize); return true; }
/** * Removes a Key/Value pair based on its position in the file * * @param integer $position The offset position in the file */ public function remove($position) { $temp = new \SplTempFileObject(-1); $this->file->flock(LOCK_EX); $filesize = $this->file->getSize(); $metadata = $this->getMetadata($position); // Seek past the document we want to remove $this->file->fseek($metadata->length, SEEK_CUR); // Write everything after the target document to memory $temp->fwrite($this->file->fread($filesize)); // Clear the file up to the target document $this->file->ftruncate($position); // Write Temp back to the end of the file $temp->fseek(0); $this->file->fseek(0, SEEK_END); $this->file->fwrite($temp->fread($filesize)); $this->file->flock(LOCK_UN); }
/** * 获取文件列表 * * @author mrmsl <*****@*****.**> * @date 2012-07-17 12:46:02 * * @param string $node 节点路径 * * @return array 文件列表 */ private function _getFile($node) { $node = trim($node, '/'); $this->_denyDirectory($node); $file_arr = array(); $directory = PACKER_JS_PATH . $node . '/'; $k = 0; if (is_dir($directory)) { $date_format = sys_config('sys_timezone_datetime_format'); $d = dir($directory); while ($f = $d->read()) { if ($f == '.' || $f == '..' || substr($f, 0, 1) == '.') { continue; } $filename = $directory . '/' . $f; if (is_dir($filename)) { $file_arr[$k] = array('text' => $f, 'checked' => $f == 'pack' ? null : false, 'id' => $node . '/' . $f); $file_arr[$k]['data'] = $this->_getFile($f); $k++; } elseif (substr($f, -3) == '.js' && !in_array($f, array('app.js'))) { $desc = ''; //js文件说明 $file = new SplFileObject($filename); if (!strpos($filename, '.min.')) { $file->fgets(); $desc = trim(str_replace('*', '', $file->fgets())); //第二行为文件说明 } $file_arr[] = array('text' => $f, 'id' => $node . '/' . $f, 'leaf' => true, 'checked' => $node == 'pack' ? null : false, 'filesize' => format_size($file->getSize()), 'filemtime' => new_date($date_format, $file->getMTime()), 'desc' => $desc); } } //end while $d->close(); } //end if return $file_arr; }
/** * {@inheritdoc} */ public function updateMetadata(MediaInterface $media, $force = true) { // this is now optimized at all!!! $path = tempnam(sys_get_temp_dir(), 'zym_media_update_metadata'); $fileObject = new \SplFileObject($path, 'w'); $fileObject->fwrite($this->getReferenceFile($media)->getContent()); $media->setSize($fileObject->getSize()); }
/** * {@inheritdoc} */ public function updateMetadata(MediaInterface $media, $force = true) { try { // this is now optimized at all!!! $path = tempnam(sys_get_temp_dir(), 'sonata_update_metadata'); $fileObject = new \SplFileObject($path, 'w'); $fileObject->fwrite($this->getReferenceFile($media)->getContent()); $image = $this->imagineAdapter->open($fileObject->getPathname()); $size = $image->getSize(); $media->setSize($fileObject->getSize()); $media->setWidth($size->getWidth()); $media->setHeight($size->getHeight()); } catch (\LogicException $e) { $media->setProviderStatus(MediaInterface::STATUS_ERROR); $media->setSize(0); $media->setWidth(0); $media->setHeight(0); } }
/** * @param string $sourceUri * @param string $destinationUri * @param int $totalSize * @param string $hash * @throws \Exception * @return int */ public function downloadFile($sourceUri, $destinationUri, $totalSize, $hash) { if (false === ($destination = fopen($destinationUri, 'a+'))) { throw new \Exception('Destination is invalid.'); } if (filesize($destinationUri) > 0) { throw new \Exception(sprintf("File on destination %s does already exist.", $destinationUri)); } $partFile = $destinationUri . '.part'; $partFile = new \SplFileObject($partFile, 'a+'); $size = $partFile->getSize(); if ($size >= $totalSize) { $this->verifyHash($partFile, $hash); $this->moveFile($partFile, $destinationUri); # close local file fclose($destination); unset($partFile); return 0; } $range = $size . '-' . $totalSize; // Configuration of curl $ch = curl_init(); curl_setopt($ch, CURLOPT_RANGE, $range); curl_setopt($ch, CURLOPT_URL, $sourceUri); curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_NOPROGRESS, FALSE); $me = $this; curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($ch, $dltotal, $dlnow) use($me, $size) { if ($dlnow > 0) { $this->progress($dltotal, $dlnow, $size + $dlnow); } }); $me = $this; $isHalted = false; $isError = false; curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $str) use($me, $partFile, &$isHalted, &$isError) { if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 206) { $isError = true; return -1; } $partFile->fwrite($str); if ($me->shouldHalt()) { $isHalted = true; return -1; } return strlen($str); }); $result = curl_exec($ch); $error = curl_error($ch); curl_close($ch); if ($isError && !$isHalted) { throw new \Exception("Wrong http code"); } if ($result === false && !$isHalted) { throw new \Exception($error); } clearstatcache(false, $partFile->getPathname()); $size = $partFile->getSize(); if ($size >= $totalSize) { $this->verifyHash($partFile, $hash); $this->moveFile($partFile, $destinationUri); } // close local file fclose($destination); unset($partFile); return $size; }
<?php $file = __DIR__ . "/data.txt"; file_put_contents($file, "foobar"); $s = new SplFileObject($file); echo $s->getSize();
public function getSizeString() { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = parent::getSize(); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, 2) . ' ' . $units[$pow]; }
/** * {@inheritdoc} */ public function getFileSize() { return $this->file ? $this->file->getSize() : null; }
/** * Unserializes the object from JSON contained in the given file. * * @param \SplFileObject $file * The file to be read from. Since it may also be written to, it should * be opened with mode `c+`. * * @return DivideIQ * The unserialized object. */ public static function fromFile(\SplFileObject $file) { $file->rewind(); $object = static::fromJson($file->fread($file->getSize())); $object->file = $file; return $object; }
private function _getFile($download = false) { if (!$this->authed && !$this->config->readonly) { echo json_encode(array('status' => false, 'message' => 'not authenticated')); exit; } if (!$this->requestDir || !is_file($this->requestDir)) { header('Status: 404 Not Found'); header('HTTP/1.0 404 Not Found'); exit; } $file = new SplFileObject($this->requestDir); // not really sure if this range shit works. stole it from an old script i wrote if (isset($_SERVER['HTTP_RANGE'])) { list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2); if ($size_unit == 'bytes') { list($range, $extra_ranges) = explode(',', $range_orig, 2); } else { $range = ''; } if ($range) { list($seek_start, $seek_end) = explode('-', $range, 2); } $seek_end = empty($seek_end) ? $size - 1 : min(abs(intval($seek_end)), $size - 1); $seek_start = empty($seek_start) || $seek_end < abs(intval($seek_start)) ? 0 : max(abs(intval($seek_start)), 0); if ($seek_start > 0 || $seek_end < $size - 1) { header('HTTP/1.1 206 Partial Content'); } else { header('HTTP/1.1 200 OK'); } header('Accept-Ranges: bytes'); header('Content-Range: bytes ' . $seek_start . '-' . $seek_end . '/' . $size); $contentLength = $seek_end - $seek_start + 1; } else { header('HTTP/1.1 200 OK'); header('Accept-Ranges: bytes'); $contentLength = $file->getSize(); } header('Pragma: public'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Date: ' . date('r')); header('Last-Modified: ' . date('r', $file->getMTime())); header('Content-Length: ' . $contentLength); header('Content-Transfer-Encoding: binary'); if ($download) { header('Content-Disposition: attachment; filename="' . $file->getFilename() . '"'); header('Content-Type: application/force-download'); } else { header('Content-Type: ' . mime_content_type($file->getPathname())); } // i wrote this freading a really long time ago but it seems to be more robust than SPL. someone correct me if im wrong $fp = fopen($file->getPathname(), 'rb'); fseek($fp, $seek_start); while (!feof($fp)) { set_time_limit(0); print fread($fp, 1024 * 8); flush(); ob_flush(); } fclose($fp); exit; }
function gravityCount() { //returns count of domains in blocklist. $NGC4889 = new \SplFileObject('/etc/pihole/gravity.list'); $NGC4889->seek($NGC4889->getSize()); $swallowed = $NGC4889->key(); return $swallowed; }
<?php $fname = tempnam('/tmp', 'foobar'); file_put_contents($fname, 'herpderp'); $spl = new SplFileObject($fname, 'r'); $spl->fseek($spl->getSize() - 4); var_dump($spl->fgets());
} else { ++$logs[$msg]->hits; $time = date_timestamp_get(date_create($parts['time'])); if ($time < $logs[$msg]->first) { $logs[$msg]->first = $time; } if ($time > $logs[$msg]->last) { $logs[$msg]->last = $time; } } $prevError =& $logs[$msg]; } $log->next(); } if ($cache !== null) { $cacheData = serialize(['seek' => $log->getSize(), 'logs' => $logs, 'types' => $types, 'typecount' => $typecount]); file_put_contents($cache, $cacheData); } $log = null; osort($logs, ['last' => SORT_DESC]); $total = count($logs); ksort($types); $host = function_exists('gethostname') ? gethostname() : (php_uname('n') ?: (empty($_SERVER['SERVER_NAME']) ? $_SERVER['HOST_NAME'] : $_SERVER['SERVER_NAME'])); ?> <!doctype html> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="cleartype" content="on"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320">