Simple PHP IRC web client using Ajax calls.

irc.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. // Prevent PHP from stopping the script after 30 sec
  3. set_time_limit(0);
  4. include_once("config.php");
  5. // Change these values!
  6. $username = $argv[1];
  7. if(!isset($username) || $username == "") {
  8. echo "Username not given...";
  9. exit(1);
  10. }
  11. echo "Starting client...";
  12. file_put_contents(".$username.socket", "Welcome");
  13. chmod(".$username.socket", 0777);
  14. file_put_contents(".$username.pingfile", "pong");
  15. chmod(".$username.pingfile", 0777);
  16. // Opening the socket to the Rizon network
  17. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  18. socket_connect($socket, $server, $port);
  19. // Send auth info
  20. // fputs($socket, "PASS " . $password . "\n");
  21. echo "Connected, sending nickname to IRC server...";
  22. $nickline = "NICK " . $username . "\n";
  23. $userline = "USER " . $username . " 0 * :" . $username . "'s Bot\n";
  24. socket_write($socket, $nickline, strlen($nickline));
  25. socket_write($socket, $userline, strlen($userline));
  26. // Join channel
  27. foreach($channels as $channel) {
  28. $channelline = "JOIN " . $channel . "\n";
  29. socket_write($socket, $channelline, strlen($channelline));
  30. }
  31. // Force an endless while
  32. while (1) {
  33. // Continue the rest of the script here
  34. while($bytes = socket_recv($socket, $r_data, 2048, MSG_DONTWAIT) !== '') {
  35. if($bytes !== FALSE) {
  36. //$data = socket_read($socket, 2048, PHP_NORMAL_READ);
  37. $data = $r_data;
  38. }
  39. // If client sent something, push it to the IRC server!
  40. if(file_exists(".$username.push")) {
  41. $pushFile = file_get_contents(".$username.push");
  42. socket_write($socket, $pushFile, strlen($pushFile));
  43. unlink(".$username.push");
  44. }
  45. // Check if web client still up, if no pong after 15 seconds, connection closed.
  46. if(!file_exists(".$username.pingfile") || (date("YmdHis.", filemtime(".$username.pingfile"))<(date("YmdHis.", filemtime(".$username.pingfile"))-10))) {
  47. echo "Exiting, leaving IRC server...";
  48. $quitline = "QUIT :Timed out\n";
  49. socket_write($socket, $quitline, strlen($quitline));
  50. socket_close($socket);
  51. exit(1);
  52. }
  53. if(isset($data)) {
  54. $stringMsg = explode('PRIVMSG', $data);
  55. $socketFileContents = file_get_contents(".$username.socket");
  56. file_put_contents(".$username.socket", $socketFileContents . $data);
  57. $ex = explode(' ', $data);
  58. // Send PONG back to the server
  59. if ($ex[0] == "PING") {
  60. echo "PONG to IRC server...";
  61. $pongline = "PONG " . $ex[1] . "\n";
  62. socket_write($socket, $pongline, strlen($pongline));
  63. }
  64. }
  65. usleep(500);
  66. }
  67. }
  68. ?>