Are sockets so slow in PHP? - php

I'm using this code for sockets. Console says that the page is processed for a very small amount of time, but Chrome says that page is loading for ~1 second!
$this->serv_sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($this->serv_sock, $this->serv, $this->port) or die("Could not bind to address\n");
socket_listen($this->serv_sock);
while (1) {
echo "Waiting...\n";
$client = socket_accept($this->serv_sock);
$start_mtime = microtime(true);
echo "Accepted at ".$start_mtime.".\n";
$input = '';
$len = 0;
do {
//echo "Reading.\n";
$inp = socket_read($client, 1024);
$input .= $inp;
if (strpos($input, "\n\n") === false && strpos($input, "\r\n\r\n") === false)
continue;
if (!$len) {
if (!preg_match("/Content-Length: (\d+)/", $input, $matches)) {
break;
}
$len = $matches[1];
if (!$len)
break;
echo "We want $len bytes.\n";
}
if (strpos($input, "\n\n") !== false)
list($headers, $content) = explode("\n\n", $input);
else
list($headers, $content) = explode("\r\n\r\n", $input);
if (strlen($content) >= $len)
break;
} while ($inp);
echo "Calling callback as ".microtime(true).".\n";
if (strpos($input, "\n\n") !== false)
list($headers, $content) = explode("\n\n", $input);
else
list($headers, $content) = explode("\r\n\r\n", $input);
$output = $this->translate($callback, $headers, $content); // nothing slow here
$time_end = microtime(true);
echo "Sending output at ".$time_end." (total ".($time_end - $start_mtime).")\n\n";
$output = "HTTP/1.0 Ok\n".
"Content-Type: text/html; charset=utf-8\n".
"Content-Length: ".strlen($output)."\n".
"Connection: close\n\n".
$output;
socket_write($client, $output);
socket_close($client);
}

If I understand what you're saying. As far as I know there is a difference between server processing time and client processing time.
The time it actually takes to process the information on the server will always be less. Once the server finishes processing the information the data still has to be sent to the browser and has to be rendered. The time for the data to get there and for the browser to render is what I'm suspecting the reason is as to why Chrome is telling you it's taking ~1 second.

Related

PHP fwirte() how can I set timeout?

I have a problem.
I connect a server use fsockopen and it success.
Maybe Network blocking after connect successed, so, I want to set a timeout when I use fread and fwrite.
I can set timeout with stream_set_timeout when I fread something,
and checked by stream_get_meta_data.
$fs = fsockopen("127.0.0.1", 10008, $errno, $errstr, 1);
stream_set_timeout($fs, 5, 0);
read(1024,$fs);
function read($length, $fs)
{
$read = 0;
$parts = array();
while ($read < $length && !feof($fs)) {
$data = fread($fs, $length - $read);
$status = stream_get_meta_data($fs);
if ($status['timed_out']) {
die("Stream Timeout!n");
}
$read += strlen($data);
$parts []= $data;
}
return implode($parts);
}
now, I want to know, if stream_set_timeout can work in fwrite?
and, How can I set timeout when I use fwrite?
My English is so poor.sorry.

Cannot get required headers from some IPs and ports to parse song title using ShoutCast protocol

I'm trying to extract song title from live mp3 streams using SC protocol. The php script works fine with some IPs and ports, however with some IPs and ports I cannot get required headers from the response to determine the meta-block frequency, therefore I cannot find the location of the song title in the stream. Here's my code:
<?php
while(true)
{
//close warning messages (re-open for debugging)
error_reporting(E_ERROR | E_PARSE);
//create and connect socket with the parameters entered by the user
$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
echo "Establishing connection to the given adress...\n";
$fp = fsockopen($argv[1], $argv[2], $errno, $errstr, 10);
if($fp)
{
echo "Connection established.\n";
$result = socket_connect($sock, $argv[1], $argv[2]);
//prepare request
$request = "GET / HTTP/1.1\r\n";
$request .= "Icy-MetaData: 1\r\n\r\n";
//send request
socket_write($sock,$request,strlen($request));
//set sentinel boolean value's initial value
$headers = true;
//put the segment to be parsed into a string variable
$l = socket_read($sock,2048);
$meta = "";
$streamurl = "";
$checkContentType = false;
//Parsing metadata frequency and streamurl from response's headers.
foreach(preg_split("/((\r?\n)|(\r\n?))/", $l) as $line)
{
if(!(strpos($line, "metaint:") === false))
{
$meta = $line;
}
if(!(strpos($line, "icy-url:") === false))
{
$streamurl = $line;
}
if(!strpos($line, "audio/mpeg") === false)
{
$checkContentType = true;
}
}
echo $l;
//Checking if the content of the stream is mpeg or not
if($checkContentType)
{
$pos = strpos($meta, ":");
$interval = intval(substr($meta,$pos+1));
$pos = strpos($streamurl, ":");
$streamurl = substr($streamurl, $pos+1);
$flag = false;
//initialize bytecount to 0
$bytecount = 0;
//Extracting song title using SC protocol
while($headers)
{
$l = socket_read($sock,PHP_NORMAL_READ);
$bytecount++;
if($bytecount == $interval )
{
$headers = false;
$flag = true;
}
if($flag)
{
$len = ord($l);
}
}
//Determining length variable
$len = $len * 16;
$string = socket_read($sock,$len);
$pos2 = strpos($string, "'") + 1;
$pos3 = strpos($string, ";",$pos2) -1;
$songtitle = substr($string, $pos2, ($pos3-$pos2));
//Formatting the log entry
$finalstr = "[".date("c")."]"."[".$streamurl."]".$songtitle."\n";
echo "logged".$finalstr;
//finalize connection
socket_close($sock);
//Writing the requested info to a log file
file_put_contents("log.txt", $finalstr,FILE_APPEND | LOCK_EX);
//waiting 5 minutes
echo "Logging next entry in five minutes. \n";
sleep(300);
}
else
{
echo "Content of the stream is not suitable.\n";
exit;
}
}
else
{
echo "Unable to connect to the given ip and port.\n Exiting...\n";
socket_close($sock);
exit;
}
}
?>
I've never tried to access shoutcast programatically but I've run streaming audio servers in the past. There are actually two different flavours of shoutcast server and I would guess your program is trying to talk to one and these broken servers are the other type.
From the post READING SHOUTCAST METADATA FROM A STREAM:
Turns out that SHOUTcast and Icecast (two of the most popular server
applications for streaming radio) are supposed to be compatible, but
the response message from each server is slightly different.
Full details about the shoutcast protocol: Shoutcast Metadata Protocol

PHP Socket - send binary data

How to send binary data representing 01 (PHP)?
My Server code (sockets TCP, address is only example. I use my server address of course)
error_reporting(E_ALL);
set_time_limit(0);
ignore_user_abort(true);
$address = '11.111.111.111'; // example server address
$port = 9000; // example port
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, $address, $port);
socket_listen($sock);
$clients = array($sock);
while(true) {
$read = $clients;
if (socket_select($read, $write = NULL, $except = NULL, 0) < 1) {
continue;
}
if (in_array($sock, $read)) {
$clients[] = $newsock = socket_accept($sock);
$key = array_search($sock, $read);
unset($read[$key]);
}
foreach ($read as $read_sock) {
$data = #socket_read($read_sock, 1024);
if ($data === false) {
// remove client for $clients array
$key = array_search($read_sock, $clients);
unset($clients[$key]);
echo "client disconnected.\n";
// continue to the next client to read from, if any
continue;
}
$data = trim($data);
// check if there is any data after trimming off the spaces
if (!empty($data)) {
// send this to all the clients in the $clients array (except the first one, which is a listening socket)
foreach ($clients as $send_sock) {
// if its the listening sock or the client that we got the message from, go to the next one in the list
if ($send_sock == $sock || $send_sock == $read_sock) {
continue;
}
$fp = fopen('socket_communication.txt', 'a');
fwrite($fp, date("Y-m-d H:i:s")." - DATA ".$data."\n");
fclose($fp);
$value = unpack('H*', "1");
$response = base_convert($value[1], 16, 2);
socket_write($send_sock, $response, 1);
} // end of broadcast foreach
}
}
}
echo "Closing sockets...";
socket_close($sock);
I would like to server sent binary data (01 or 1).
I use unpack function and convert it by base_convert but it doesnt works.
This code send response to client
$value = unpack('H*', "1");
$response = base_convert($value[1], 16, 2);
socket_write($send_sock, $response, 1);

Using PHP to read a web page with fsockopen(), but fgets is not working

Im using this code here: http://www.digiways.com/articles/php/httpredirects/
public function ReadHttpFile($strUrl, $iHttpRedirectMaxRecursiveCalls = 5)
{
// parsing the url getting web server name/IP, path and port.
$url = parse_url($strUrl);
// setting path to '/' if not present in $strUrl
if (isset($url['path']) === false)
$url['path'] = '/';
// setting port to default HTTP server port 80
if (isset($url['port']) === false)
$url['port'] = 80;
// connecting to the server]
// reseting class data
$this->success = false;
unset($this->strFile);
unset($this->aHeaderLines);
$this->strLocation = $strUrl;
$fp = fsockopen ($url['host'], $url['port'], $errno, $errstr, 30);
// Return if the socket was not open $this->success is set to false.
if (!$fp)
return;
$header = 'GET / HTTP/1.1\r\n';
$header .= 'Host: '.$url['host'].$url['path'];
if (isset($url['query']))
$header .= '?'.$url['query'];
$header .= '\r\n';
$header .= 'Connection: Close\r\n\r\n';
// sending the request to the server
echo "Header is: <br />".str_replace('\n', '\n<br />', $header)."<br />";
$length = strlen($header);
if($length != fwrite($fp, $header, $length))
{
echo 'error writing to header, exiting<br />';
return;
}
// $bHeader is set to true while we receive the HTTP header
// and after the empty line (end of HTTP header) it's set to false.
$bHeader = true;
// continuing untill there's no more text to read from the socket
while (!feof($fp))
{
echo "in loop";
// reading a line of text from the socket
// not more than 8192 symbols.
$good = $strLine = fgets($fp, 128);
if(!$good)
{
echo 'bad';
return;
}
// removing trailing \n and \r characters.
$strLine = ereg_replace('[\r\n]', '', $strLine);
if ($bHeader == false)
$this->strFile .= $strLine.'\n';
else
$this->aHeaderLines[] = trim($strLine);
if (strlen($strLine) == 0)
$bHeader = false;
echo "read: $strLine<br />";
return;
}
echo "<br />after loop<br />";
fclose ($fp);
}
This is all I get:
Header is:
GET / HTTP/1.1\r\n
Host: www.google.com/\r\n
Connection: Close\r\n\r\n
in loopbad
So it fails the fgets($fp, 128);
Is there a reason you aren't using PHP's built-in, enabled-by-default ability to fetch remote files using fopen?
$remote_page = file_get_contents('http://www.google.com/'); // <- Works!
There are also plenty of high-quality third-party libraries, if you need to do something like fetch headers without thinking too hard. Try Zend_Http_Client on for size.
The flaw is here:
$good = $strLine = fgets($fp, 128);
if(!$good)
{
echo 'bad';
return;
}
fgets() returns either a string on success, or FALSE on failure. However, if there was no more data to be returned, fgets() will return the empty string (''). So, both $good and $strLine are set to the empty string, which PHP will happily cast to FALSE in the if() test. You should rewrite as follows:
$strLine = fgets($fp, 128);
if ($strLine === FALSE) { // strict comparison - types and values must match
echo 'bad';
return;
}
There's no need for the double assignment, as you can test $strLine directly.

PHP miniwebsever file download

$httpsock = #socket_create_listen("9090");
if (!$httpsock) {
print "Socket creation failed!\n";
exit;
}
while (1) {
$client = socket_accept($httpsock);
$input = trim(socket_read ($client, 4096));
$input = explode(" ", $input);
$input = $input[1];
$fileinfo = pathinfo($input);
switch ($fileinfo['extension']) {
default:
$mime = "text/html";
}
if ($input == "/") {
$input = "index.html";
}
$input = ".$input";
if (file_exists($input) && is_readable($input)) {
echo "Serving $input\n";
$contents = file_get_contents($input);
$output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents";
} else {
//$contents = "The file you requested doesn't exist. Sorry!";
//$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents";
function openfile()
{
$filename = "a.pl";
$file = fopen($filename, 'r');
$filesize = filesize($filename);
$buffer = fread($file, $filesize);
$array = array("Output"=>$buffer,"filesize"=>$filesize,"filename"=>$filename);
return $array;
}
$send = openfile();
$file = $send['filename'];
$filesize = $send['filesize'];
$output = 'HTTP/1.0 200 OK\r\n';
$output .= "Content-type: application/octet-stream\r\n";
$output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n';
$output .= "Content-Length:$filesize\r\n";
$output .= "Accept-Ranges: bytes\r\n";
$output .= "Cache-Control: private\n\n";
$output .= $send['Output'];
$output .= "Content-Transfer-Encoding: binary";
$output .= "Connection: Keep-Alive\r\n";
}
socket_write($client, $output);
socket_close ($client);
}
socket_close ($httpsock);
Hello, I am snikolov i am creating a miniwebserver with php and i would like to know how i can send the client a file to download with his browser such as firefox or internet explore i am sending a file to the user to download via sockets, but the cleint is not getting the filename and the information to download can you please help me here,if i declare the file again i get this error in my server
Fatal error: Cannot redeclare openfile() (previously declared in C:\User
s\fsfdsf\sfdsfsdf\httpd.php:31) in C:\Users\hfghfgh\hfghg\httpd.php on li
ne 29, if its possible, i would like to know if the webserver can show much banwdidth the user request via sockets, perl has the same option as php but its more hardcore than php i dont understand much about perl, i even saw that a miniwebserver can show much the client user pulls from the server would it be possible that you can assist me with this coding, i much aprreciate it thank you guys.
You are not sending the filename to the client, so how should it know which filename to use?
There is a drawback, you can provide the desired filename in the http header, but some browsers ignore that and always suggest the filename based on the last element in URL.
For example http://localhost/download.php?help.me would result in the sugested filename help.me in the file download dialogue.
see: http://en.wikipedia.org/wiki/List_of_HTTP_headers
Everytime you run your while (1) loop you declare openfile function. You can declare function only once. Try to move openfile declaration outside loop.
$httpsock = #socket_create_listen("9090");
if (!$httpsock) {
print "Socket creation failed!\n";
exit;
}
while (1) {
$client = socket_accept($httpsock);
$input = trim(socket_read ($client, 4096));
$input = explode(" ", $input);
$input = $input[1];
$fileinfo = pathinfo($input);
switch ($fileinfo['extension']) {
default:
$mime = "text/html";
}
if ($input == "/") {
$input = "index.html";
}
$input = ".$input";
if (file_exists($input) && is_readable($input)) {
echo "Serving $input\n";
$contents = file_get_contents($input);
$output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents";
} else {
//$contents = "The file you requested doesn't exist. Sorry!";
//$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents";
$filename = "dada";
$file = fopen($filename, 'r');
$filesize = filesize($filename);
$buffer = fread($file, $filesize);
$send = array("Output"=>$buffer,"filesize"=>$filesize,"filename"=>$filename);
$file = $send['filename'];
$output = 'HTTP/1.0 200 OK\r\n';
$output .= "Content-type: application/octet-stream\r\n";
$output .= "Content-Length: $filesize\r\n";
$output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n';
$output .= "Accept-Ranges: bytes\r\n";
$output .= "Cache-Control: private\n\n";
$output .= $send['Output'];
$output .= "Pragma: private\n\n";
// $output .= "Content-Transfer-Encoding: binary";
//$output .= "Connection: Keep-Alive\r\n";
}
socket_write($client, $output);
socket_close ($client);
}
socket_close ($httpsock);

Categories