I made a simple php code to test WebSocket, the client connects without problems, could receive data without probemas, but I can not send data from server to client, please correct my code to work, thanks
server.php
$in = '';
$content = '';
$connected = 0;
while($in != "quit"){
if(!$connected){
$in=trim(fgets(STDIN));
$pos = strpos($in, 'Sec-WebSocket-Key:');
if($pos !== false){
$key = str_replace('Sec-WebSocket-Key: ','',$in);
$magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$resp = shell_exec("echo -n $key$magic | openssl sha1 -binary | base64");
}
if($in == ""){
$head = "HTTP/1.1 101 Switching Protocols\r\n";
$head.= "Connection: Upgrade\r\n";
$head.= "Upgrade: websocket\r\n";
$head.= "Sec-WebSocket-Accept: $resp\r\n";
$head.= "\r\n";
echo $head;
$connected = 1;
}
}else{
sleep(3);
$hex = "810461626364"; //abcd
$byte = str_split($hex, 2);
$out = '';
foreach($byte as $b){
$out.= chr(hexdec($b));
}
echo $out;
}
}
type in terminal:
ncat -l 12345 -c 'php -q server.php'
and connect the client to localhost:12345
solved, it was not working because it had two line breaks after the response header, I changed this
$head.= "Sec-WebSocket-Accept: $resp\r\n";
$head.= "\r\n";
echo $head;
for this
$head.= "Sec-WebSocket-Accept: $resp\r\n";
echo $head;
and it worked.
Related
i have implemented a socket server in localhost
script i used is from http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket
script is
$host = "localhost"; //host
$port = 9099; //port
if(isset($argv[1]))
{
$host = $argv[1];
}
if(isset($argv[2]))
{
$port = $argv[2];
}
$null = NULL; //null var
$ips=array();
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//bind socket to specified host
socket_bind($socket, 0, $port);
//listen to port
socket_listen($socket);
//create & add listning socket to the list
$clients = array($socket);
$clients_ip=array();
//start endless loop, so that our script doesn't stop
while (true) {
//manage multipal connections
$changed = $clients;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accpet new socket
socket_getpeername($socket_new, $ip);
$clients[] = $socket_new; //add socket to client array
$clients_ip[$ip] = $socket_new;
$header = socket_read($socket_new, 1024); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
//get ip address of connected socket
$ips[]=$ip;
$response = mask(json_encode(array('ip'=>$ip,'type'=>'c', 'message'=>$ip.' connected','ips'=>$ips))); //prepare json data
send_message($response); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
//print_r($changed);exit;
if(count($changed)>0)
{
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
{
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text); //json decode
//$user_name = $tst_msg->name; //sender name
//$user_message = $tst_msg->message; //message text
//$user_color = $tst_msg->color; //color
//prepare data to be sent to clientjson_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color))
$response_text = mask($received_text);
if(isset($tst_msg->type))
{
if($tst_msg->type=="n")
{
#socket_write($clients_ip[$tst_msg->to_ip],$response_text,strlen($response_text));
}
}
//send_message($response_text); //send data
break 2; //exist this loop
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
if (($key = array_search($ip, $ips)) !== false)
{
unset($ips[$key]);
}
$ips=array_values($ips);
//notify all users about disconnected connection
$response = mask(json_encode(array('ip'=>$ip,'type'=>'d', 'message'=>$ip.' disconnected','ips'=>$ips)));
send_message($response);
}
}
}
}
// close the listening socket
socket_close($sock);
function send_message($msg)
{
global $clients;
foreach($clients as $changed_socket)
{
#socket_write($changed_socket,$msg,strlen($msg));
}
return true;
}
//Unmask incoming framed message
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/demo/shout.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));
}
i run this program in xampp shell like
php -q path-to-server\server.php
i have a server with shell support
But when i run script
php -q path-to-server\server.php
it works but when shell is closed server will close automatically
so how to run this server continuously with out automatically closing?
i have a linux hosting package
Use this code,
php -f server.php
if you want to run continusely in banground you can use nohub
nohup php server.php &
if want to kill the process you use kill
kill processid
you can run in terminal
php filename.php
I'm guessing you are connecting to the server by ssh?
The server session is ending and all open proccesses are killed that is why your server instance is ending, you are running it from a non-privileged user.
So the way I use is to install screen on the remote server and use that.
https://www.gnu.org/software/screen/manual/screen.html
Or it looks like you might be running a windows server. If this is the case I would recomend using a Linux server as windows makes this a little harder. You will have to run your server instance as a system proccess.
you should run this command as a background proccess like
nohup php -f myBind.php > /dev/null &
Also you can put a simple sccript to crontab for checking your bind.php is up or not if its not run it again.
I'm trying to connect a PHP-based client to a websocket server.
Here's the code I have been using which has been widely published on different forums. But for some reason I just cannot get it to work.
Any help would be appreciated.
$host = 'host'; //where is the websocket server
$port = 443; //ssl
$local = "http://www.example.com/"; //url where this script run
$data = '{"id": 2,"command": "server_info"}'; //data to be send
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: $local"."\r\n".
"Host: $host"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
////WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000); //receives the data included in the websocket package "\x00DATA\xff"
$retdata = trim($wsdata,"\x00\xff"); //extracts data
////WebSocket handshake
fclose($sock);
echo $retdata;
I would probably prefer to use an existing websocket client library (maybe https://github.com/gabrielbull/php-websocket-client or https://github.com/Devristo/phpws/tree/master/src/Devristo/Phpws/Client ?) rather than roll your own, but I got it to at least connect by using:
$head = "GET / HTTP/1.1"."\r\n".
"Host: $host"."\r\n".
"Upgrade: websocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
"Sec-WebSocket-Version: 13"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
My server is using TLS/SSL, so I also needed:
$sock = fsockopen('tls://'.$host, $port, $errno, $errstr, 2);
The full protocol spec is: https://tools.ietf.org/rfc/rfc6455.txt
UPDATE 2019: many servers requires the key to be more unique that the original example, resulting in failure to establish upgrade connection. The key generation is now changed accordingly.
Your header must contain:
Sec-WebSocket-Key: (some value)
Sec-WebSocket-Version: 13
to connect successfully.
When you have made the connection, you also need to use the hybi10 frame encoding.
See: https://tools.ietf.org/rfc/rfc6455.txt - Its a bit dry though.
I have made this working example:
<?php
$sp=websocket_open('127.0.0.1/ws_request.php?param=php_test',$errstr);
websocket_write($sp,"Websocket request message");
echo websocket_read($sp,true);
$sp=websocket_open('127.0.0.1:8080/ws_request.php?param=php_test',$errstr);
websocket_write($sp,"Websocket request message");
echo websocket_read($sp,true);
function websocket_open($url){
$key=base64_encode(openssl_random_pseudo_bytes(16));
$query=parse_url($url);
$header="GET / HTTP/1.1\r\n"
."pragma: no-cache\r\n"
."cache-control: no-cache\r\n"
."Upgrade: WebSocket\r\n"
."Connection: Upgrade\r\n"
."Sec-WebSocket-Key: $key\r\n"
."Sec-WebSocket-Version: 13\r\n"
."\r\n";
$sp=fsockopen($query['host'],$query['port'], $errno, $errstr,1);
if(!$sp) die("Unable to connect to server ".$url);
// Ask for connection upgrade to websocket
fwrite($sp,$header);
stream_set_timeout($sp,5);
$reaponse_header=fread($sp, 1024);
if(!strpos($reaponse_header," 101 ")
|| !strpos($reaponse_header,'Sec-WebSocket-Accept: ')){
die("Server did not accept to upgrade connection to websocket"
.$reaponse_header);
}
return $sp;
}
function websocket_write($sp, $data,$final=true){
// Assamble header: FINal 0x80 | Opcode 0x02
$header=chr(($final?0x80:0) | 0x02); // 0x02 binary
// Mask 0x80 | payload length (0-125)
if(strlen($data)<126) $header.=chr(0x80 | strlen($data));
elseif (strlen($data)<0xFFFF) $header.=chr(0x80 | 126) . pack("n",strlen($data));
elseif(PHP_INT_SIZE>4) // 64 bit
$header.=chr(0x80 | 127) . pack("Q",strlen($data));
else // 32 bit (pack Q dosen't work)
$header.=chr(0x80 | 127) . pack("N",0) . pack("N",strlen($data));
// Add mask
$mask=pack("N",rand(1,0x7FFFFFFF));
$header.=$mask;
// Mask application data.
for($i = 0; $i < strlen($data); $i++)
$data[$i]=chr(ord($data[$i]) ^ ord($mask[$i % 4]));
return fwrite($sp,$header.$data);
}
function websocket_read($sp,$wait_for_end=true,&$err=''){
$out_buffer="";
do{
// Read header
$header=fread($sp,2);
if(!$header) die("Reading header from websocket failed");
$opcode = ord($header[0]) & 0x0F;
$final = ord($header[0]) & 0x80;
$masked = ord($header[1]) & 0x80;
$payload_len = ord($header[1]) & 0x7F;
// Get payload length extensions
$ext_len = 0;
if($payload_len >= 0x7E){
$ext_len = 2;
if($payload_len == 0x7F) $ext_len = 8;
$ext=fread($sp,$ext_len);
if(!$ext) die("Reading header extension from websocket failed");
// Set extented paylod length
$payload_len= 0;
for($i=0;$i<$ext_len;$i++)
$payload_len += ord($header[$i]) << ($ext_len-$i-1)*8;
}
// Get Mask key
if($masked){
$mask=fread($sp,4);
if(!$mask) die("Reading header mask from websocket failed");
}
// Get payload
$frame_data='';
do{
$frame= fread($sp,$payload_len);
if(!$frame) die("Reading from websocket failed.");
$payload_len -= strlen($frame);
$frame_data.=$frame;
}while($payload_len>0);
// if opcode ping, reuse headers to send a pong and continue to read
if($opcode==9){
// Assamble header: FINal 0x80 | Opcode 0x02
$header[0]=chr(($final?0x80:0) | 0x0A); // 0x0A Pong
fwrite($sp,$header.$ext.$mask.$frame_data);
// Recieve and unmask data
}elseif($opcode<3){
$data="";
if($masked)
for ($i = 0; $i < $data_len; $i++)
$data.= $frame_data[$i] ^ $mask[$i % 4];
else
$data.= $frame_data;
$out_buffer.=$data;
}
// wait for Final
}while($wait_for_end && !$final);
return $out_buffer;
}
You can get the full version here: https://github.com/paragi/PHP-websocket-client
Connecting to a WSS stream with purely php:
Example with the public binance wss api.
<?php
$sock = stream_socket_client("tls://stream.binance.com:9443",$error,$errnum,30,STREAM_CLIENT_CONNECT,stream_context_create(null));
if (!$sock) {
echo "[$errnum] $error" . PHP_EOL;
} else {
echo "Connected - Do NOT get rekt!" . PHP_EOL;
fwrite($sock, "GET /stream?streams=btcusdt#kline_1m HTTP/1.1\r\nHost: stream.binance.com:9443\r\nAccept: */*\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ".rand(0,999)."\r\n\r\n");
while (!feof($sock)) {
var_dump(explode(",",fgets($sock, 512)));
}
}
More details: WebSockets - send json data via php
https://github.com/ratchetphp/Pawl
I tried around 10 different solutions from various stackoverflow threads but nothing worked, after spending about 6 hours trying different solution this worked for me.
scenario:
Ratchet as server
I was able to connect via reactjs
I wasn't able to connect via php,
Expected Result: To send message from php-client to all connected react clients. the git repo i provided was a lucky break i was looking for.
I tried the solution presented here and it works fine for me.
here are the details:
step1: Install the library from here with non-root user as follows:
php8.0 composer require textalk/websocket
then use the code below for sending some message to a socket which is located on localhost and has port number 8080:
<?php
require('vendor/autoload.php');
use WebSocket\Client;
$client = new Client("ws://127.0.0.1:8080");
$client->send($argv[1]);
?>
Since I had php7.1 webserver and the socket was installed with php8.0, I put the above code in a PHP file (testphp.php) and call it using shell_exec('php8.0 testphp.php hello');
The 400 error is because you're missing Host and Origin in the header.
$key=base64_encode(openssl_random_pseudo_bytes(16));
$query=parse_url($url);
$local = "http://".$query['host'];
if (isset($_SERVER['REMOTE_ADDR'])) $local = "http://".$_SERVER['REMOTE_ADDR'];
$header="GET / HTTP/1.1\r\n"
."Host: ".$query['host']."\r\n"
."Origin: ".$local."\r\n"
."Pragma: no-cache\r\n"
."Cache-Control: no-cache\r\n"
."Upgrade: websocket\r\n"
."Connection: Upgrade\r\n"
."Sec-WebSocket-Key: $key\r\n"
."Sec-WebSocket-Version: 13\r\n"
."\r\n";
This is likely a familiar sob story. But there are so many of them out there, and I'm such a n00b I can't find the answer, so I'd like your help if you can help me.
So, I'm using phpwebsocket by lemmingzshadow (google brings this up pretty easily if you are unfamiliar). As far as I can tell the version he has out has a bug where it doesn't follow the standards that Chrome 20.+ now uses. Its got something to do with the hand shake & security keys but that's where I'm stuck at. I know I need to provide the following based on other questions, hopefully you can help me understand and fix this issue:
The header Chrome receives is (Edited; I apparently posted the message to the server twice.):
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: aWXrpLOnEm15mE8+w1zG05ad01k=
Sec-WebSocket-Protocol: QuatroDuo
The header my server receives is:
Upgrade: websocket
Connection: Upgrade
Host: gumonshoe.net:8000
Origin: http://gumonshoe.net
Sec-WebSocket-Key: v3+iw0U78qkwZnp+RWTu3A
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
I don't think the cookies are necessary, correct me if I'm wrong though.
I hate to do this next part, but I figure pasting it all is better than doing nothing and needing to come back later. Here is the portion of code that reads & interprets the handshake and sends the new one.
Help is appreaciated:
<?PHP
private function handshake($data)
{
$this->log('Performing handshake\r\n\r\n' . $data);
$lines = preg_split("/\r\n/", $data);
// check for valid http-header:
if(!preg_match('/\AGET (\S+) HTTP\/1.1\z/', $lines[0], $matches)) {
$this->log('Invalid request: ' . $lines[0]);
$this->sendHttpResponse(400);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
return false;
}
// check for valid application:
$path = $matches[1];
$this->application = $this->server->getApplication(substr($path, 1));
if(!$this->application) {
$this->log('Invalid application: ' . $path);
$this->sendHttpResponse(404);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
// generate headers array:
$headers = array();
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
// check for supported websocket version:
if(!isset($headers['Sec-WebSocket-Version']) || $headers['Sec-WebSocket-Version'] < 6)
{
$this->log('Unsupported websocket version.');
$this->sendHttpResponse(501);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
// check origin:
if($this->server->getCheckOrigin() === true)
{
$origin = (isset($headers['Sec-WebSocket-Origin'])) ? $headers['Sec-WebSocket-Origin'] : false;
$origin = (isset($headers['Origin'])) ? $headers['Origin'] : $origin;
if($origin === false)
{
$this->log('No origin provided.');
$this->sendHttpResponse(401);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
if(empty($origin))
{
$this->log('Empty origin provided.');
$this->sendHttpResponse(401);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
if($this->server->checkOrigin($origin) === false)
{
$this->log('Invalid origin provided. : ' . $origin . ' Legal options were:');
$gumk = 0;
foreach(array_keys($this->server->getAllowedOrigins()) as $lo) {
$this->log( '[' . $gumk++ . '] : ' . $lo);
}
$this->sendHttpResponse(401);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
}
// do handyshake: (hybi-10)
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$response = "HTTP/1.1 101 Switching Protocols\r\n";
$response.= "Upgrade: websocket\r\n";
$response.= "Connection: Upgrade\r\n";
$response.= "Sec-WebSocket-Accept: " . $secAccept . "\r\n";
$response.= "Sec-WebSocket-Protocol: " . substr($path, 1) . "\r\n\r\n";
if(false === ($this->server->writeBuffer($this->socket, $response)))
{
return false;
}
$this->handshaked = true;
$this->log('Handshake sent');
$this->application->onConnect($this);
// trigger status application:
if($this->server->getApplication('status') !== false)
{
$this->server->getApplication('status')->clientConnected($this->ip, $this->port);
}
return true;
}
Receiving the following error,
Error during WebSocket handshake: Sec-WebSocket-Protocol mismatch
As I'm largely inexperienced in this level of server debugging, a more detailed answer than linking me to documentation/specifications would be appreciated.
If any of you are beating your head against a wall, this is the offending piece of code:
$response.= "Sec-WebSocket-Protocol: " . substr($path, 1) .
I am sure there is a way to actually set the desired/possible protocols, but I'm not sure yet what they are; and I'm not sure if its necessary for my purposes. If someone has an explanation of what the protocol switching is even for, I'd love to read it, but for now I'm just taking it out of my code.
Lots of googling to find this small problem.
I also dumped the pack(H*) code in the handshake which didn't seem to be necessary based on what I was reading. I'm not sure if that did anything or not, but it wasn't necessary to get the program to work.
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.
$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);