How do I pass session to new socket via fsockopen? - php

I need to pass the session to an asynchronous call via fsockopen in php.
Can you help me pass the session to the new socket?
SOLUTION:
The following code works.
start.php
<?php
session_start();
$_SESSION['var1'] = 'value1';
async_call('/async.php');
echo '<pre>';
print_r($_SESSION);
echo $_COOKIE['PHPSESSID'] . "\r\n";
echo 'verify.php';
function async_call($filepath) {
$host = 'sandbox'; // set to your domain
$sock = fsockopen($host, 80);
fwrite($sock, "GET $filepath HTTP/1.1\r\n");
fwrite($sock, "Host: $host\r\n");
fwrite($sock, "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n");
fwrite($sock, "Connection: close\r\n");
fwrite($sock, "\r\n");
fflush($sock);
fclose($sock);
}
?>
async.php
<?php
session_start();
logger('confirm logger is working');
logger($_SESSION); // this is always blank!
function logger($msg) {
$filename = 'debug.log';
$fd = fopen($filename, "a");
if (is_array($msg))
$msg = json_encode($msg);
$msg = '[' . date('Y/m/d h:i:s', time()) . "]\t" . $msg;
fwrite($fd, $msg . "\n");
fclose($fd);
}
?>
verify.php
<?php
$logfile = 'debug.log';
echo 'start.php';
echo '<pre>' . file_get_contents($logfile);
?>
I could get this working locally, but it turned out the shared host I was staging on disallowed fsockopen without any documentation. All good on my own servers. Thanks for the help.

Thanks for the help, Andreas. Turns out the shared host I was staging on disallowed fsockopen without any documentation. That's why I could get it working locally but not on the staging server.
The following code works.
start.php
<?php
session_start();
$_SESSION['var1'] = 'value1';
async_call('/async.php');
echo '<pre>';
print_r($_SESSION);
echo $_COOKIE['PHPSESSID'] . "\r\n";
echo 'verify.php';
function async_call($filepath) {
$host = 'sandbox'; // set to your domain
$sock = fsockopen($host, 80);
fwrite($sock, "GET $filepath HTTP/1.1\r\n");
fwrite($sock, "Host: $host\r\n");
fwrite($sock, "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n");
fwrite($sock, "Connection: close\r\n");
fwrite($sock, "\r\n");
fflush($sock);
fclose($sock);
}
?>
async.php
<?php
session_start();
logger('confirm logger is working');
logger($_SESSION); // this is always blank!
function logger($msg) {
$filename = 'debug.log';
$fd = fopen($filename, "a");
if (is_array($msg))
$msg = json_encode($msg);
$msg = '[' . date('Y/m/d h:i:s', time()) . "]\t" . $msg;
fwrite($fd, $msg . "\n");
fclose($fd);
}
?>
verify.php
<?php
$logfile = 'debug.log';
echo 'start.php';
echo '<pre>' . file_get_contents($logfile);
?>

Related

(PHP) tcp socket over proxy

I connect to the Minecraft server via tcp, how do I use a proxy server
I know how to use a proxy for HTTP requests, but I don’t really understand how to do it for TCP
$data = "\x00";
$data .= makeVarInt($proto);
$data .= pack('c', strlen($ip)) . $ip;
$data .= pack('n', $port);
$data .= "\x02";
$handshake = pack('c', strlen($data)) . $data;
$nick = generateRandomString(5)."_RAGE_". generateRandomString(5);
//Create TCP socket
$socket = #stream_socket_client("tcp://$ip:$port", $errno, $errstr, 10);
//Check for errors
if ($errno > 0) {
echo "ERROR: " . $errstr . PHP_EOL;
continue;
}
//Send login handshake packet
fwrite($socket, $handshake);
//Make login start packet
$data = "\x00";
$data .= pack('c', strlen($nick)) . $nick;
$data = pack('c', strlen($data)) . $data;
//Send login start packet
fwrite($socket, $data);

How do I implement proxy authentication with fsockopen in PHP?

I want to use a proxy with authentication to my below code to communicate and get data from whois servers.
My code is as follows:
$whoisserver = "whois.verisign-grs.com";
$port = 43;
$timeout = 10;
$fp = #fsockopen($whoisserver, $port, $errno, $errstr, $timeout) or die("Socket Error " . $errno . " - " . $errstr);
fputs($fp, $domain . "\r\n");
$out = "";
while(!feof($fp)){
$out .= fgets($fp);
}
fclose($fp);
In the above I want to use a username and password to authenticate my proxy.
What do I change in the code above to achieve my desired outcome?

ozeki NG fsockopen(): unable to connect to 197.XXX.XXX.XX:9501 (Connection timed out)

i am working to send sms with ozeki NG and PHP, and i can send SMS from localhost but when i upload it on cpanel it says "fsockopen(): unable to connect to 197.XXX.XXX.XX:9501 (Connection timed out)"
IS THEIR ANY ONE WHO COULD HELP ME...thanks in advance...
$ozeki_user = "xxxx";
$ozeki_password = "xxxx";
$ozeki_url = "http://197.xxx.xxx.xxx:9501/api?";
function httpRequest($url){
$pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
preg_match($pattern,$url,$args);
$in = "";
$fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
if (!$fp) {
return("$errstr ($errno)");
} else {
$out = "GET /$args[3] HTTP/1.1\r\n";
$out .= "Host: $args[1]:$args[2]\r\n";
$out .= "User-agent: Ozeki PHP client\r\n";
$out .= "Accept: */*\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
$in.=fgets($fp, 128);
}
}
fclose($fp);
return($in);
}
function ozekiSend($phone, $msg, $debug=true){
global $ozeki_user,$ozeki_password,$ozeki_url;
$url = 'username='.$ozeki_user;
$url.= '&password='.$ozeki_password;
$url.= '&action=sendmessage';
$url.= '&messagetype=SMS:TEXT:UCS2';
$url.= '&recipient='.urlencode($phone);
$url.= '&messagedata='.urlencode($msg);
//$url.= '&messagedata='.urlencode($msg);
$urltouse = $ozeki_url.$url;
if ($debug) { echo "Request: <br>$urltouse<br><br>"; }
//Open the URL to send the message
$response = httpRequest($urltouse);
if ($debug) {
echo "Response: <br><pre>".
str_replace(array("<",">"),array("<",">"),$response).
"</pre><br>"; }
return($response);
}
$phonenum = $_POST['recipient'];
$message = $_POST['message'];
$debug = true;
ozekiSend($phonenum,$message,$debug);
?>

PHP Cache issue when posting data using fsockopen

I am using Mailchimp api 1.3 php wrapper. The problem is that a server where my customer hosts a site will cache response, it won't even make api call. The exact the same code works with me and other customers:
$api = new MCAPI($apiKey);
$doubleOptin = false;
$mergeVar = array(
'FNAME' => '',
'LNAME' => ''
);
$api->listSubscribe($listId, $email, $mergeVar, 'html', $doubleOptin);
print_r($api);
method listSubscribe() calls method callServer where I guess is the problem:
$payload = "POST " . $this->apiUrl["path"] . "?" . $this->apiUrl["query"] . "&method=" . $method . " HTTP/1.0\r\n";
$payload .= "Host: " . $host . "\r\n";
$payload .= "User-Agent: MCAPI/" . $this->version ."\r\n";
$payload .= "Content-type: application/x-www-form-urlencoded\r\n";
$payload .= "Content-length: " . strlen($post_vars) . "\r\n";
$payload .= "Connection: close \r\n\r\n";
$payload .= $post_vars;
ob_start();
if ($this->secure){
$sock = fsockopen("ssl://".$host, 443, $errno, $errstr, 30);
} else {
$sock = fsockopen($host, 80, $errno, $errstr, 30);
}
if(!$sock) {
$this->errorMessage = "Could not connect (ERR $errno: $errstr)";
$this->errorCode = "-99";
ob_end_clean();
return false;
}
$response = "";
fwrite($sock, $payload);
stream_set_timeout($sock, $this->timeout);
$info = stream_get_meta_data($sock);
while ((!feof($sock)) && (!$info["timed_out"])) {
$response .= fread($sock, $this->chunkSize);
$info = stream_get_meta_data($sock);
}
var_dump($response); exit;
Does anybody have any idea why fsockopen and fwrite never sends call to Mailchimp? Weird thing is that I can actually read $response, but it is always the same from cache.
If the code works for you and there is some query caching then you could try to add a timestamp to the request.
"&time=".time()
This way you always have a "fresh" request.

How to send SMS on multiple numbers stored in database

This is my code and I am using as external file include in my code as external file. When new user post this code is run but not sent message on all numbers that stored in database:
Error is:
Warning: fsockopen() [function.fsockopen]: unable to connect to :0
(Failed to parse address "") in C:\xampp\htdocs\funsmss\location\sendsms.php
Failed to parse address "" (0)
Here's the code:
<?php
$sql = "select * from subscribe where type ='$cat' and city ='$city'";
$query = mysql_query($sql);
if ($query != null) {
while ($row = mysql_fetch_array($query)) {
$name = $row['name'];
$phoneNum = $row['fone'];
$message = "Hi ".$name.", now you can buy your product.";
ozekiSend($phoneNum, $message);
// for debugging, try the following line
//echo ozekiSend($phoneNum, $message, true);
}
}
########################################################
# Login information for the SMS Gateway
########################################################
$ozeki_user = "admin";
$ozeki_password = "abc123";
$ozeki_url = "http://127.0.0.1:9501/api?";
########################################################
# Functions used to send the SMS message
########################################################
function httpRequest($url)
{
$pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
preg_match($pattern, $url, $args);
$in = "";
$fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
if (!$fp) {
return("$errstr ($errno)");
} else {
$out = "GET /$args[3] HTTP/1.1\r\n";
$out .= "Host: $args[1]:$args[2]\r\n";
$out .= "User-agent: Ozeki PHP client\r\n";
$out .= "Accept: */*\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
$in.=fgets($fp, 128);
}
}
fclose($fp);
return($in);
}
function ozekiSend($phone, $msg, $debug = false)
{
global $ozeki_user, $ozeki_password, $ozeki_url;
$url = 'username=' . $ozeki_user;
$url.= '&password=' . $ozeki_password;
$url.= '&action=sendmessage';
$url.= '&messagetype=SMS:TEXT';
$url.= '&recipient=' . urlencode($phone);
$url.= '&messagedata=' . urlencode($msg);
$urltouse = $ozeki_url . $url;
if ($debug === true) {
echo "Request: <br>$urltouse<br><br>";
}
//Open the URL to send the message
$response = httpRequest($urltouse);
if ($debug === true) {
echo "Response: <br><pre>" .
str_replace(array("<", ">"), array("<", ">"), $response) .
"</pre><br>";
}
return($response);
}
?>

Categories