public function read($length = 3600, $ending = "\r\n") { if (!is_resource($this->_resource)) { return false; } return stream_get_line($this->_resource, $length, $ending); }
protected function performHandshake() { $request = ''; do { $buffer = stream_get_line($this->socket, 1024, "\r\n"); $request .= $buffer . "\n"; $metadata = stream_get_meta_data($this->socket); } while (!feof($this->socket) && $metadata['unread_bytes'] > 0); if (!preg_match('/GET (.*) HTTP\\//mUi', $request, $matches)) { throw new ConnectionException("No GET in request:\n" . $request); } $get_uri = trim($matches[1]); $uri_parts = parse_url($get_uri); $this->request = explode("\n", $request); $this->request_path = $uri_parts['path']; /// @todo Get query and fragment as well. if (!preg_match('#Sec-WebSocket-Key:\\s(.*)$#mUi', $request, $matches)) { throw new ConnectionException("Client had no Key in upgrade request:\n" . $request); } $key = trim($matches[1]); /// @todo Validate key length and base 64... $response_key = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); $header = "HTTP/1.1 101 Switching Protocols\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Accept: {$response_key}\r\n" . "\r\n"; $this->write($header); $this->is_connected = true; }
function DoTest($fp, $delim) { echo "Delimiter: " . $delim . "\n"; rewind($fp); echo "\t" . stream_get_line($fp, 10, $delim) . "\n"; echo "\t" . stream_get_line($fp, 10, $delim) . "\n"; }
public function makeRequest($out) { if (!$this->connectSocket()) { // reconnect if not connected return FALSE; } fwrite($this->socket, $out . "\r\n"); $line = fgets($this->socket); $line = explode(" ", $line); $status = intval($line[0], 10); $hasResponse = true; if ($status === 200) { // several lines followed by empty line $endSequence = "\r\n\r\n"; } else { if ($status === 201) { // one line of data returned $endSequence = "\r\n"; } else { $hasResponse = FALSE; } } if ($hasResponse) { $response = stream_get_line($this->socket, 1000000, $endSequence); } else { $response = FALSE; } return array("status" => $status, "response" => $response); }
/** * Imports a single database table using the WordPress database class. * @access public * @param string $table The table to import * @return array An array of the results. */ public function import_table_wpdb($table, $replace_url = '') { $live_url = site_url(); $fh = fopen("{$this->backup_dir}revisr_{$table}.sql", 'r'); $size = filesize("{$this->backup_dir}revisr_{$table}.sql"); $status = array('errors' => 0, 'updates' => 0); while (!feof($fh)) { $query = trim(stream_get_line($fh, $size, ';' . PHP_EOL)); if (empty($query)) { $status['dropped_queries'][] = $query; continue; } if ($this->wpdb->query($query) === false) { $status['errors']++; $status['bad_queries'][] = $query; } else { $status['updates']++; $status['good_queries'][] = $query; } } fclose($fh); if ('' !== $replace_url) { $this->revisr_srdb($table, $replace_url, $live_url); } if (0 !== $status['errors']) { return false; } return true; }
function read_sequence($id) { $id = '>' . $id; $ln_id = strlen($id); $fd = STDIN; // reach sequence three do { $line = stream_get_line($fd, 250, "\n"); // if EOF then we couldn't find the sequence if (feof($fd)) { exit(-1); } } while (strncmp($line, $id, $ln_id) !== 0); ob_start(); // for repeated string concatenations, output buffering is fastest // next, read the content of the sequence while (!feof($fd)) { $line = stream_get_line($fd, 250, "\n"); if (!isset($line[0])) { continue; } $c = $line[0]; if ($c === ';') { continue; } if ($c === '>') { break; } // append the uppercase sequence fragment, // must get rid of the CR/LF or whatever if present echo $line; } return strtoupper(ob_get_clean()); }
function ask($question, $default = null, $validator = null) { global $STDIN, $STDOUT; if (!is_resource($STDIN)) { $STDIN = fopen('php://stdin', 'r'); } if (!is_resource($STDOUT)) { $STDOUT = fopen('php://stdout', 'w'); } $input_stream = $STDIN; while (true) { print WARN . "- {$question}"; if ($default !== null) { print MAGENTA . "[{$default}]"; } print NORMAL . ": "; $answer = stream_get_line($input_stream, 10240, "\n"); if (!$answer && $default !== null) { return $default; } if ($answer && (!$validator || $validator($answer))) { return $answer; } } }
private function check_ip() { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } $this->current_ip = md5($ip); if (!file_exists($this->config['ips'])) { if (is_writable('.')) { touch($this->config['ips']); } else { exit('Could not create "' . $this->config['ips'] . '"'); } } if ($file = fopen($this->config['ips'], 'r')) { while ($line = stream_get_line($file, 128, "\n")) { if (strpos($line, $this->current_ip) !== FALSE) { $this->counted = TRUE; break; } } fclose($file); } else { exit('Could not open "' . $this->config['ips'] . '"'); } if (!$this->counted) { file_put_contents($this->config['ips'], $this->current_ip . "\n", FILE_APPEND); } }
public function parse() { $this->_line_number = 1; $this->_char_number = 1; $eof = false; while (!feof($this->_stream) && !$eof) { $pos = ftell($this->_stream); $line = stream_get_line($this->_stream, $this->_buffer_size, $this->_line_ending); $ended = (bool) (ftell($this->_stream) - strlen($line) - $pos); // if we're still at the same place after stream_get_line, we're done $eof = ftell($this->_stream) == $pos; $byteLen = strlen($line); for ($i = 0; $i < $byteLen; $i++) { if ($this->_emit_file_position) { $this->_listener->file_position($this->_line_number, $this->_char_number); } $this->_consume_char($line[$i]); $this->_char_number++; } if ($ended) { $this->_line_number++; $this->_char_number = 1; } } }
public function index() { $RESPONSE_END_TAG = "<END/>"; if (isset($_POST['command_line'])) { $addr = gethostbyname("localhost"); $client = stream_socket_client("tcp://{$addr}:2014", $errno, $errorMessage); if ($client === false) { throw new UnexpectedValueException("Failed to connect: {$errorMessage}"); } else { fwrite($client, $_POST['command_line']); $server_response = stream_get_line($client, 1024, $RESPONSE_END_TAG); fclose($client); $data = $server_response; //write to file $myfile = fopen("evaluate_output.txt", "a") or die("Unable to open file!"); fwrite($myfile, $data . PHP_EOL); fclose($myfile); //write on the html page header('Content-Type: application/json'); echo json_encode(array('response' => $server_response)); } } else { header('Content-Type: application/json'); echo json_encode(array('response' => 'Missing parameters : Please fill all the required parameters ! ', 'others' => '')); } }
public function index() { if (isset($_POST['config']) && isset($_POST['command_test'])) { $RESPONSE_END_TAG = "<END/>"; $addr = gethostbyname("localhost"); $client = stream_socket_client("tcp://{$addr}:2014", $errno, $errorMessage); if ($client === false) { throw new UnexpectedValueException("Failed to connect: {$errorMessage}"); } $config = $_POST['config']; fwrite($client, 'test ' . $_POST['command_test'] . ' ' . $config); $server_response = stream_get_line($client, 1024, $RESPONSE_END_TAG); fclose($client); $response_code = substr($server_response, 0, 2); $server_response = substr($server_response, 3, strlen($server_response)); $msg = ''; $time = ''; if ($response_code == 'OK') { $data = explode(') ', $server_response); $msg = str_replace('(', '', $data[0]) . '.'; $time = str_replace(')', '', str_replace('(', '', $data[1])) . '.'; } else { $msg = 'The following error occurred : ' . str_replace(')', '', str_replace('(', '', $server_response)) . '.'; } header('Content-Type: application/json'); echo json_encode(array('response' => nl2br($msg), 'others' => $time)); //echo $msg."</br>".$time; } else { header('Content-Type: application/json'); echo json_encode(array('response' => 'Missing parameters : Please fill all the required parameters ! ', 'others' => '')); } }
function readline() { $line = ''; do { if ($this->eol) { $more = stream_get_line($this->stream, $this->blocksize, $this->eol); } else { $more = fgets($this->stream, $this->blocksize); } // Sockets may return boolean FALSE for EOF and empty string // for client disconnect. if ($more === false && feof($this->stream)) { break; } elseif ($more === '') { throw new Exception\ClientDisconnect(); } $line .= $more; $pos = ftell($this->stream); // Check if $blocksize bytes were read, which indicates that // an EOL might not have been found if (($pos - $this->pos) % $this->blocksize == 0) { // Attempt to seek back to read the EOL if (!$this->seek(-$this->ceol, SEEK_CUR)) { break; } if ($this->read($this->ceol) !== $this->eol) { continue; } } $this->pos = $pos; } while (false); return $line; }
function read_sequence($id) { $id = '>' . $id; $ln_id = strlen($id); $fd = STDIN; // reach sequence three while (strpos($line, $id) === false) { $line = stream_get_line($fd, 64, "\n"); // returns faster when the length is too large. if (feof($fd)) { exit(-1); } } // next, read the content of the sequence $r = ''; while (!feof($fd)) { $line = stream_get_line($fd, 64, "\n"); if (!isset($line[0])) { continue; } $c = $line[0]; if ($c === ';') { continue; } if ($c === '>') { break; } $r .= $line; } return strtoupper($r); }
function getWeatherData($strURL, $strCacheFile, $intLimitHours, &$strGeographicLocation) { if (!file_exists($strCacheFile) || filemtime($strCacheFile) + 60 * 60 * $intLimitHours < time()) { $arrCacheData = file($strURL); if (!$arrCacheData) { die('Problem Retrieving NOAA Data! Please try your request again.'); } $arrGeographicLocation = explode('"', $arrCacheData[1], 3); $strGeographicLocation = str_replace('"', '', $arrGeographicLocation[1]); $arrCacheData = array_filter($arrCacheData, "removeWeatherXMLCruft"); $arrCacheData = array_merge($arrCacheData); $fdCacheFile = fopen($strCacheFile, "w"); fputs($fdCacheFile, $strGeographicLocation . "\n"); for ($i = 0; $i < sizeof($arrCacheData); $i++) { fputs($fdCacheFile, $arrCacheData[$i]); } fclose($fdCacheFile); } $arrCacheData = array(); $fdCacheFile = fopen($strCacheFile, "r"); $strGeographicLocation = stream_get_line($fdCacheFile, 4096, "\n"); while (!feof($fdCacheFile)) { $arrCacheData[] = stream_get_line($fdCacheFile, 4096, "\n"); } fclose($fdCacheFile); $strWeatherData = implode("\r\n", $arrCacheData); $strWeatherData = strip_tags(str_replace(array(',', "\r\n"), array('', ','), $strWeatherData)); $arrCacheData = str_getcsv($strWeatherData); return array_chunk($arrCacheData, 3); }
/** * Checks if CSS file was compiled from LESS * * @param string $dir a path to file * @param string $entry a filename * * @return boolean */ public static function isCssLessCompiled($dir, $entry) { $file = $dir . '/' . $entry; $fp = fopen($file, 'r'); $line = stream_get_line($fp, 1024, "\n"); fclose($fp); return 0 === strcmp($line, self::getCssHeader()); }
/** * Read a single line from the console input * * @param int $maxLength Maximum response length * @return string */ public function readLine($maxLength = 2048) { if($this->autoRewind) { rewind($this->stream); } $line = stream_get_line($this->stream, $maxLength, PHP_EOL); return rtrim($line,"\n\r"); }
function getCliInput() { if (function_exists('readline')) { return readline("> "); } echo "> "; return stream_get_line(STDIN, 1024, PHP_EOL); }
/** * Read input from console * * @param string $prompt * * @return string */ public function readline($prompt) { if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { echo $prompt; return stream_get_line(STDIN, 2048, PHP_EOL); } return readline($prompt); }
/** * Reads a line of user input * * @author Art <*****@*****.**> * * @param string $prompt Prompt message * * @return string */ static function readline($prompt = null) { if ($prompt) { echo '[' . date('Y-m-d H:i:s') . '] ' . $prompt . ': '; } $r = trim(strtolower(stream_get_line(STDIN, PHP_INT_MAX, PHP_EOL))); echo PHP_EOL; return $r; }
public function proxify(\Erebot\URIInterface $proxyURI, \Erebot\URIInterface $nextURI) { $credentials = $proxyURI->getUserInfo(); $host = $nextURI->getHost(); $port = $nextURI->getPort(); $scheme = $nextURI->getScheme(); if ($port === null) { $port = getservbyname($scheme, 'tcp'); } if (!is_int($port) || $port <= 0 || $port > 65535) { throw new \Erebot\InvalidValueException('Invalid port'); } $request = ""; $request .= sprintf("CONNECT %s:%d HTTP/1.0\r\n", $host, $port); $request .= sprintf("Host: %s:%d\r\n", $host, $port); $request .= "User-Agent: Erebot/dev-master\r\n"; if ($credentials !== null) { $request .= sprintf("Proxy-Authorization: basic %s\r\n", base64_encode($credentials)); } $request .= "\r\n"; for ($written = 0, $len = strlen($request); $written < $len; $written += $fwrite) { $fwrite = fwrite($this->_socket, substr($request, $written)); if ($fwrite === false) { throw new \Erebot\Exception('Connection closed by proxy'); } } $line = stream_get_line($this->_socket, 4096, "\r\n"); if ($line === false) { throw new \Erebot\InvalidValueException('Invalid response from proxy'); } $this->_logger->debug('%(line)s', array('line' => addcslashes($line, ".."))); $contents = array_filter(explode(" ", $line)); switch ((int) $contents[1]) { case 200: break; case 407: throw new \Erebot\Exception('Proxy authentication required'); default: throw new \Erebot\Exception('Connection rejected by proxy'); } // Avoid an endless loop by limiting the number of headers. // No HTTP server is likely to send more than 2^10 headers anyway. $max = 1 << 10; for ($i = 0; $i < $max; $i++) { $line = stream_get_line($this->_socket, 4096, "\r\n"); if ($line === false) { throw new \Erebot\InvalidValueException('Invalid response from proxy'); } if ($line == "") { break; } $this->_logger->debug('%(line)s', array('line' => addcslashes($line, ".."))); } if ($i === $max) { throw new \Erebot\InvalidValueException('Endless loop detected in proxy response'); } }
/** * Asks a question to the user. * * @param OutputInterface $output * @param string|array $question The question to ask * @param string $default The default answer if none is given by the user * * @return string The user answer */ public function ask(OutputInterface $output, $question, $default = null) { $output->write($question); if (false === ($ret = stream_get_line(null === $this->inputStream ? STDIN : $this->inputStream, 4096, "\n"))) { throw new \Exception('Aborted'); } $ret = trim($ret); return strlen($ret) > 0 ? $ret : $default; }
function prompt($msg) { if (PHP_OS == 'WINNT') { echo $msg; return stream_get_line(STDIN, 1024, PHP_EOL); } else { return readline($msg); } }
private function read_template($name) { $lines = array(); $file = fopen($name, 'r'); while (!feof($file)) { $lines[] = stream_get_line($file, 30000, "\n"); } return $lines; }
protected function process_lines($stream) { while ($line = stream_get_line($stream, 9000, "\n")) { list(, $json_game) = explode("\t", $line); $decoded = json_decode($json_game, true); (yield $decoded); } fclose($stream); }
/** * Reads a line of user input. Windows does not have readline() so a cross-platform solution is required. * * @author Art <*****@*****.**> * * @param string $prompt Prompt message * * @return string */ static function readline($prompt = null) { if ($prompt) { echo $prompt; } $r = trim(strtolower(stream_get_line(STDIN, PHP_INT_MAX, PHP_EOL))); echo PHP_EOL; return $r; }
/** * Cross-platform input on the command line * * @param string $question The question to ask * * @return string */ function getInput($question = '') { if (!function_exists('readline')) { echo $question . ' '; return stream_get_line(STDIN, 1024, PHP_EOL); } else { return readline($question . ' '); } }
/** * Make sure perl script worked * @throws RuntimeException */ protected function readFirstLine() { $FirstLine = stream_get_line($this->Handle, 4096, PHP_EOL); if (trim($FirstLine) != 'SUCCESS') { fclose($this->Handle); unlink($this->Filename); throw new RuntimeException('Reading *.fit-file failed. First line was "' . $FirstLine . '".'); } }
public function seeInLogs(array $patterns) { foreach ($patterns as $pattern) { $line = stream_get_line($this->logFile, 1024, "\n"); \PHPUnit_Framework_Assert::assertRegExp($pattern, $line); } $rest = stream_get_line($this->logFile, 1024, "\n"); $this->assertFalse($rest); }
/** * @param resource $handle * @return array */ public function read() { $handle = func_get_arg(0); $string = ''; while (!feof($handle)) { $string .= stream_get_line($handle, self::LENGTH, "\n"); } return $this->decode($this->spec, $string); }
/** * Deserializes a goal state document. * * @return none */ public function deserialize() { do { $lengthString = stream_get_line($this->_inputStream, 100, "\n"); } while (empty($lengthString) || $lengthString == "\n" || $lengthString == "\r"); $intLengthString = hexdec(trim($lengthString)); $chunkData = stream_get_contents($this->_inputStream, $intLengthString); $goalState = $this->_deserializer->deserialize($chunkData); return $goalState; }