/** * Tries to determine the file type magically * @param string $data * @returns a string, the mime type, or null if none was found. */ public static function magicMimeType($data) { if (self::$finfo == null) { if (!class_exists('finfo')) { I2CE::raiseError('Magic file utilties not enabled. Please run \'pecl install Fileinfo\' or some such thing.'); return null; } $config = I2CE::getConfig(); $magic_file = null; if ($config->setIfIsSet($magic_file, "/modules/MimeTypes/magic_file")) { $magic_file = I2CE::getFileSearch()->search('MIME', $magic_file); if (!$magic_file) { $magic_file == null; } } //I2CE::raiseError("Using $magic_file"); //@self::$finfo = new finfo(FILEINFO_MIME, $magic_file); @(self::$finfo = new finfo(FILEINFO_MIME)); if (!self::$finfo) { I2CE::raiseError('Unable to load magic file database ' . $magic_file, E_USER_NOTICE); return null; } } if (!($mime_type = self::$finfo->buffer($data))) { I2CE::raiseError('Unable to determine mime type magically', E_USER_NOTICE); //some error occured return null; } return $mime_type; }
/** * Pasa el archivo cache * @param string $ubicacion * @param string $nombre * @return string hash del cache */ public function cache($ubicacion, $nombre = null, $bo_file = true) { $this->_hash = null; $cache = $this->_ci->cache->iniciar(); while (is_null($this->_hash)) { $this->_hash = $this->_ci->random->rand_string(20) . time(); if ($existe = $cache->load($this->_hash)) { $this->_hash = null; } } if (is_null($nombre)) { $nombre = basename($ubicacion); } if ($bo_file) { $archivo = file_get_contents($ubicacion); $mime = mime_content_type($ubicacion); $tipo = pathinfo($ubicacion, PATHINFO_EXTENSION); } else { $archivo = $ubicacion; $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->buffer($ubicacion); $explode = explode(".", $nombre); $tipo = strtolower($explode[count($explode) - 1]); } $cache->save(array("archivo" => $archivo, "archivo_nombre" => $nombre, "mime" => $mime, "tipo" => $tipo), $this->_hash); return $this->_hash; }
public function addFile($field_name, $absolute_filename_path) { $file_info = new \finfo(FILEINFO_MIME); $mime_type = $file_info->buffer(file_get_contents($absolute_filename_path)); $mime = explode(';', $mime_type); $this->files[$field_name] = curl_file_create($absolute_filename_path, reset($mime), basename($absolute_filename_path)); }
/** * Executes index action * * @param sfWebRequest $request A request object */ public function executeShow(sfWebRequest $request) { // for apiKey check $memberId = $this->getUser()->getMember(); $reqFileName = $request->getParameter('filename'); $separates = explode('.', $reqFileName); $cnt = count($separates); $fileId = ''; $ext = ''; if (1 == $cnt) { $fileId = $reqFileName; } else { $fileId = join('', array_slice($separates, 0, $cnt - 1)); $ext = '.' . $separates[$cnt - 1]; } $file = Doctrine::getTable('File')->find($fileId); $this->forward404Unless($file); $filebin = $file->getFileBin(); $data = $filebin->getBin(); $filename = $file->getName(); if (!$data) { return $this->renderJSON(array('status' => 'error', 'message' => 'file download error')); } $filename = substr($filename, strpos($filename, "/", 1)); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($data); $this->getResponse()->setHttpHeader('Content-Type', $type); $this->getResponse()->setHttpHeader('Content-Length', strlen($data)); // for ie if (1 === preg_match('/MSIE/', $request->getHttpHeader('User-Agent'))) { $filename = mb_convert_encoding($filename, 'sjis-win', 'utf8'); } $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="' . $filename . '"'); return $this->renderText($data); }
public function preSaveImageBox($field, $request) { $fieldName = $field['name']; if (empty($_FILES[$fieldName]['name'])) { if (empty($field['required'])) { unset($_REQUEST[$fieldName]); } else { //Settaggio necessario nel caso il campo sia not null $_REQUEST[$fieldName] = null; } return; } if (array_key_exists('max-dimension', $field) && !empty($field['max-dimension'])) { $dimension = explode(',', $field['max-dimension']); HelperImage::resize($_FILES[$fieldName]['tmp_name'], $dimension[0], $dimension[1]); } //Se è necessario immagazzinare il file in un blob recupero il file e lo inserisco in $_REQUEST if (!empty($field['store-in-blob'])) { $_REQUEST[$fieldName] = file_get_contents($_FILES[$fieldName]['tmp_name']); $_REQUEST[$fieldName . '_nam'] = $_FILES[$fieldName]['name']; $finfo = new \finfo(FILEINFO_MIME_TYPE); $_REQUEST[$fieldName . '_typ'] = $finfo->buffer($_REQUEST[$fieldName]); $_REQUEST[$fieldName . '_dim'] = strlen($_REQUEST[$fieldName]); return; } //Inserisco in $_REQUEST il filepath e sposto il file temporaneo nella directory definitiva $_REQUEST[$fieldName] = HelperImage::getUniqueFileName(UPLOAD_PATH . $_FILES[$fieldName]['name']); move_uploaded_file($_FILES[$fieldName]['tmp_name'], $_REQUEST[$fieldName]); }
function getImageType($image_binary) { $data = base64_decode($image_binary); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($data); return $type; }
/** * Renders a scaled version of the image referenced by the provided filename, taken any (optional) manipulators into consideration. * @param String $sourceData The binary data of the original source image. * @param Array $scaleParams * @param Int $imageType One of the PHP image type constants, such as IMAGETYPE_JPEG * @return Array * ['resource'] The image file data string * ['mime'] Mime type of the generated cache file * ['timestamp'] Timestamp of the generated cache file **/ public function scale($sourceData, $scaleParams, $imageType) { $this->_setInputParams($scaleParams); $mem = new Garp_Util_Memory(); $mem->useHighMemory(); if (strlen($sourceData) == 0) { throw new Exception("This is an empty file!"); } if (!($source = imagecreatefromstring($sourceData))) { $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->buffer($sourceData); throw new Exception("This source image could not be scaled. It's probably not a valid file type. Instead, this file is of the following type: " . $mime); } $this->_analyzeSourceImage($source, $imageType); $this->_addOmittedCanvasDimension(); if ($this->_isFilterDefined($scaleParams)) { Garp_Image_Filter::filter($source, $scaleParams['filter']); } if ($this->_isSourceEqualToTarget($scaleParams)) { $outputImage = $sourceData; } else { $canvas = $this->_createCanvasImage($imageType); $this->_projectSourceOnCanvas($source, $canvas); // Enable progressive jpegs imageinterlace($canvas, true); $outputImage = $this->_renderToImageData($canvas); imagedestroy($canvas); } $output = array('resource' => $outputImage, 'mime' => $this->params['mime'], 'timestamp' => time()); imagedestroy($source); return $output; }
public function createFileFromPath($path, $description, Google_ParentReference $fileParent = null) { $fi = new finfo(FILEINFO_MIME); $mimeType = explode(';', $fi->buffer(file_get_contents($path))); $fileName = preg_replace('/.*\\//', '', $path); return $this->createFile($fileName, $mimeType[0], $description, file_get_contents($path), $fileParent); }
public function isPngData($data) { $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->buffer($data); $containsPngMime = strpos($mime, 'image/png') !== false; return $containsPngMime; }
/** * @param $file_loc * @return bool * * https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet#File_uploads * * * */ public static function get_mime_type($file_loc) { $finfo = new finfo(FILEINFO_MIME_TYPE); $fileContents = file_get_contents($file_loc); $mimeType = $finfo->buffer($fileContents); return $mimeType; }
/** * Determine the mimetype of the blob. * * @return string A mimetype */ public function getMimetype() { if (null === $this->mimetype) { $finfo = new \finfo(FILEINFO_MIME); $this->mimetype = $finfo->buffer($this->getContent()); } return $this->mimetype; }
/** * Returns the mime type for content of a string * @param mixed $data * @param string $default * @return string the mime type or default */ public static function getMimeTypeForData($data, $default = null) { if (class_exists('finfo', false)) { $finfo = new finfo(FILEINFO_MIME); return $finfo->buffer($data); } return $default; }
/** * @test */ public function itShouldConvertABase64ImageIntoBinary() { $imageData64 = self::SOME_BASE64_IMAGE; //Using Mime Type, 'cause binary comparison is some kind of akward $expectedMime = self::SOME_MIME; $f = new \finfo(FILEINFO_MIME); $this->assertThat($f->buffer($this->converter->getBinaryImageData($imageData64)), $this->equalTo($expectedMime)); }
protected function _getImageMime($bytes) { $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->buffer($bytes); $mime = explode(';', $mime); $mime = $mime[0]; return $mime; }
public function testCanGenerateLongerValidWav() { $wav = new Wav(); $output = $wav->setFrequency(100)->generate($this->getLoremIpsum()); $finfo = new \finfo(FILEINFO_MIME_TYPE); $mime = $finfo->buffer($output); $this->assertSame('audio/x-wav', $mime); }
public function controller_cors($args) { $url = $args["url"]; $contents = file_get_contents($url); $file_info = new finfo(FILEINFO_MIME_TYPE); $mime_type = $file_info->buffer($contents); header('Content-Type: $mime_type'); return $contents; }
/** * Get the asset from the 'src' parameter * * @param Request $request * @return $this|Response */ public function getAsset(Request $request) { if (!$request->get('src')) { return response('"src" not passed.', Response::HTTP_BAD_REQUEST); } $file = file_get_contents($request->get('src')); $file_info = new \finfo(FILEINFO_MIME_TYPE); $mime_type = $file_info->buffer($file); return response($file)->header('Content-Type', $mime_type); }
function checkContentType($url) { $finfo = new finfo(FILEINFO_MIME_TYPE); $type = @$finfo->buffer(file_get_contents($url)); if ($type == 'text/html') { return true; } else { return false; } }
function download_image_async(string $url, string $basename, string $savedir = '/tmp') : \Generator { static $exts = ['image/jpeg' => '.jpg', 'image/png' => '.png', 'image/gif' => '.gif']; $content = (yield curl_init_with($url)); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($content); $ext = isset($exts[$type]) ? $exts[$type] : ''; file_put_contents("{$savedir}/{$basename}{$ext}", $content); echo "Downloaded {$url}, saved as {$savedir}/{$basename}{$ext}\n"; }
/** * Constrcutor. * * @param array $data */ public function __construct($data) { $this->name = $data['name']; $this->tmpName = $data['tmp_name']; $this->error = $data['error']; $this->size = $data['size']; if ($this->tmpName) { $fileInfo = new \finfo(FILEINFO_MIME); $this->extension = $fileInfo->buffer(file_get_contents($this->tmpName)); } }
/** * @return CURLFile */ public function getCURLFile() { if ($this->mimeType == null) { $finfo = new \finfo(FILEINFO_MIME_TYPE); $this->mimeType = $finfo->buffer($this->data); } $path = tempnam(sys_get_temp_dir(), 'TELEGRAM') . '.' . str_replace('/', '.', $this->mimeType); //todo fix nasty mimetype -> ext converter file_put_contents($path, $this->data); return curl_file_create($path, $this->mimeType); }
function get_content($origin) { if (isset($_REQUEST['_query'])) $url = 'http://'.$origin.'/'.$_REQUEST['_query']; else $url = 'http://'.$origin; $buffer = file_get_contents($url); preg_match('~charset=([-a-z0-9_]+)~i',$buffer, $charset); if (isset($charset[1])) $charset = $charset[1]; else $charset = 'utf-8'; $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($buffer); header('Content-Type: '.$type.'; charset='.$charset); $buffer = str_ireplace(array($origin, '../'), array($_SERVER['HTTP_HOST'], ''), $buffer); return $buffer; }
/** * @param string $content * * @return MimeTypeInterface * @throws MimeTypeNotFoundException */ public static function getMimeTypeByContent($content) { static::initialize(); $fileInfo = new FileInfo(FILEINFO_MIME_TYPE); $contentType = $fileInfo->buffer($content); $filter = function (MimeType $registeredMimeType) use($contentType) { return $contentType === $registeredMimeType->getContentType(); }; /** @var MimeTypeInterface[] $matchingMimeTypes */ $matchingMimeTypes = array_filter(static::$registeredMimeTypes, $filter); return array_shift($matchingMimeTypes); }
/** * return the logo as an image * * @param int $id * @return \Illuminate\Http\Response */ public function logo($id) { $brand = Brand::find($id); // if the brand with the specified id doesn't exist return nothing if (!$brand) { return; } // get the mime type $finfo = new \finfo(FILEINFO_MIME_TYPE); $mimetype = $finfo->buffer($brand->logo); return response($brand->logo)->header('Content-Type', $mimetype); }
public function testRenderBase64() { $this->visitUrl($this->getTestPageBaseUrl() . "/static/basic.html"); //Check we get a string $stringData = $this->browser->renderBase64("png"); $this->assertTrue(is_string($stringData)); $binaryData = base64_decode($stringData, true); //now we check that the binary data is actually PNG $fileInfo = new \finfo(FILEINFO_MIME); $this->assertNotFalse($binaryData); $this->assertNotFalse(strstr($fileInfo->buffer($binaryData), "image/png")); }
private function set_mime_from_string($data) { if (version_compare(PHP_VERSION, '5.3.0') >= 0) { $magic = new finfo(FILEINFO_MIME_TYPE); $this->mime_type = $magic->buffer(substr($data, 0, 2048)); } else { $temp = tmpfile(); fwrite($temp, $data, 2048); fseek($temp, 0); $this->set_mime_compat($temp); fclose($temp); } }
protected function createFile($name) { $file = new File($name); $info = new \finfo(FILEINFO_MIME_TYPE); $path = $this->getFilepath($name); $content = file_get_contents($path); $file->setContent($content); $file->setMimeType($info->buffer($content)); $file->setSize(filesize($path)); $file->setLastAccess(new \DateTime('now', new \DateTimeZone('UTC'))); $file->setLastModification(new \DateTime('-1 day', new \DateTimeZone('UTC'))); return $file; }
public function write($path, $content) { $options = $this->_getOptions($path, array('Body' => $content)); $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = $finfo->buffer($content); if (false !== $mimeType) { $options['ContentType'] = $mimeType; } try { $this->_client->putObject($options); } catch (\Exception $e) { throw new CM_Exception('Cannot write bytes to the path', null, ['bytesCount' => strlen($content), 'path' => $path, 'originalExceptionMessage' => $e->getMessage()]); } }
/** * @param string $fileContents Binary content of file * @param string $destinationPath Full destination path including extension * @return string Returns url for upload on ImgNinja * @throws ServiceException */ public function upload($fileContents, $destinationPath) { $info = new \finfo(FILEINFO_MIME); $mime = $info->buffer($fileContents, FILEINFO_MIME_TYPE); $this->httpRequest->setHeaders(['X-Auth-Token: ' . $this->apiToken, 'Content-type: ' . $mime]); $this->httpRequest->setRawPostData($fileContents); $response = json_decode($this->api($destinationPath, self::METHOD_POST)->getResponse()); if ($response === null || isset($response->error) && $response->error) { $error = isset($response->error) ? $response->error : 'Invalid response'; $code = isset($response->code) ? $response->code : 0; throw new ServiceException($error, $code); } return $response->url; }
/** * Debug HTTP interactions * * @param Client $client * @param OutputInterface $output */ protected function logHttp(Client $client, OutputInterface $output) { $guzzle = $client->getHttpClient(); if (OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity()) { $logger = function ($message) use($output) { $finfo = new \finfo(FILEINFO_MIME); $msg = substr($finfo->buffer($message), 0, 4) == 'text' ? $message : '(binary string)'; $output->writeln('<info>Guzzle</info> ' . $msg); }; $logAdapter = new ClosureLogAdapter($logger); $logPlugin = new LogPlugin($logAdapter, MessageFormatter::DEBUG_FORMAT); $guzzle->addSubscriber($logPlugin); } }