PHP Cache issue when posting data using fsockopen - php

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.

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);

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);
?>

How can I send data/text from PHP using WebSocket to process?

I have process on server which acts as WebSocket server (not written in Ratchet). I want to be able to send data to this process using PHP (as client).
I found a lot of examples to send as TCP like this:
<?php
$addr = gethostbyname("localhost");
$client = stream_socket_client("tcp://$addr:8887", $errno, $errorMessage);
if ($client === false) {
throw new UnexpectedValueException("Failed to connect: $errorMessage");
}
fwrite($client, "GET / HTTP/1.0\r\nHost: localhost\r\nAccept: */*\r\n\r\n");
echo stream_get_contents($client);
?>
All I need I to send message to the process and close the connection. The result that I expect is the result from the webSocket will be later printed or "echo" to the PHP page.
Is there a way to make it work with curl in php?
I have found this code on github, (I can't find the exact repo where I got it from because I have looked and tried a lot of them)
<?php
class WebsocketClient {
private $_Socket = null;
public function __construct($host, $port) {
$this->_connect($host, $port);
}
public function __destruct() {
$this->_disconnect();
}
public function sendData($data) {
// send actual data:
fwrite($this->_Socket, "\x00" . $data . "\xff") or die('Error:' . $errno . ':' . $errstr);
$wsData = fread($this->_Socket, 2000);
$retData = trim($wsData, "\x00\xff");
return $retData;
}
private function _connect($host, $port) {
$key1 = $this->_generateRandomString(32);
$key2 = $this->_generateRandomString(32);
$key3 = $this->_generateRandomString(8, false, true);
$header = "GET /echo HTTP/1.1\r\n";
$header.= "Upgrade: WebSocket\r\n";
$header.= "Connection: Upgrade\r\n";
$header.= "Host: " . $host . ":" . $port . "\r\n";
$header.= "Origin: http://localhost\r\n";
$header.= "Sec-WebSocket-Key1: " . $key1 . "\r\n";
$header.= "Sec-WebSocket-Key2: " . $key2 . "\r\n";
$header.= "\r\n";
$header.= $key3;
$this->_Socket = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($this->_Socket, $header) or die('Error: ' . $errno . ':' . $errstr);
$response = fread($this->_Socket, 2000);
/**
* #todo: check response here. Currently not implemented cause "2 key handshake" is already deprecated.
* See: http://en.wikipedia.org/wiki/WebSocket#WebSocket_Protocol_Handshake
*/
return true;
}
private function _disconnect() {
fclose($this->_Socket);
}
private function _generateRandomString($length = 10, $addSpaces = true, $addNumbers = true) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
$useChars = array();
// select some random chars:
for ($i = 0; $i < $length; $i++) {
$useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
}
// add spaces and numbers:
if ($addSpaces === true) {
array_push($useChars, ' ', ' ', ' ', ' ', ' ', ' ');
}
if ($addNumbers === true) {
array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
}
shuffle($useChars);
$randomString = trim(implode('', $useChars));
$randomString = substr($randomString, 0, $length);
return $randomString;
}
}
$WebSocketClient = new WebsocketClient('localhost', 8887);
echo $WebSocketClient->sendData("MyUserNameFromPHP");
unset($WebSocketClient);
?>
Out of 7 php websocket clients that I tried, this is the only one that I was able to work with.
It doesn't requires any external files or frameworks.
This is simple implementation for executing short command that doesn't require persistent connection to webSocket server.
I hope it helps you guys , and you will save some time !!!

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);
}
?>

How do I pass session to new socket via fsockopen?

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);
?>

Categories