Why is this code not working in a new file?
I have written/found a php script and I don't understand why it's working one time and the other time it doesn't. The script connects to a game server and tries to get information from it:
$ip = 'MyServer';
$port = 'OurPort';
$connect_ip = "udp://" . $ip;
$connect = fsockopen($connect_ip, $port, $errno, $errstr, 30);
socket_set_timeout ($connect, 1, 000000);
$send = "ÿÿÿÿ" . chr (0x02) . "getstatus";
fputs($connect, $send);
fwrite ($connect, $send);
$output = fread($connect, 1);
if(!empty($output)) {
do {
$status_pre = socket_get_status($connect);
$output = $output . fread($connect, 1);
$status_post = socket_get_status($connect);
} while ($status_pre['unread_bytes'] != $status_post['unread_bytes']);
};
$output开发者_StackOverflow = explode ('\\', $output);
var_dump($output);
The output is working, something like:
array(149) { [0]=> string(20) "ÿÿÿÿstatusResponse " [1]=> ........ }
I thought: Let's do it properly and wrap it into a function like this (all code stays the same, except the beginning and end line). This will still work as long is it stays in the same file. But I thought I could put the function "check" into a new file, then I get this result:
**status.php**
function check($ip, $port) {
$connect_ip = "udp://" . $ip;
$connect = fsockopen($connect_ip, $port, $errno, $errstr, 30);
socket_set_timeout ($connect, 1, 000000);
$send = "ÿÿÿÿ" . chr (0x02) . "getstatus";
fputs($connect, $send);
fwrite ($connect, $send);
$output = fread($connect, 1);
if(!empty($output)) {
do {
$status_pre = socket_get_status($connect);
$output = $output . fread($connect, 1);
$status_post = socket_get_status($connect);
} while ($status_pre['unread_bytes'] != $status_post['unread_bytes']);
};
$output = explode ('\\', $output);
var_dump($output);
}
**index.php**
include('status.php');
check('MyServer', 'OurPort')
But guess what? The output is now:
array(1) { [0]=> string(30) "ÿÿÿÿdisconnectÿÿÿÿdisconnect" }
How is that even possible? What am I overseeing here? Is it an encoding problem with the strange y's?
Your using fwrite and then fputs which is an alias of fwrite so your calling fwrite twice. use it once and you wont get twice the output.
Make sure you save the file in the correct encoding. Try utf-8.
Those strange y's with umlauts are non-ascii characters:
$send = "ÿÿÿÿ" . chr (0x02) . "getstatus";
So if you edit such a file you have to be carefull that those are written with the correct encoding. So if the original-file is written with iso-8859-1
then then you have to make sure that your status.php
is also writen with iso-8859-1
and not, for example, utf-8
.
The better solution is to encode that "prefix" with chr
like you did with the chr(0x02)
. That way you ensure that your editor doesn't mix stuff up.
精彩评论