function show() { $folder = 'tmp/'; if (isset($_REQUEST['qqfile'])) { $file = $_REQUEST['qqfile']; $path = $folder . $file; $input = fopen("php://input", "r"); $temp = tmpfile(); $realSize = stream_copy_to_stream($input, $temp); fclose($input); if ($realSize != $_SERVER["CONTENT_LENGTH"]) { die("{'error':'size error'}"); } if (is_writable($folder)) { $target = fopen($path, 'w'); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); echo "{success:true, target:'{$file}'}"; } else { die("{'error':'not writable: {$path}'}"); } } else { $file = $_FILES['qqfile']['name']; $path = $folder . $file; if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) { die("{'error':'permission denied'}"); } echo "{success:true, target:'{$file}'}"; } }
function callWebService($url, $method, $data = "") { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //curl_setopt($ch,CURLOPT_HEADER, 0); $fp = null; if ($method == "PUT") { curl_setopt($ch, CURLOPT_PUT, 1); $fp = tmpfile(); fwrite($fp, $data); fseek($fp, 0); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data)); } elseif ($method == "POST") { $post = array("data" => $data); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); } elseif ($method == "DELETE") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); } $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($fp) { fclose($fp); } curl_close($ch); return array("code" => $httpCode, "content" => $response); }
function create_tmp_file($data) { $tmp_file = tmpfile(); fwrite($tmp_file, $data); rewind($tmp_file); return $tmp_file; }
public static function createTmpFile($data) { $tmp_file = tmpfile(); fwrite($tmp_file, $data); rewind($tmp_file); return $tmp_file; }
private function createTables() { /* @var $entityManager \Doctrine\ORM\EntityManager */ $entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_zfcDatagrid'); /* @var $cli \Symfony\Component\Console\Application */ $cli = $this->getServiceLocator()->get('doctrine.cli'); $helperSet = $cli->getHelperSet(); $helperSet->set(new EntityManagerHelper($entityManager), 'em'); $fp = tmpfile(); // $input = new StringInput('orm:schema-tool:create --dump-sql'); $input = new StringInput('orm:schema-tool:create'); /* @var $command \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand */ $command = $cli->get('orm:schema-tool:create'); $returnCode = $command->run($input, new StreamOutput($fp)); $phpArray = $this->getServiceLocator()->get('Zf2datatable.examples.data.phpArray'); $persons = $phpArray->getPersons(); $this->createData(new Person(), $persons); // $entityManager->f // fseek($fp, 0); // $output = ''; // while (! feof($fp)) { // $output = fread($fp, 4096); // } // fclose($fp); // echo '<pre>'; // print_r($output); // print_r($returnCode); // echo 'DONE!'; // exit(); }
public function testSettingServices() { $logger = new Mustache_Logger_StreamLogger(tmpfile()); $loader = new Mustache_Loader_StringLoader(); $tokenizer = new Mustache_Tokenizer(); $parser = new Mustache_Parser(); $compiler = new Mustache_Compiler(); $mustache = new Mustache_Engine(); $cache = new Mustache_Cache_FilesystemCache(self::$tempDir); $this->assertNotSame($logger, $mustache->getLogger()); $mustache->setLogger($logger); $this->assertSame($logger, $mustache->getLogger()); $this->assertNotSame($loader, $mustache->getLoader()); $mustache->setLoader($loader); $this->assertSame($loader, $mustache->getLoader()); $this->assertNotSame($loader, $mustache->getPartialsLoader()); $mustache->setPartialsLoader($loader); $this->assertSame($loader, $mustache->getPartialsLoader()); $this->assertNotSame($tokenizer, $mustache->getTokenizer()); $mustache->setTokenizer($tokenizer); $this->assertSame($tokenizer, $mustache->getTokenizer()); $this->assertNotSame($parser, $mustache->getParser()); $mustache->setParser($parser); $this->assertSame($parser, $mustache->getParser()); $this->assertNotSame($compiler, $mustache->getCompiler()); $mustache->setCompiler($compiler); $this->assertSame($compiler, $mustache->getCompiler()); $this->assertNotSame($cache, $mustache->getCache()); $mustache->setCache($cache); $this->assertSame($cache, $mustache->getCache()); }
/** * @test */ public function fromFile_exceed_buffer() { //Create a 10k temp file $temp = tmpfile(); fwrite($temp, str_repeat("1", 10000)); $meta_data = stream_get_meta_data($temp); $filename = $meta_data["uri"]; /** @var LoopInterface $loop */ $loop = \EventLoop\getLoop(); $source = new FromFileObservable($filename); $result = false; $complete = false; $error = false; $source->subscribe(new CallbackObserver(function ($value) use(&$result) { $result = $value; }, function ($e) use(&$error) { $error = true; }, function () use(&$complete) { $complete = true; })); $loop->tick(); $this->assertEquals("4096", strlen($result)); $this->assertFalse($complete); $this->assertFalse($error); $loop->tick(); $this->assertEquals("4096", strlen($result)); $this->assertFalse($complete); $this->assertFalse($error); $loop->tick(); $this->assertEquals("1808", strlen($result)); $this->assertTrue($complete); $this->assertFalse($error); }
function connect($filename, $encode = "EUC-JP") { $allData = array(); //一時ファイルを使い、一気に文字コード変換 if (!file_exists($filename)) { return false; } if (!($fileData = file_get_contents($filename))) { return false; } $fileData = mb_convert_encoding($fileData, "UTF-8", $encode); // 一時ファイルに書き込み $handle = tmpfile(); $size = fwrite($handle, $fileData); fseek($handle, 0); while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) { $line = array(); foreach ($data as $val) { echo $val; $line[] = trim($val); } $allData[] = $line; } fclose($handle); if ($this->allData = $allData) { return true; } else { return false; } }
/** * Sends a command with arguments to NodeJS process * which executes and when done returns the response * to this driver if no errors occur a Array returns * * @param string $action Command in NodeJS process * @return Array|Boolean|String * @throws NodeDriverException */ private function executeOnNodeDriver($action) { $args = func_get_args(); array_shift($args); $jsonString = json_encode(["command" => $action, "params" => $args]); $tmpHandle = tmpfile(); fwrite($tmpHandle, $jsonString); $metaDatas = stream_get_meta_data($tmpHandle); $tmpFilename = $metaDatas['uri']; $execString = "node " . realpath(dirname(__FILE__) . '/../../../vendor/node/index.js') . ' ' . $tmpFilename; //debug($execString); try { $response = exec($execString, $output, $return_var); } catch (Exception $e) { //debug($e); } //debug($response); fclose($tmpHandle); if ($return_var != 0) { throw new NodeDriverException([$action, print_r($args, true), $response]); } try { $response = json_decode($response, true); } catch (Exception $ex) { } return $response; }
/** * Open the stream and return the associated resource. * * @param string $streamName Stream name (here, it is * null). * @param \Hoa\Stream\Context $context Context. * @return resource * @throws \Hoa\File\Exception */ protected function &_open($streamName, \Hoa\Stream\Context $context = null) { if (false === ($out = @tmpfile())) { throw new File\Exception('Failed to open a temporary stream.', 0); } return $out; }
/** * Save the file to the specified path * @return boolean TRUE on success */ function save($path, $filename) { $input = fopen("php://input", "r"); $temp = tmpfile(); $realSize = stream_copy_to_stream($input, $temp); fclose($input); if ($realSize != $this->getSize()) { return false; } $target = fopen($path, "w"); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); //insert data into attachment table if (!class_exists('VmConfig')) { require JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'helpers' . DS . 'config.php'; } $thumb_width = VmConfig::loadConfig()->get('img_width'); $user_s =& JFactory::getUser(); $user_id = $user_s->id; $product_vm_id = JRequest::getInt('virtuemart_product_id'); $database =& JFactory::getDBO(); $gallery = new stdClass(); $gallery->id = 0; $gallery->virtuemart_user_id = $user_id; $gallery->virtuemart_product_id = $product_vm_id; $gallery->file_name = $filename; $gallery->created_on = date('Y-m-d,H:m:s'); if (!$database->insertObject('#__virtuemart_product_attachments', $gallery, 'id')) { echo $database->stderr(); return false; } // end of insert data return true; }
public function executeHttpPost($url, $postData) { $curlHandler = curl_init(); curl_setopt($curlHandler, CURLOPT_ENCODING, "gzip"); curl_setopt($curlHandler, CURLOPT_URL, $url); curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlHandler, CURLOPT_CAINFO, realpath(dirname(__FILE__)) . "/startssl.pem"); // THE CRAPIEST THING I'VE EVER SEEN : $putData = tmpfile(); fwrite($putData, $putString); fseek($putData, 0); curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $postData); try { $body = curl_exec($curlHandler); if ($body == false) { throw new Exception("Unable to curl " . $url . " reason: " . curl_error($curlHandler)); } $status = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); if ($status != 200) { throw new ScoopHttpNot200Exception($url, $body, $status); } curl_close($curlHandler); return $body; } catch (Exception $e) { curl_close($curlHandler); throw $e; } }
public function provideNotEmptyTestData() { self::$fileResource = tmpfile(); $emptyCountable = new \ArrayObject(); $countable = new \ArrayObject(['not', 'empty']); return [[null, false], ['', false], ['something', true], [0, false], [1, true], [false, false], [true, true], [[], false], [['not', 'empty'], true], [new \stdClass(), true], [$emptyCountable, false], [$countable, true], [self::$fileResource, true]]; }
public function generate($log) { global $db; $host = "ftp.mozilla.org"; $hostpos = strpos($this->logURL, $host); if ($hostpos === false) { throw new Exception("Log file {$this->logURL} not hosted on {$host}!"); } $path = substr($this->logURL, $hostpos + strlen($host) + strlen("/")); $ftpstream = @ftp_connect($host); if (!@ftp_login($ftpstream, "anonymous", "")) { throw new Exception("Couldn't connect to Mozilla FTP server."); } $fp = tmpfile(); if (!@ftp_fget($ftpstream, $fp, $path, FTP_BINARY)) { throw new Exception("Log not available at URL {$this->logURL}."); } ftp_close($ftpstream); rewind($fp); $db->beginTransaction(); $stmt = $db->prepare("\n UPDATE runs_logs\n SET content = :content\n WHERE buildbot_id = :id AND type = :type;"); $stmt->bindParam(":content", $fp, PDO::PARAM_LOB); $stmt->bindParam(":id", $log['_id']); $stmt->bindParam(":type", $log['type']); $stmt->execute(); $db->commit(); fclose($fp); }
public static function crudHttp($uri, $data, $header = array()) { $ch = curl_init(); if (isset($data['get']) && !empty($data['get'])) { $uri .= '?' . http_build_query($data['get']); } if (isset($data['post']) && !empty($data['post'])) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data['post']); } if (isset($data['put']) && !empty($data['put'])) { $str = stripslashes(http_build_query($data['put'])); $tmp_file = tmpfile(); fwrite($tmp_file, $str); fseek($tmp_file, 0); curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_INFILE, $tmp_file); curl_setopt($ch, CURLOPT_INFILESIZE, strlen($str)); } if (isset($data['delete']) && !empty($data['delete'])) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data['delete']); } curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $r = curl_exec($ch); curl_close($ch); return $r; }
public function testResource() { $res = tmpfile(); $in = new Insistence(); $in->setSchema(['internalType' => 'resource'])->insist($res); $in->setSchema(['internalType' => ['resource', 'string']])->insist($res); }
function connectToSesame($url, $data = "", $del = "", $put = "") { $ch = curl_init($url); curl_setopt($ch, CURLOPT_MUTE, 1); if ($data != "" && $put != "YES") { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "{$data}"); } curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'Authorization: Basic ' . 'bWV0YW1vcnBob3NpczptM3RhbTBycGgwc2lz')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // curl_setopt(CURLOPT_USERPWD, '[metamorphosis]:[m3tam0rph0sis]'); if ($del == "YES") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); } if ($put == "YES") { //$data = http_build_query($data); $len = strlen($data); // $fh = fopen('php://memory', 'rw'); // fwrite($fh, $data); // rewind($fh); $putData = tmpfile(); fwrite($putData, $data); fseek($putData, 0); curl_setopt($ch, CURLOPT_INFILE, $putData); curl_setopt($ch, CURLOPT_INFILESIZE, $len); curl_setopt($ch, CURLOPT_PUT, true); } $output = curl_exec($ch); curl_close($ch); if ($put == "YES") { fclose($putData); } return $output; }
private function gettempfilehandle() { if (!$this->tempfilehandle) { $this->tempfilehandle = tmpfile(); } return $this->tempfilehandle; }
function output_word($data, $fileName = '') { if (empty($data)) { return ''; } $data = ' <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 11"> <meta name=Originator content="Microsoft Word 11"> <xml><w:WordDocument><w:View>Print</w:View></xml></head> <body>' . $data . '</body></html>'; $filepath = tmpfile(); $len = strlen($data); fwrite($filepath, $data); header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename={$fileName}.doc"); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $fileName . '.doc'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $len); rewind($filepath); echo fread($filepath, $len); }
/** * Generate real image. * @param resource $image * @param string $format * @return \App\Libraries\Image */ private static function generateRealImage($image, $format) { $tempFile = tmpfile(); $metaDatas = stream_get_meta_data($tempFile); $tmpFilename = $metaDatas['uri']; fclose($tempFile); switch ($format) { case Objects\Image::PNG: imagepng($image, $tmpFilename); break; case Objects\Image::JPG: imagejpeg($image, $tmpFilename); break; case Objects\Image::GIF: imagegif($image, $tmpFilename); break; default: $format = Objects\Image::PNG; imagepng($image, $tmpFilename); break; } $formatedFilename = $tmpFilename . "." . $format; @rename($tmpFilename, $formatedFilename); imagedestroy($image); return new Objects\Image($formatedFilename, $format); }
protected function getHandles() { if (false === ($stdout_handle = tmpfile())) { throw new PHPUnit_Framework_Exception('A temporary file could not be created; verify that your TEMP environment variable is writable'); } return [1 => $stdout_handle]; }
/** * UNTESTED Parse a text containing CSV formatted data. * * @access public * @param string * @return array */ function parseText($p_Text) { $fp = fopen(tmpfile(), 'w+'); fwrite($fp, $p_Text); rewind($fp); return $this->parseLines($fp); }
/** * Executes the task * * @param array $uParameters parameters * @param FormatterInterface $uFormatter formatter class * * @return int exit code */ public function executeTask(array $uParameters, FormatterInterface $uFormatter) { if (!isset($uParameters[0])) { $uFormatter->writeColor("red", "parameter needed: database name."); return 1; } $tDatabase = $uParameters[0]; // set up server class $tServer = new Server($this->services); $tServer->connect(); // set output $tHandle = tmpfile(); // start dumping database to a local file $uFormatter->writeColor("green", "reading sql dump from the server for database '{$tDatabase}'..."); $tServer->dump($tDatabase, $tHandle); // seek to the beginning fseek($tHandle, 0); // set up client class $tClient = new Client($this->services); $uFormatter->writeColor("green", "writing dump to the client..."); // execute sql at the client $tClient->connect(); $tClient->dropAndCreateDatabase($tDatabase); $tClient->executeStream($tHandle); // close and destroy the file fclose($tHandle); $uFormatter->writeColor("yellow", "done."); return 0; }
function curl_request($url, $verb = "", $request_body) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); if (!empty($verb)) { if (!empty($request_body)) { if ($verb == "PUT") { $putData = tmpfile(); fwrite($putData, $request); fseek($putData, 0); curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_INFILE, $putData); curl_setopt($ch, CURLOPT_INFILESIZE, strlen($request)); } else { if ($verb == "POST") { curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/xml")); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body); } } } else { if ($verb == "DELETE") { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); } else { // Simple GET } } } else { // No Action } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERPWD, $this->token); $data = curl_exec($ch); curl_close($ch); return $data; }
/** * NOTE: This function is incomplete, the fallback is to '/tmp' which targets Unix-like. * * @return string */ function php_sys_get_temp_dir() { // (PHP 5 >= 5.2.1) if (function_exists('sys_get_temp_dir')) { return sys_get_temp_dir(); } // (PHP 4 >= 4.3.0, PHP 5) if (function_exists('stream_get_meta_data')) { $handle = tmpfile(); // (PHP 4, PHP 5) $meta = stream_get_meta_data($handle); // (PHP 5 >= 5.1.0) if (isset($meta['uri'])) { return dirname($meta['uri']); } } // emulate PHP 4 <= 4.0.6 tempnam() behavior, fragile foreach (array('TMPDIR', 'TMP') as $key) { if (isset($_ENV[$key])) { return $_ENV[$key]; } } // fallback for Unix-like (php_shell specifically) return '/tmp'; }
static function upload_from_string($string, $url) { $fh = tmpfile(); fwrite($fh, $string); fseek($fh, 0); return self::put($fh, $url); }
function createFile($imgURL) { $remImgURL = urldecode($imgURL); $urlParced = pathinfo($remImgURL); $remImgURLFilename = $urlParced['basename']; $imgData = wp_remote_get($remImgURL); if (is_wp_error($imgData)) { $badOut['Error'] = print_r($imgData, true) . " - ERROR"; return $badOut; } $imgData = $imgData['body']; $tmp = array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()] = tmpfile()))); if (!is_writable($tmp)) { return "Your temporary folder or file (file - " . $tmp . ") is not witable. Can't upload images to Flickr"; } rename($tmp, $tmp .= '.png'); register_shutdown_function(create_function('', "unlink('{$tmp}');")); file_put_contents($tmp, $imgData); if (!$tmp) { return 'You must specify a path to a file'; } if (!file_exists($tmp)) { return 'File path specified does not exist'; } if (!is_readable($tmp)) { return 'File path specified is not readable'; } // $data['name'] = basename($tmp); return "@{$tmp}"; }
function save($path) { $input = fopen("php://input", "r"); $temp = tmpfile(); $realSize = stream_copy_to_stream($input, $temp); fclose($input); if ($realSize != $this->getSize()) { return false; } ///////////////////////////////////////////////////// $target = fopen(JPATH_SITE . "/tmp/" . basename($path), "w"); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); $extension = explode(".", $path); $extension_file = $extension[count($extension) - 1]; if ($extension_file == 'jpg' || $extension_file == 'jpeg' || $extension_file == 'png' || $extension_file == 'gif' || $extension_file == 'JPG' || $extension_file == 'JPEG' || $extension_file == 'PNG' || $extension_file == 'GIF') { $image_size = getimagesize(JPATH_SITE . "/tmp/" . basename($path)); } if (isset($image_size) && $image_size === FALSE) { unlink(JPATH_SITE . "/tmp/" . basename($path)); return false; } unlink(JPATH_SITE . "/tmp/" . basename($path)); ///////////////////////////////////////////////////// $target = fopen($path, "w"); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); return true; }
public static function createTempFile($data) { $tmpFile = tmpfile(); fwrite($tmpFile, base64_decode($data)); fseek($tmpFile, 0); return $tmpFile; }
function file_put_contents($file, $data) { if (is_array($data)) { $data = implode("\n", $data); } if (file_put_contents($file, $data) == false) { if ($this->init()) { $fp = tmpfile(); if (!is_resource($fp)) { return false; } fwrite($fp, $data); fseek($fp, 0); if ($this->ftp->put(&$fp, $file) == false) { return false; } if (is_resource($fp)) { fclose($fp); } return true; } else { return false; } } else { return true; } }