Socket TimeOut Issue in Laravel - php

I am connecting my website to a server having an application in VB6. I connect to an IP on a specified port using PHP. My code is as follows:
public static function hello()
{
static::$version = Config::get('socket.version');
static::$user = Config::get('socket.user');
static::$pwd = Config::get('socket.password');
$xmlstr = '<?xml version="1.0"?>';
$xmlstr .= '<HelloRequest version="' . static::$version . '" user="' . static::$user . '" pwd="' . static::$pwd . '" />';
//$xmlstr = '|'.strlen($xmlstr).'|'.$xmlstr; // Appending Length
return static::runRequest($xmlstr);
}
and it calls runRequest($xmlstr) method in the same class:
public static function runRequest($request)
{
static::$address = Config::get('socket.address');
static::$port = Config::get('socket.port');
static::$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!static::$socket) {
return (object) array(
'error' => true,
'message' => "socket_create() failed: reason: " . socket_strerror(socket_last_error())
);
}
socket_set_option(static::$socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0));
$result = socket_connect(static::$socket, static::$address, static::$port);
if (!$result) {
static::close();
return (object) array(
'error' => true,
'message' => "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error(static::$socket))
);
}
$bytes = socket_send(static::$socket, $request, strlen($request), 0);
if ($bytes > 0) {
$buf = " ";
$totalBytes = 0;
$outbuf = "";
$maxlen = 4096;
$loopcnt = 0;
$maxloops = 100;
while (true) {
$receivedBytes = socket_recv(static::$socket, $buf, $maxlen, 0);
if ($receivedBytes > 0) {
$buf = str_replace("&", "&", $buf);
$outbuf .= $buf;
$totalBytes += $receivedBytes;
if(strrpos($outbuf, "\r\n") == true)
break;
}
$loopcnt++;
}
$outbuf = str_replace("\r\n", "", $outbuf);
socket_close(static::$socket);
return (object) array(
'error' => false,
'message' => $outbuf
);
}
socket_close(static::$socket);
return (object) array(
'error' => true,
'message' => 'Something went wrong. Please try again.'
);
}
PROBLEM IS THAT THE CODE STUCKS at:
$receivedBytes = socket_recv(static::$socket, $buf, $maxlen, 0);
and returns 500 internal Server Error in Page Title and Request Time out on Page:
Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'.
Any Clue on it what might be wrong. Username/Paswords, IP and ports are correct, tested using putty.
We are using litespeed server (not apache). Here are the logs for the event:
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] Connection idle time: 121 while in state: 6 watching for event: 25,close!
2015-06-15 17:46:35.201 [NOTICE] [ip.address.removed:62539:HTTP2-1] Content len: 0, Request line: 'GET /socket/hello HTTP/1.1'
2015-06-15 17:46:35.201 [NOTICE] [ip.address.removed:62539:HTTP2-1] Redirect: #1, URL: /index.php/socket/hello
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] HttpExtConnector state: 8, request body sent: 0, response body size: -2, response body sent:0, left in buffer: 0, attempts: 0.
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] Lsapi connection state: 3, watching event: 25, respState: 1, m_iTotalPending:0, m_iPacketLeft:0, m_iCurRespHeader:791624304, req sent for 121 seconds,Total processing time: 121.
2015-06-15 17:46:35.201 [INFO] [ip.address.removed:62539:HTTP2-1] Abort request processing by PID:4736, kill: 1, begin time: 121, sent time: 121, req processed: 0

Related

stream_socket_client with TLS 1.2

I'm trying to create a connection between the client and the server (with 2-way TLS).
Client.php
$stream_context = stream_context_create(['ssl' => [
'local_cert' => "path/to/cer.pem",
'verify_peer' => true,
'verify_peer_name' => false,
'passphrase' => "password to cert",
'verify_depth' => 0
]]);
$socket = stream_socket_client("tlsv1.2://127.0.0.1:8000", $errno, $errstr, 3, STREAM_CLIENT_CONNECT, $stream_context);
if ($socket === false) {
return false;
}
$req = "POST /Serwer.php HTTP/1.1\r\n" .
"Content-Type: text/xml;charset=UTF-8\r\n" .
"Host: 127.0.0.1\r\n" .
"Connection: Close\r\n" .
"Hello world!\r\n";
$start = time();
fwrite($socket, $req);
$resp = '';
while (!feof($socket)) {
if (time() - $start > 15) {
break;
}
$f = fgets($socket);
$resp .= $f;
}
fclose($socket);
echo $resp;
Server.php
$stream_context = stream_context_create(['ssl' => [
'local_cert' => "path/to/cert.pem",
'passphrase' => "password to cert",
'allow_self_signed' => true,
'verify_peer' => true
]]);
$server = stream_socket_server("tlsv1.2://0.0.0.0:8000",$errno, $error, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $stream_context);
if ($server === false) {
return false;
}
$connects = array();
while (true) {
$read = $connects;
$read []= $server;
$write = $except = null;
$mod_fd = stream_select($read, $write, $except, 3); // return always 0, I don't know why
if ($mod_fd === false) {
break;
}
if (in_array($server, $read)) {
$connect = stream_socket_accept($server, -1);
$connects[] = $connect;
unset($read[ array_search($server, $read) ]);
}
foreach($read as $connect) {
$headers = '';
while ($buffer = rtrim(fgets($connect))) {
$headers .= $buffer;
}
fwrite($connect, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\nHello!");
fclose($connect);
unset($connects[ array_search($connect, $connects) ]);
}
fclose($server);
In this example server and client are on different machines.
I must to use TLS v 1.2.
Address and port on the client and the server must be the same or different? (For example in server.php I use address 0.0.0.0 and port 8000, but in client.php 127.0.0.1 and port 8000)
How the server and the client must accept the certificates TLS?
How read on server side phrase "Hello world" from client?

can not read serial port using php or nodejs

I have tried to read serial port data sending with arduino by php or nodejs and I couldn't. I think my codes are correct. I think the problem is permission access reading serial port limited by windows or browser but i'm not sure. although the software of arduino can read data.
when I run my codes, arduio sends data over and over but nothing to show data.
can you help me?!
Here my php codes:
<?php
//-- settings --//
//brainboxes serial ports
$portName = "COM5";
$baudRate = 9600;
$bits = 8;
$spotBit = 1;
header( 'Content-type: text/plain; charset=utf-8' );
?>
Serial Port Test
================
<?php
function echoFlush($string)
{
echo $string . "\n";
flush();
ob_flush();
}
if(!extension_loaded('dio'))
{
echoFlush( "PHP Direct IO does not appear to be installed for more info see: http://www.php.net/manual/en/book.dio.php" );
exit;
}
try
{
//the serial port resource
$bbSerialPort;
echoFlush( "Connecting to serial port: {$portName}" );
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
$bbSerialPort = dio_open($portName, O_RDWR );
//we're on windows configure com port from command line
exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
}
else //'nix
{
$bbSerialPort = dio_open($portName, O_RDWR | O_NOCTTY | O_NONBLOCK );
dio_fcntl($bbSerialPort, F_SETFL, O_SYNC);
//we're on 'nix configure com from php direct io function
dio_tcsetattr($bbSerialPort, array(
'baud' => $baudRate,
'bits' => $bits,
'stop' => $spotBit,
'parity' => 0
));
}
if(!$bbSerialPort)
{
echoFlush( "Could not open Serial port {$portName} ");
exit;
}
// send data
$dataToSend = "HELLO WORLD!";
echoFlush( "Writing to serial port data: \"{$dataToSend}\"" );
$bytesSent = dio_write($bbSerialPort, $dataToSend );
echoFlush( "Sent: {$bytesSent} bytes" );
//date_default_timezone_set ("Europe/London");
$runForSeconds = new DateInterval("PT10S"); //10 seconds
$endTime = (new DateTime())->add($runForSeconds);
echoFlush( "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );
while (new DateTime() < $endTime) {
$data = dio_read($bbSerialPort, 256); //this is a blocking call
if ($data) {
echoFlush( "Data Recieved: ". $data );
}
}
echoFlush( "Closing Port" );
dio_close($bbSerialPort);
}
catch (Exception $e)
{
echoFlush( $e->getMessage() );
exit(1);
}
?>
Error in php:
"Warning: dio_open(): cannot open file COM5 with flags 2 and permissions 0: Permission denied in C:\xampp\htdocs\serialreading\SerialPortTest.php on line 42
Could not open Serial port COM5"
Here my nodejs codes:
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM5');
const parser = usbport.pipe(new Readline());
parser.on('data', function (data) {
io.emit('data', { data: data });
});
Error in nodejs:
"Could Not get"

Socket.io/ PHP server side

I use socket.io for socket app in my client side. For the server I use socket library of PHP.
After the handsake, the connection was closed and generated a warning
failed: WebSocket is closed before the connection is established.
socket_getsockname($socket_server, $addr, $port);
while($socket = socket_accept($socket_server)) {
$handshake = false;
if(!$socket){
print "error \n";
}
socket_getpeername($socket, $raddr, $rport);
$msg = "Welcome aboard !";
$length = strlen($msg);
print socket_read ( $socket , 255 )."\n";
$error = socket_last_error($socket);
$error_message = socket_strerror($error);
if(!$handshake){
$bytes = socket_recv($socket,$buffer,2048,0);
list($resource,$host,$origin,$key,$key1,$key2,$l8b) = getheaders($buffer);
$accept = base64_encode(SHA1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
$upgrade = "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" .
"Upgrade: WebSocket\r\n" .
"Connection: Upgrade\r\n" .
"Sec-WebSocket-Origin: " . $origin . "\r\n" .
"Sec-WebSocket-Location: ws://" . $host . $resource . "\r\n" .
"Sec-WebSocket-Accept: " . $accept . "\r\n\r\n";
if(socket_write($socket,$upgrade.chr(0),strlen($upgrade.chr(0)))) {
$handshake = true;
}
}
else{
if(socket_write ( $socket , $msg,$length)){
print "Mesg envoyee \n";
}
}
do{
$read = socket_read($socket, 1080);
print $read."\n";
if(socket_write ( $socket , $msg,$length)){
print "Mesg envoyee \n";
}
} while ($read != '');
in my server side in PHP
in my client :
var socket = io('http://localhost:4454',{
agent: false,
transports: ['websocket']
});
console.log(socket);
socket.on('connect', () => {
socket.send('hi');
console.log(socket);
});
socket.emit('foo');
socket.on('message', (data) => {
console.log(data);
console.log(socket);
});
socket.on('data', (data) => {
console.log(data);
});
socket.on('error', (error) => {
console.log(error);
});
//blocage des reconnection si erreurs
var attemp = 5;
socket.on('reconnecting', (attemp) => {
console.log("I'm sad :(");
//socket.close();
});
I don't find any solution for this issue.
I don't understand why in localhost stream was automatically close.
Server side looked fine, in this time...

Unable to setup COM port, check it is correct

I am sending sms using Nokia usb Device and PHP script but getting error
many answer are there on stack but no answer has solution of this problem
Fatal error: Uncaught Exception: Unable to setup COM port, check it is correct in C:\xampp\htdocs\sms-prac\send-sms.php:103
Stack trace:
#0 C:\xampp\htdocs\sms-prac\send-sms.php(36): gsm_send_sms->init()
#1 {main}
thrown in C:\xampp\htdocs\sms-prac\send-sms.php on line 103
My gsm_send_sms Class Code
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM1';
public $baud = 115200;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of messgage sent');
$this->debugmsg('Did not receive confirmation of messgage sent');
return false;
}
$this->debugmsg("Message sent");
return true;
}
}
My PHP Code which i am using to send SMS
<?php
//SMS via GSM Modem - A PHP class to send SMS messages via a GSM modem attached to the computers serial port.
//Windows only (tested on XP with PHP 5.2.6)
//Tested with the EZ863 (Telit GE863) GSM modem
//Requires that PHP has permission to access "COM" system device, and system "mode" command
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
//Example
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "MembersManagmentSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Member.memberId, Member.memberContactMobileNumber, SMSRecipient.smsRecipientReceiverId, SMSRecipient.smsInfoId, SMSInfo.smsInfoText, SMSInfo.`smsInfoSaveDateTime` FROM Member, SMSRecipient,SMSInfo WHERE SMSRecipient.`smsRecipientReceiverId` = Member.`memberId` AND SMSRecipient.`smsInfoId`= SMSInfo.`smsInfoId` AND SMSRecipient.smsRecipientSentDateTime IS NULL AND Member.`memberContactMobileNumber` IS NOT NULL AND SMSInfo.`smsInfoSaveDateTime` > DATE_SUB(NOW(), INTERVAL 1 DAY)";
$result = $conn->query($sql);
echo "<pre>";
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM3';
$gsm_send_sms->baud = 115200;
$gsm_send_sms->init();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r($row);
$status = $gsm_send_sms->send($row['memberContactMobileNumber'], $row['smsInfoText']);
if ($status) {
$sql = "UPDATE SMSRecipient SET smsRecipientSentDateTime = now() WHERE smsInfoId = ".$row['smsInfoId']." and smsRecipientReceiverId = ".$row['memberId'];
if ($conn->query($sql) === TRUE) {
echo "Message sent\n";
}
} else {
echo "Message not sent\n";
}
}
//exit();
} else {
echo "0 results";
}
$gsm_send_sms->close();
$conn->close();
?>
on change $gsm_send_sms->debug = false; to true, get
Array
(
[0] =>
[1] => Status for device COM3:
[2] => -----------------------
[3] => Baud: 115200
[4] => Parity: None
[5] => Data Bits: 8
[6] => Stop Bits: 1
[7] => Timeout: OFF
[8] => XON/XOFF: OFF
[9] => CTS handshaking: OFF
[10] => DSR handshaking: OFF
[11] => DSR sensitivity: OFF
[12] => DTR circuit: ON
[13] => RTS circuit: ON
[14] =>
)
After Debug above Code I found that when i first time connect my device and run it php executing this line as like as infinity loop and before this line all debugmsg and other code running fine please help me
$buffer = fread($this->fp, 8192);

stream_socket_client - php_network_getaddresses: getaddrinfo failed: Name or service not known

function drupal_http_request($url, array $options = array()) {
// Allow an alternate HTTP client library to replace Drupal's default
// implementation.
$override_function = variable_get('drupal_http_request_function', FALSE);
if (!empty($override_function) && function_exists($override_function)) {
return $override_function($url, $options);
}
$result = new stdClass();
// Parse the URL and make sure we can handle the schema.
$uri = #parse_url($url);
if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}
if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}
timer_start(__FUNCTION__);
// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);
// Merge the default headers.
$options['headers'] += array(
'User-Agent' => 'Drupal (+http://drupal.org/)',
);
// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];
// Use a proxy if one is defined and the host is not on the excluded list.
$proxy_server = variable_get('proxy_server', '');
if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
// Set the scheme so we open a socket to the proxy server.
$uri['scheme'] = 'proxy';
// Set the path to be the full URL.
$uri['path'] = $url;
// Since the URL is passed as the path, we won't use the parsed query.
unset($uri['query']);
// Add in username and password to Proxy-Authorization header if needed.
if ($proxy_username = variable_get('proxy_username', '')) {
$proxy_password = variable_get('proxy_password', '');
$options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
}
// Some proxies reject requests with any User-Agent headers, while others
// require a specific one.
$proxy_user_agent = variable_get('proxy_user_agent', '');
// The default value matches neither condition.
if ($proxy_user_agent === NULL) {
unset($options['headers']['User-Agent']);
}
elseif ($proxy_user_agent) {
$options['headers']['User-Agent'] = $proxy_user_agent;
}
}
switch ($uri['scheme']) {
case 'proxy':
// Make the socket connection to a proxy server.
$socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
// The Host header still needs to match the real request.
$options['headers']['Host'] = $uri['host'];
$options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
break;
case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;
case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;
default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}
if (empty($options['context'])) {
$fp = #stream_socket_client($socket, $errno, $errstr, $options['timeout']);
}
else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = #stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}
var_dump($fp);
// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr) ? trim($errstr) : t('Error opening socket #socket', array('#socket' => $socket));
print_r($result);
exit();
// Mark that this request failed. This will trigger a check of the web
// server's ability to make outgoing HTTP requests the next time that
// requirements checking is performed.
// See system_requirements().
variable_set('drupal_http_request_fails', TRUE);
return $result;
}
// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}
// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}
// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
}
// If the database prefix is being used by SimpleTest to run the tests in a copied
// database then set the user-agent header to the database prefix so that any
// calls to other Drupal pages will run the SimpleTest prefixed database. The
// user-agent is used to ensure that multiple testing sessions running at the
// same time won't interfere with each other as they would if the database
// prefix were stored statically in a file or database variable.
$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['test_run_id'])) {
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
}
$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}
// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';
while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);
if ($info['timed_out']) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);
// Parse the response status line.
$response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
$result->protocol = $response_status_array['http_version'];
$result->status_message = $response_status_array['reason_phrase'];
$code = $response_status_array['response_code'];
$result->headers = array();
// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
}
else {
$result->headers[$name] = trim($value);
}
}
$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;
switch ($code) {
case 200: // OK
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['location'];
$options['timeout'] -= timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
}
elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects']--;
$result = drupal_http_request($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $result->status_message;
}
return $result;
}
I'm getting the below mentioned message by doing var_dump of $fp as mentioned above on my VM machine hosted with Ubuntu 14.04
stdClass Object
(
[code] => 0
[error] => php_network_getaddresses: getaddrinfo failed: Name or service not known
)
When I'm implementing the same thing on my localhost which is XAMPP based in Windows 7 I'm getting this:
Resource id #8
Due to this I'm unable to use the drupal_http_request
As per your suggestion I've tried dns_get_record()
$dns_get_record = dns_get_record("www.google.com");
print_r($dns_get_record);
and got this as the output:
Array
(
[0] => Array
(
[host] => www.google.com
[class] => IN
[ttl] => 243
[type] => A
[ip] => 216.58.220.4
)
[1] => Array
(
[host] => www.google.com
[class] => IN
[ttl] => 257
[type] => AAAA
[ipv6] => 2404:6800:4009:805::2004
)
)
I've also checked the stream_socket_client()
var_dump(stream_socket_client());
and it returned me bool(false)
Since you've not put any proper error handling in the code, we can't tell which function is being executed. You haven't provided the parameters you are passing, so we can't tell what the cause is, but the most likely issue is that you are trying to establish a network connection and the host where the code is running is unable to resolve the hostname inside $socket.
You can very this with dns_get_record() or speak to your hosting provider.

Categories