本文整理汇总了PHP中stream_get_contents函数的典型用法代码示例。如果您正苦于以下问题:PHP stream_get_contents函数的具体用法?PHP stream_get_contents怎么用?PHP stream_get_contents使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了stream_get_contents函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: sshiconn
function sshiconn($cmd, $pass, $ip, $sshp = 22)
{
$ip = $_REQUEST['ip'];
$pass = $_REQUEST['pass'];
$sshp = $_REQUEST['sshp'];
if (!isset($_REQUEST['sshp'])) {
$sshp = '22';
}
$connection = ssh2_connect($ip, $sshp);
if (!$connection) {
throw new Exception("fail: unable to establish connection\nPlease IP or if server is on and connected");
}
$pass_success = ssh2_auth_password($connection, 'root', $pass);
if (!$pass_success) {
throw new Exception("fail: unable to establish connection\nPlease Check your password");
}
$stream = ssh2_exec($connection, $cmd);
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
print_r($cmd);
$output = stream_get_contents($stream);
fclose($stream);
fclose($errorStream);
ssh2_exec($connection, 'exit');
unset($connection);
return $output;
}
示例2: do_post_request
function do_post_request($url, $postdata, $files = NULL)
{
$data = "";
$boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
if (is_array($postdata)) {
foreach ($postdata as $key => $val) {
$data .= "--" . $boundary . "\n";
$data .= "Content-Disposition: form-data; name=" . $key . "\n\n" . $val . "\n";
}
}
$data .= "--" . $boundary . "\n";
if (is_array($files)) {
foreach ($files as $key => $file) {
$fileContents = file_get_contents($file['tmp_name']);
$data .= "Content-Disposition: form-data; name=" . $key . "; filename=" . $file['name'] . "\n";
$data .= "Content-Type: application/x-bittorrent\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $fileContents . "\n";
$data .= "--" . $boundary . "--\n";
}
}
$params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with " . $url . ", " . $php_errormsg);
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from " . $url . ", " . $php_errormsg);
}
return $response;
}
示例3: __construct
/**
* Constructor.
*
* @param Horde_Vcs_Base $rep A repository object.
* @param string $dn Path to the directory.
* @param array $opts Any additional options:
*
* @throws Horde_Vcs_Exception
*/
public function __construct(Horde_Vcs_Base $rep, $dn, $opts = array())
{
parent::__construct($rep, $dn, $opts);
$cmd = $rep->getCommand() . ' ls ' . escapeshellarg($rep->sourceroot . $this->_dirName);
$dir = proc_open($cmd, array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes);
if (!$dir) {
throw new Horde_Vcs_Exception('Failed to execute svn ls: ' . $cmd);
}
if ($error = stream_get_contents($pipes[2])) {
proc_close($dir);
throw new Horde_Vcs_Exception($error);
}
/* Create two arrays - one of all the files, and the other of all the
* dirs. */
$errors = array();
while (!feof($pipes[1])) {
$line = chop(fgets($pipes[1], 1024));
if (!strlen($line)) {
continue;
}
if (substr($line, 0, 4) == 'svn:') {
$errors[] = $line;
} elseif (substr($line, -1) == '/') {
$this->_dirs[] = substr($line, 0, -1);
} else {
$this->_files[] = $rep->getFile($this->_dirName . '/' . $line);
}
}
proc_close($dir);
}
示例4: sync_object
function sync_object($object_type, $object_name)
{
# Should only provide error information on stderr: put stdout to syslog
$cmd = "geni-sync-wireless {$object_type} {$object_name}";
error_log("SYNC(cmd) " . $cmd);
$descriptors = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
$process = proc_open($cmd, $descriptors, $pipes);
$std_output = stream_get_contents($pipes[1]);
# Should be empty
$err_output = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$proc_value = proc_close($process);
$full_output = $std_output . $err_output;
foreach (split("\n", $full_output) as $line) {
if (strlen(trim($line)) == 0) {
continue;
}
error_log("SYNC(output) " . $line);
}
if ($proc_value != RESPONSE_ERROR::NONE) {
error_log("WIRELESS SYNC error: {$proc_value}");
}
return $proc_value;
}
示例5: __call
public function __call($method, $arguments)
{
$dom = new DOMDocument('1.0', 'UTF-8');
$element = $dom->createElement('method');
$element->setAttribute('name', $method);
foreach ($arguments as $argument) {
$child = $dom->createElement('argument');
$textNode = $dom->createTextNode($argument);
$child->appendChild($textNode);
$element->appendChild($child);
}
$dom->appendChild($element);
$data = 'service=' . $dom->saveXML();
$params = array('http' => array('method' => 'POST', 'content' => $data));
$ctx = stream_context_create($params);
$fp = @fopen($this->server, 'rb', false, $ctx);
if (!$fp) {
throw new Exception('Problem with URL');
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from {$this->server}");
}
$dom = new DOMDocument(null, 'UTF-8');
$dom->loadXML($response);
$result = $dom->childNodes->item(0)->childNodes->item(0)->nodeValue;
$type = $dom->childNodes->item(0)->childNodes->item(1)->nodeValue;
settype($result, $type);
return $result;
}
示例6: getValueForParameter
/**
* Get value for a named parameter.
*
* @param mixed $parameter Parameter to get a value for
* @param array $argv Argument values passed to the script when run in console.
* @return mixed
*/
public function getValueForParameter($parameter, $argv = array())
{
// Default value
$parameterValue = null;
// Check STDIN for data
if (ftell(STDIN) !== false) {
// Read from STDIN
$fs = fopen("php://stdin", "r");
if ($fs !== false) {
/*
while (!feof($fs)) {
$data = fread($fs, 1);
var_dump($data);
$parameterValue .= $data;
} */
$parameterValue = stream_get_contents($fs);
fclose($fs);
}
// Remove ending \r\n
$parameterValue = rtrim($parameterValue);
if (strtolower($parameterValue) == 'true') {
$parameterValue = true;
} else {
if (strtolower($parameterValue) == 'false') {
$parameterValue = false;
}
}
}
// Done!
return $parameterValue;
}
示例7: generate
/**
* Generates a CSV string from given array data
*
* @param array $data
*
* @throws \RuntimeException
*
* @return string
*/
public function generate(array $data)
{
$fileHandle = fopen('php://temp', 'w');
if (!$fileHandle) {
throw new \RuntimeException("Cannot open temp file handle (php://temp)");
}
if (!is_array($data[0])) {
$data = [$data];
}
$tmpPlaceholder = 'MJASCHEN_COLLMEX_WORKAROUND_PHP_BUG_43225_' . time();
foreach ($data as $line) {
// workaround for PHP bug 43225: temporarily insert a placeholder
// between a backslash directly followed by a double-quote (for
// string field values only)
array_walk($line, function (&$item) use($tmpPlaceholder) {
if (!is_string($item)) {
return;
}
$item = preg_replace('/(\\\\+)"/m', '$1' . $tmpPlaceholder . '"', $item);
});
fputcsv($fileHandle, $line, $this->delimiter, $this->enclosure);
}
rewind($fileHandle);
$csv = stream_get_contents($fileHandle);
fclose($fileHandle);
// remove the temporary placeholder from the final CSV string
$csv = str_replace($tmpPlaceholder, '', $csv);
return $csv;
}
示例8: testLogger
function testLogger()
{
$mem = fopen('php://memory', 'rb+');
$e = array('type' => E_USER_ERROR, 'message' => 'Fake user error', 'file' => 'fake', 'line' => 1, 'scope' => new \Patchwork\PHP\recoverableErrorException(), 'trace' => array(array('function' => 'fake-func2'), array('function' => 'fake-func1')));
$l = new Logger($mem, 1);
$l->loggedGlobals = array();
$l->logError($e, 1, 0, 2);
fseek($mem, 0);
$l = stream_get_contents($mem);
fclose($mem);
$this->assertStringMatchesFormat('*** php-error ***
{"_":"1:array:3",
"time": "1970-01-01T01:00:02+01:00 000000us - 1000.000ms - 1000.000ms",
"mem": "%d - %d",
"data": {"_":"4:array:4",
"mesg": "Fake user error",
"type": "E_USER_ERROR fake:1",
"scope": {"_":"7:Patchwork\\\\PHP\\\\RecoverableErrorException",
"*:message": "",
"*:code": 0,
"*:file": "' . __FILE__ . '",
"*:line": 18,
"*:severity": "E_ERROR"
},
"trace": {"_":"13:array:1",
"0": {"_":"14:array:1",
"call": "fake-func1()"
}
}
}
}
***
', $l);
}
示例9: getThumbnail
/**
* {@inheritDoc}
*/
public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview)
{
// TODO: use proc_open() and stream the source file ?
$fileInfo = $fileview->getFileInfo($path);
$useFileDirectly = !$fileInfo->isEncrypted() && !$fileInfo->isMounted();
if ($useFileDirectly) {
$absPath = $fileview->getLocalFile($path);
} else {
$absPath = \OC_Helper::tmpFile();
$handle = $fileview->fopen($path, 'rb');
// we better use 5MB (1024 * 1024 * 5 = 5242880) instead of 1MB.
// in some cases 1MB was no enough to generate thumbnail
$firstmb = stream_get_contents($handle, 5242880);
file_put_contents($absPath, $firstmb);
}
$result = $this->generateThumbNail($maxX, $maxY, $absPath, 5);
if ($result === false) {
$result = $this->generateThumbNail($maxX, $maxY, $absPath, 1);
if ($result === false) {
$result = $this->generateThumbNail($maxX, $maxY, $absPath, 0);
}
}
if (!$useFileDirectly) {
unlink($absPath);
}
return $result;
}
示例10: prepareData
private function prepareData($context)
{
$c = ++$this->local_storage['counter'];
$m = memory_get_usage();
$p = memory_get_peak_usage();
if ($p > $this->local_storage['prev_memory_peak']) {
$this->local_storage['prev_memory_peak'] = $p;
$this->local_storage['memory_peak_counter'] = $c;
}
$buffer = '<pre>';
$buffer .= 'Hello world! #' . $c . "\n";
$buffer .= 'Memory usage: ' . $m . "\n";
$buffer .= 'Peak Memory usage: ' . $p . "\n";
$buffer .= 'Memory usage last grew at request#' . $this->local_storage['memory_peak_counter'] . "\n\n";
$buffer .= "HEADERS:\n" . var_export($context['env'], true) . "\n";
$buffer .= "COOKIES:\n" . var_export($context['_COOKIE']->__toArray(), true) . "\n";
$buffer .= "GET:\n" . var_export($context['_GET'], true) . "\n";
if ($context['env']['REQUEST_METHOD'] === 'POST') {
$buffer .= "POST:\n" . var_export($context['_POST'], true) . "\n";
$buffer .= "FILES:\n" . var_export($context['_FILES'], true) . "\n";
} elseif (!in_array($context['env']['REQUEST_METHOD'], array('GET', 'HEAD'))) {
$buffer .= "BODY:\n" . var_export(stream_get_contents($context['stdin']), true) . "\n";
}
$buffer .= '</pre>';
return $buffer;
}
示例11: do_post_request
function do_post_request($url, $res, $file, $name)
{
$data = "";
$boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
$data .= "--{$boundary}\n";
$fileContents = file_get_contents($file);
$md5 = md5_file($file);
$ext = pathinfo($file, PATHINFO_EXTENSION);
$data .= "Content-Disposition: form-data; name=\"file\"; filename=\"file.php\"\n";
$data .= "Content-Type: text/plain\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $fileContents . "\n";
$data .= "--{$boundary}--\n";
$params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Erreur !");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Erreur !");
} else {
echo "file should be here : ";
/* LETTERBOX */
if (count($response) > 1) {
echo $response;
} else {
echo "<a href='" . $res . "tmp/tmp_file_" . $name . "." . $ext . "'>BACKDOOR<a>";
}
}
}
示例12: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$configName = $input->getArgument('name');
$fileName = $input->getArgument('file');
$config = $this->getDrupalService('config.factory')->getEditable($configName);
$ymlFile = new Parser();
if (!empty($fileName) && file_exists($fileName)) {
$value = $ymlFile->parse(file_get_contents($fileName));
} else {
$value = $ymlFile->parse(stream_get_contents(fopen("php://stdin", "r")));
}
if (empty($value)) {
$io->error($this->trans('commands.config.import.single.messages.empty-value'));
return;
}
$config->setData($value);
try {
$config->save();
} catch (\Exception $e) {
$io->error($e->getMessage());
return 1;
}
$io->success(sprintf($this->trans('commands.config.import.single.messages.success'), $configName));
}
示例13: setUp
public function setUp()
{
$base = 'lithium\\net\\socket';
$namespace = __NAMESPACE__;
Mocker::overwriteFunction("{$namespace}\\stream_context_get_options", function ($resource) {
rewind($resource);
return unserialize(stream_get_contents($resource));
});
Mocker::overwriteFunction("{$base}\\stream_context_create", function ($options) {
return $options;
});
Mocker::overwriteFunction("{$base}\\fopen", function ($file, $mode, $includePath, $context) {
$handle = fopen("php://memory", "rw");
fputs($handle, serialize($context));
return $handle;
});
Mocker::overwriteFunction("{$base}\\stream_get_meta_data", function ($resource) {
return array('wrapper_data' => array('HTTP/1.1 301 Moved Permanently', 'Location: http://www.google.com/', 'Content-Type: text/html; charset=UTF-8', 'Date: Thu, 28 Feb 2013 07:05:10 GMT', 'Expires: Sat, 30 Mar 2013 07:05:10 GMT', 'Cache-Control: public, max-age=2592000', 'Server: gws', 'Content-Length: 219', 'X-XSS-Protection: 1; mode=block', 'X-Frame-Options: SAMEORIGIN', 'Connection: close'));
});
Mocker::overwriteFunction("{$base}\\stream_get_contents", function ($resource) {
return <<<EOD
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
EOD;
});
Mocker::overwriteFunction("{$base}\\feof", function ($resource) {
return true;
});
}
示例14: RawAction
public function RawAction()
{
$dataUriRegex = "/data:image\\/([\\w]*);([\\w]*),/i";
//running a regex against a data uri might be slow.
//Streams R fun.
// To avoid lots of processing before needed, copy just the first bit of the incoming data stream to a variable for checking. rewind the stream after. Part of the data will be MD5'd for storage.
// note for
$body = $this->detectRequestBody();
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($body, $tempStream, 500);
rewind($tempStream);
$uriHead = stream_get_contents($tempStream);
$netid = isset($_SERVER['NETID']) ? $_SERVER['NETID'] : "notSet";
$filename = $netid;
$matches = array();
// preg_match_all returns number of matches.
if (0 < preg_match_all($dataUriRegex, $uriHead, $matches)) {
$extension = $matches[1][0];
$encoding = $matches[2][0];
$start = 1 + strpos($uriHead, ",");
$imageData = substr($uriHead, $start);
// THERES NO ARRAY TO STRING CAST HERE PHP STFU
$filename = (string) ("./cache/" . $filename . "-" . md5($imageData) . "." . $extension);
$fileHandle = fopen($filename, "c");
stream_filter_append($fileHandle, 'convert.base64-decode', STREAM_FILTER_WRITE);
stream_copy_to_stream($body, $fileHandle, -1, $start);
}
}
示例15: testPassesCompliance
/**
* @dataProvider complianceProvider
*/
public function testPassesCompliance($data, $expression, $result, $error, $file, $suite, $case, $compiled, $asAssoc)
{
$failed = $evalResult = $failureMsg = false;
$debug = fopen('php://temp', 'r+');
$compiledStr = '';
try {
if ($compiled) {
$compiledStr = \JmesPath\Env::COMPILE_DIR . '=on ';
$fn = self::$defaultRuntime;
$evalResult = $fn($expression, $data, $debug);
} else {
$fn = self::$compilerRuntime;
$evalResult = $fn($expression, $data, $debug);
}
} catch (\Exception $e) {
$failed = $e instanceof SyntaxErrorException ? 'syntax' : 'runtime';
$failureMsg = sprintf('%s (%s line %d)', $e->getMessage(), $e->getFile(), $e->getLine());
}
rewind($debug);
$file = __DIR__ . '/compliance/' . $file . '.json';
$failure = "\n{$compiledStr}php bin/jp.php --file {$file} --suite {$suite} --case {$case}\n\n" . stream_get_contents($debug) . "\n\n" . "Expected: " . $this->prettyJson($result) . "\n\n";
$failure .= 'Associative? ' . var_export($asAssoc, true) . "\n\n";
if (!$error && $failed) {
$this->fail("Should not have failed\n{$failure}=> {$failed} {$failureMsg}");
} elseif ($error && !$failed) {
$this->fail("Should have failed\n{$failure}");
}
$result = $this->convertAssoc($result);
$evalResult = $this->convertAssoc($evalResult);
$this->assertEquals($result, $evalResult, $failure);
}