Currently I am making a IRC that sends a message onto the IRC main channel. Here is my code:
<?php
$ircServer = "xxxx";
$ircPort = "6667";
$ircChannel = "#bots";
set_time_limit(0);
$msg = $_GET['msg'];
$ircSocket = fsockopen($ircServer, $ircPort, $eN, $eS);
if ($ircSocket)
{
fwrite($ircSocket, "USER Lost rawr.test lol :code\n");
fwrite($ircSocket, "NICK Rawr" . rand() . "\n");
fwrite($ircSocket, "JOIN " . $ircChannel . "\n");
fwrite($ircSocket, "PRIVMSG " . $channel . " :" . $msg = $_GET['msg'] . "\n");
while(1)
{
while($data = fgets($ircSocket, 128))
{
echo nl2br($data);
flush();
// Separate all data
$exData = explode(' ', $data);
// Send PONG back to the server
if($exData[0] == "PING")
{
fwrite($ircSocket, "PONG ".$exData[1]."\n");
}
}
echo $eS . ": " . $eN;
}
}
?>
<html><body>
<h4>IRC Bot Tester</h4>
<form action="irc.php" method="post">
Command: <input type="text" name="msg" />
<input type="submit" />
</form>
</body></html>
My problem is the BOT is not sending any messages to the channel, as you see I used post + get data for the message info sent to the channel.
Here is the log what I recieve:
:irc.underworld.no 366 Rawr30517 #bots
:End of /NAMES list.
:irc.underworld.no 411 Rawr30517 :No
recipient given (PRIVMSG) : 0: 0PING
:irc.underworld.no
I do not know which part causes the this:
recipient given (PRIVMSG) : 0: 0PING
Thanks if anyone could help me. I am trying to simply post a message to the bot and the bot delivers the message to the main channel.
Change:
$msg = $_GET['msg'];
...
fwrite($ircSocket, "PRIVMSG " . $channel . " :" . $msg = $_GET['msg'] . "\n");
To:
$msg = $_POST['msg'];
...
fwrite($ircSocket, "PRIVMSG " . $ircChannel . " :" . $msg . "\n");
fwrite($ircSocket, "PRIVMSG " . $ircChannel . " " . $msg = $_GET['msg'] . "\n");
To:
fwrite($ircSocket, "PRIVMSG " . $ircChannel . " " .$msg. "\n");
Related
This question already has answers here:
Cannot open file using fopen (php)
(4 answers)
Closed 2 years ago.
In my first php file I open the users.txt to read it and then write in it. Here is the code for it:
Read:
if(file_exists("users.txt")){
$handle = fopen("users.txt", "r");
if ($handle) {
...
} else {
$ERROR = "Can't open the 'users.txt' file";
}
if ($userExist === true) {
...
}
else {
...
}
} else {
...
}
write:
$file = fopen("users.txt", "a") or die("Unable to open the file");
$data = PHP_EOL. $UserId . " " . $Fname . " " . $Lname . " " . $pass;
fwrite($file, $data);
fclose($file);
In my second php file, I tried to open the same file but apprently when I do this code:
$file = fopen("users.txt", "a") or die("Unable to open the file");
if (file_exists($file)) {
$data = " " . $Phone . " " . $recoveryEmail . " " . $month . " " . $day . " " . $year . " " . $gender;
fwrite($file, $data);
fclose($file);
}
else{
echo "Can't open the file 'users.txt'";
}
When I run it everything works fine for my first php file, but for second it prints the message:
Can't open the file 'users.txt'
After you use the fopen function, the $file is a handle, not the file name.
Hence please amend as follows:
$file = fopen("users.txt", "a") or die("Unable to open the file");
if (file_exists("users.txt")) {
$data = " " . $Phone . " " . $recoveryEmail . " " . $month . " " . $day . " " . $year . " " . $gender;
fwrite($file, $data);
fclose($file);
}
else{
echo "Can't open the file 'users.txt'";
}
Using phpseclib from my PHP application, I am running a perl .pl script which creates a file on the remote server's drive/folder in one of the exec() commands. This works fine and the file exists. The next exec() does an 'ls' command to retrieve the full filename which contains a date/time stamp on the end of the file name that is unknown. When it runs, it doesn't find the file when it is there and I can see it when doing a manual 'ls' on the Linux system. I believe it might be a timing issue, so I also included a sleep 15 in between creation and doing the 'ls' command, but this did not resolve the issue. And if I run the program again, creating a 2nd file, then the 'ls' returns the filename for the first file I generated. I didn't see an fclose in the documentation, but did see it in some other posts here that might lead me to believe this might also be the issue. Has anyone else experienced this issue and how did you resolve? Thanks.
Updated: Code snippet added....
$ssh2->login(LINUX_USER,LINUX_PASS);
$connected = $ssh2->isAuthenticated();
if ($connected) {
//$_SESSION['feedback'] .= "Connection and authentication successful to " . LINUX_SVR . ".<br>";
$cmd_string = "/usr/bin/perl-report.pl " . LINUX_ENV . " " . $parm1 . " " . $parm2;
$error = $ssh2->exec($cmd_string);
if ($error) {
$_SESSION['feedback'] .= "Unable to execute command to create the Report - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
} else {
$_SESSION['feedback'] .= "Report successfully created for ID " . $parm2 . ".<br>";
//get the full name of the file created
$cmd_string = "sleep 15";
$ssh2->exec($cmd_string);
$cmd_string = "ls /root/Report-" . $parm1 . "-" . $parm2 . "-" . $date . "*";
$error = $ssh2->exec($cmd_string);
if (empty($error)) {
$_SESSION['feedback'] .= "Unable to execute command to obtain report name - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
} else {
$filename = $ssh2->exec($cmd_string);
$filename = substr($filename, 6, strlen($filename));
$_SESSION['feedback'].= "The file name created is " . $filename . "<br>";
//verify that the filename is valid
if (substr($filename,0,7)=="Report-") {
//mail the attachment to the emailaddr
$cmd_string = "echo 'Requested Report attached.' | mail -s '" . $filename . "' -a '/root/" . $filename . "' " . $emailaddr . "\n";
$error = $ssh2->exec($cmd_string);
if ($error) {
$_SESSION['feedback'] .= "Unable to successfully email the requested report - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
} else {
$_SESSION['feedback'] .= "Report successfully emailed to " . $emailaddr . ". Process complete.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
}
} else {
$_SESSION['feedback'] .= "Unable to email attachment as filename is invalid - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
}
}
}
} else {
$_SESSION['feedback'] .= "Connection and authentication failed to " . LINUX_SVR . ".<br>";
}
//disconnect when done
$ssh2->reset();
$ssh2->disconnect();
}
I am working with an API that has a function called invokeGetMatchingProductForId() and every time the script is run, this error occurs. I am attempting to loop through the script to change one variable but i am not sure if that is the problem. If you guys have any suggestions let me know. Any help would be much appreciated! Thanks in advance!
function invokeGetMatchingProductForId(MarketplaceWebServiceProducts_Interface $service, $request)
{
try {
$response = $service->GetMatchingProductForId($request);
echo ("Service Response\n");
echo ("=============================================================================\n");
global $file_name;
global $i;
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
$dom ->save('xml/' . $file_name . $i . '.xml');
echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebServiceProducts_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex- >getResponseHeaderMetadata() . "\n");
}
}
When I get a response from the server, This error occurs.
Fatal error: Cannot redeclare function()(previously declared in x:\xampp\htdocs\name\src\project0\php\unknown.php:110) in x:\xampp\htdocs\name\src\project0\php\unknown.php on line 136
Line 136 is an empty line.
I'm having a problem with retrieving the results of a processed feed file using Amazon MWS API with PHP. I'm using the getFeedSubmissionResult class, to be precise. The problem is that when i use the API, as instructed by the documentation, there are no relevant data that is read by the class that i can access (or so it seems). So my question is: how do i retrieve the raw XML file that amazon sends back and store it to a file on my computer?
I've been retracing the code used by MWS and trying to find where they pull in the XML file from amazon and parse it to try and save that into a file with no luck. I'd deeply appreciate it if someone could direct me to a fix to this, and if not, then maybe a work around may be better.
So this is what i've been doing:
I used the getFeedSubmissionResultSample.php provided in the samples of MWS . Supposedly, this should give me the data that tells me how many items were processed and how many processed items were successful. But it doesn't. So I tried to do a print_r of the response variable:
function invokeGetFeedSubmissionResult(MarketplaceWebService_Interface $service,$request) {
try {
$response = $service->getFeedSubmissionResult($request);
echo "<br />Var dump here: <pre>";
print_r($response);
echo ("<pre>Service Response\n");
echo ("=============================================================================\n");
echo(" GetFeedSubmissionResultResponse\n");
if ($response->isSetGetFeedSubmissionResultResult()) {
$getFeedSubmissionResultResult = $response->getGetFeedSubmissionResultResult();
echo (" GetFeedSubmissionResult\n");
if ($getFeedSubmissionResultResult->isSetContentMd5()) {
echo (" ContentMd5\n");
echo (" " . $getFeedSubmissionResultResult->getContentMd5() . "\n");
}
}
if ($response->isSetResponseMetadata()) {
echo(" ResponseMetadata\n");
$responseMetadata = $response->getResponseMetadata();
if ($responseMetadata->isSetRequestId())
{
echo(" RequestId\n");
echo(" " . $responseMetadata->getRequestId() . "\n");
}
}
echo(" ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebService_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
}
And the output gives me this:
Service Response
GetFeedSubmissionResultResponse
GetFeedSubmissionResult
ContentMd5
G5Sw+2ooONEZU1iQoqdEOQ==
ResponseMetadata
RequestId
f9d4be45-6710-42eb-850e-f437224f9938
ResponseHeaderMetadata: RequestId: f9d4be45-6710-42eb-850e-f437224f9938, ResponseContext: EM/RH7RHQhLSc47Tj2a2Uv2CGKEfvxaKOijjcaKeoh8dGISci3yqo9OHZs7dpLDIszJVz4Jt4z8=,9SYUaktMzcOG6UyuyhXu/kJPl0gpLeenslL2rkugDLhDYftMleRx1XIexbVWNxuYl7cO6901Foiv Kp7hvaLeAQ==, Timestamp: 2013-06-18T07:29:37.393Z
I have omitted the var_dump results because i don't know if that may pose a security issue on my part. But in any case, the var_dump didn't give any data that i could access. I have also traced the code to where the classes and their methods to see if i can access it from there but came out empty-handed.
Note that I have the proper parameters for calling in the results (i.e. the FeedSubmissionId) because I've done this with the amazon scratch pad.
Your help would be greatly appreciated! :)
regards,
Caleb
I had the same problem. The issue is that the response returns the result for you to compare the received file against to verify no corruption during transmission. To get xml response with Message you should save it to file not to php://memory. So the next code works for me fine
$filename = __DIR__.'/file.xml';
$handle = fopen($filename, 'w+');
$request = new MarketplaceWebService_Model_GetFeedSubmissionResultRequest();
$request->setMerchant(MERCHANT_ID);
$request->setFeedSubmissionId(ID_TO_CHANGE);
$request->setFeedSubmissionResult($handle);
try {
$response = $service->getFeedSubmissionResult($request);
fclose($handle);
echo ("Service Response\n");
echo ("=============================================================================\n");
echo(" GetFeedSubmissionResultResponse\n");
if ($response->isSetGetFeedSubmissionResultResult()) {
$getFeedSubmissionResultResult = $response->getGetFeedSubmissionResultResult();
echo (" GetFeedSubmissionResult");
if ($getFeedSubmissionResultResult->isSetContentMd5()) {
echo (" ContentMd5");
echo (" " . $getFeedSubmissionResultResult->getContentMd5() . "\n");
}
}
if ($response->isSetResponseMetadata()) {
echo(" ResponseMetadata\n");
$responseMetadata = $response->getResponseMetadata();
if ($responseMetadata->isSetRequestId())
{
echo(" RequestId\n");
echo(" " . $responseMetadata->getRequestId() . "\n");
}
}
echo(" ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebService_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
the result you can find in ./file.xml file
this helped me
If you do not want to use a file. Then at the end of your try statement.
$xml = stream_get_contents($request->getFeedSubmissionResult());
That will put the xml data into $xml
I writing a command and then reading back from a server via sockets in PHP. We have 20 servers that all run a Node JS script which can receive these commands and execute them. The Node JS script will return "ok" which PHP reads back to confirm the command has gone through.
The Node JS script listens on port 9000 and is set to allow half open.
Most of the time this works fine, but when a high volume of commands are sent we get errors back occasionally that say this:
Contents: Message received back from socket was 'Unexpected token {'
Transport endpoint is not connected
The transport endpoint message suggests to me that it has not connected successfully.
I am no expert in sockets so I don't know whether the implementation I have used is "correct". It does work most of the time but I am aware that there are functions like socket_bind and socket_listen that may work better, though I am not sure what they do.
Here is the PHP code that we are using. Any suggestions would be most appreciated.
public function sendDaemonCommand($address, $template_id, $params = array()) {
$hostname = $this->getHostnameFromPrivateIP($address);
$port = 9000;
$command = array('template_id' => $template_id, 'params' => $params);
$command = json_encode($command);
// Create a TCP Stream socket
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to create socket on " . $address . "\n\n" . socket_strerror(socket_last_error()) . "\n\nCommand:\n\n" . $command . "\n" . $this->functionTraceback());
return false;
}
// Connect to socket
if (socket_connect($sock, $address, $port) === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to connect to socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_close($sock);
return false;
}
// Write command to socket
$_command = $command;
$length = strlen($_command);
while (true) {
$sent = socket_write($sock, $_command, $length);
if ($sent === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to write command to socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_shutdown($sock, 2);
socket_close($sock);
return false;
}
if ($sent < $length) {
$_command = substr($_command, $sent);
$length -= $sent;
}
else {
break;
}
}
socket_shutdown($sock, 1);
// Read back from socket
if (($out = socket_read($sock, 1024)) !== false) {
#socket_shutdown($sock, 0);
$out = trim($out);
if ($out !== "ok") {
$this->mailError("Command Failed - " . $hostname, "Message received back from socket was '" . $out . "' on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_close($sock);
return false;
}
}
else {
$this->mailError("Command Failed - " . $hostname, "Failed to read from socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_shutdown($sock, 0);
socket_close($sock);
return false;
}
socket_close($sock);
return $out;
}
For a simple socket client such as this, I much prefer fsockopen() - it drastically reduces the complication of the client code and does not require the sockets extension, which is not available everywhere. The main disadvantage to this is that you lose the string error messages, but these are rarely that useful anyway - you still get an error string from creating the socket, and if read/write operations fail it's because the socket has become disconnected.
I'm also not sure how useful "allow half open" is in this context - I think it is likely to create more problems than it solves. The calls to socket_shutdown() are not doing anything useful here (and may be the source of your problems) - you would only use this if you are operating on a socket that will not be closed and may be operated on at a later point in time by some other code. Since you create a new socket and destroy it in the same routine, this is not the case.
Here is your code rewritten to use fsockopen() - as you can see, it is somewhat shorter and simpler. I have also modified it slightly so that it always returns a bool - your code returns either bool FALSE or string ok, and since there are only these two options it makes more sense for the function to always return a bool.
public function sendDaemonCommand($address, $template_id, $params = array()) {
// Prepare data
$hostname = $this->getHostnameFromPrivateIP($address);
$port = 9000;
$command = array('template_id' => $template_id, 'params' => $params);
$_command = $command = json_encode($command);
$length = strlen($_command);
// Connect to socket
if (!$sock = fsockopen($address, $port, $errNo, $errStr)) {
$this->mailError("Command Failed - " . $hostname, "Failed to connect to socket on " . $address . "\n\n" . $errStr . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
return false;
}
// Write command to socket
while (true) {
// Try and write data to socket
$sent = fwrite($sock, $_command, $length);
// If it failed, error out
if ($sent === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to write command to socket on " . $address . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
fclose($sock);
return false;
}
// If there is data left to send, try again
if ($sent < $length) {
$_command = substr($_command, $sent);
$length -= $sent;
continue;
}
// If we get here the write operation was successful
break;
}
// Read back from socket and close it
$out = fread($sock, 1024);
fclose($sock);
// Test the response from the server
if ($out === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to read from socket on " . $address . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
return false;
} else if (($out = trim($out)) !== "ok") {
$this->mailError("Command Failed - " . $hostname, "Message received back from socket was '" . $out . "' on " . $address . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
return false;
} else {
return true;
}
}