1

I'm creating an IRC bot, and I wanted to store some functions in a different file. I reference the file in my main file with include() and it works, but when I try to give fwrite() a variable like so:

$data ="THIS IS DATA\r\n";
fwrite($sock, $data);

It throws this error:

PHP Warning: feof() expects parameter 1 to be resource, null given in /home/kinz/Desktop/Eve/Eve.php on line 18

PHP Warning: fgets() expects parameter 1 to be resource, null given in /home/kinz/Desktop/Eve/Eve.php on

But when I put:

fwrite($sock, "THIS IS DATA\r\n");

It works perfectly fine. Here is my full code:

function connect_s ($serv, $port, $nick) { $sock = fsockopen($serv, $port); fwrite($sock, "USER $nick $nick $nick :$nick\r\n"); fwrite($socket, "NICK $nick\r\n"); }
function write_d ($data) { fwrite($sock, $data); }
function join_c ($chan) { write_d("JOIN $chan\r\n"); }
function get_in ($in) { for ($i = 3; $i <= count($in); $i++) { $out .= " $in[$i]"; } return trim("$out\r\n"); }
function change_n ($nick) { write_d("NICK $nick\r\n"); } ?>

I want to know why I can't use a variable as the second parameter in fwrite. Any help is greatly appreciated

4
  • 1
    Parameter 1 is $sock not $data. Commented Mar 18, 2012 at 1:09
  • And yet when I set parameter 2 manually, it fixes the problem.. Commented Mar 18, 2012 at 1:11
  • $sock is not resource id, make sure that u open server and assign to $sock ($sock = fsockopen...) before Commented Mar 18, 2012 at 1:11
  • Try var_dump($sock). Just because setting the second parameter removes the warning doesn't mean it worked. Commented Mar 18, 2012 at 1:12

2 Answers 2

5

Each new function has it's own scope for the variables. You've defined $sock in one function but it's not defined in the other functions. You need to do one of 3 things:

  1. Return $sock and pass it to any subsequent functions
  2. have global $sock; at the beginning of each of your functions
  3. write this all in an object class, and assign and use $this->sock as opposed to $sock

3 would be the "best" solution, 1 would be how to accomplish this in a functional context, and 2 is probably the easiest but using globals in this way is the last resort.

Sign up to request clarification or add additional context in comments.

Comments

1

$sock is not defined in your function named write_d.

You need to make $sock a global variable or put all of these functions into a class and make $sock a property of the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.