How add font php - php

I have such a small request because I have a php code and I do not know how to add a font to it, I know I have to add an imageloadfont but when it adds the generator just does not work. I've tried everything in my mind and nothing at all.
<?php
if( isSet( $_GET[ 'Address' ] ) )
{
$szAddress = $_GET[ 'Address' ];
$szExploded = explode( ":", $szAddress );
$szServerIP = $szExploded[ 0 ];
$szServerPort = $szExploded[ 1 ];
$Query = new SourceQuery( );
$Info = Array( );
$Rules = Array( );
$Players = Array( );
try
{
$Query -> Connect( $szServerIP, $szServerPort, DEF__TIME_OUT);
$Info = $Query -> GetInfo( );
$Players = $Query -> GetPlayers( );
$Rules = $Query -> GetRules( );
}
catch( Exception $e )
{
$Exception = $e;
}
$Query -> Disconnect( );
header( "Content-type: image/png" );
$rImage = imagecreatefrompng( DEF__IMAGE_NAME );
$iColor = imagecolorallocate( $rImage, DEF__COLOR_RED, DEF__COLOR_GREEN, DEF__COLOR_BLUE );
// bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )
imagestring( $rImage, DEF__ADDRESS_TEXT_SIZE, DEF__ADDRESS_X, DEF__ADDRESS_Y, $szAddress, $iColor );
if( $Info[ 'MaxPlayers' ] != 0 )
{
$szHostName = MIRAGE;
$szMapName = $Info[ 'Map' ];
if( strlen( $szHostName ) > DEF__HOSTNAME_MAX_TEXT_LEN )
{
$szHostName = substr( $Info[ 'HostName' ], 0, DEF__HOSTNAME_MAX_TEXT_LEN ). ' ...';
}
if( strlen( $szMapName ) > DEF__MAP_MAX_TEXT_LEN )
{
$szMapName = substr( $szMapName, 0, DEF__MAP_MAX_TEXT_LEN ). '..';
}
imagestring( $rImage, DEF__HOSTNAME_TEXT_SIZE, DEF__HOSTNAME_X, DEF__HOSTNAME_Y, $szHostName, $iColor );
imagestring( $rImage, DEF__MAP_TEXT_SIZE, DEF__MAP_X, DEF__MAP_Y, $szMapName, $iColor );
imagestring( $rImage, DEF__PLAYERS_TEXT_SIZE, DEF__PLAYERS_X, DEF__PLAYERS_Y, $Info[ 'Players' ]. '/' .$Info[ 'MaxPlayers' ], $iColor );
}
else
{
imagestring( $rImage, DEF__PLAYERS_TEXT_SIZE, DEF__PLAYERS_X, DEF__PLAYERS_Y, "SERVER OFF", $iColor );
}
$font_width = ImageFontWidth(5);
imagepng( $rImage );
imagedestroy( $rImage );
}
?>

Related

Profile photo upload locked at 600px. Ultimate Member Registration Form

This is the plugin that generates a profile photo upload button:
https://github.com/ultimatemember/Extended/blob/main/um-profile-photo/um-profile-photo.php
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Add new predefined field "Profile Photo" in UM Form Builder.
*
* #param array $arr field array settings.
*/
function um_predefined_fields_hook_profile_photo( $arr ) {
$arr['register_profile_photo'] = array(
'title' => __( 'Profile Photo', 'ultimate-member' ),
'metakey' => 'register_profile_photo',
'type' => 'image',
'label' => __('Change your profile photo','ultimate-member' ),
'upload_text' => __( 'Upload your photo here', 'ultimate-member' ),
'icon' => 'um-faicon-camera',
'crop' => 1,
'editable' => 1,
'max_size' => ( UM()->options()->get('profile_photo_max_size') ) ? UM()->options()->get('profile_photo_max_size') : 999999999,
'min_width' => str_replace('px','',UM()->options()->get('profile_photosize')),
'min_height' => str_replace('px','',UM()->options()->get('profile_photosize')),
);
return $arr;
}
add_filter( 'um_predefined_fields_hook', 'um_predefined_fields_hook_profile_photo', 99999, 1 );
/**
* Multiply Profile Photo with different sizes
*
* #param integer $user_id the user ID.
*/
function um_registration_set_profile_photo( $user_id, $args ) {
if( isset( $args['form_id'] )) $req = 'register_profile_photo-' . $args['form_id'];
else $req = 'register_profile_photo';
if( ! isset( $_REQUEST[$req] ) ) return;
//if ( strpos( $_REQUEST['register_profile_photo'], '_temp.') <= -1 ) {
//return;
//}
if( is_user_logged_in() ) {
UM()->files()->delete_core_user_photo( $user_id, 'profile_photo' );
}
$user_basedir = UM()->uploader()->get_upload_user_base_dir( $user_id, true );
$temp_dir = UM()->uploader()->get_core_temp_dir() . DIRECTORY_SEPARATOR;
$temp_profile_photo = array_slice( scandir( $temp_dir ), 2);
$temp_profile_id = isset( $_COOKIE['um-register-profile-photo'] ) ? $_COOKIE['um-register-profile-photo'] : null;
if( empty( $temp_profile_photo ) ) return;
foreach( $temp_profile_photo as $i => $p ){
if ( strpos($p, "_photo_{$temp_profile_id}_temp") !== false ) {
$profile_p = $p;
}
}
if( empty( $profile_p ) ) return;
$temp_image_path = $temp_dir . DIRECTORY_SEPARATOR . $profile_p;
$new_image_path = $user_basedir . DIRECTORY_SEPARATOR . $profile_p;
$image = wp_get_image_editor( $temp_image_path );
$file_info = wp_check_filetype_and_ext( $temp_image_path, $profile_p );
$ext = $file_info['ext'];
$new_image_name = str_replace( $profile_p, "profile_photo.{$ext}", $new_image_path );
$sizes = UM()->options()->get( 'photo_thumb_sizes' );
$quality = UM()->options()->get( 'image_compression' );
if ( ! is_wp_error( $image ) ) {
$image->save( $new_image_name );
$image->set_quality( $quality );
$sizes_array = array();
foreach( $sizes as $size ) {
$sizes_array[ ] = array ( 'width' => $size );
}
$image->multi_resize( $sizes_array );
delete_user_meta( $user_id, 'synced_profile_photo' );
update_user_meta( $user_id, 'profile_photo', "profile_photo.{$ext}" );
update_user_meta( $user_id, 'register_profile_photo', "profile_photo.{$ext}" );
#unlink( $temp_image_path );
}
}
add_action( 'um_after_user_account_updated', 'um_registration_set_profile_photo', 1, 2 );
add_action( 'um_registration_set_extra_data', 'um_registration_set_profile_photo', 1, 2 );
/**
* Set Temporary user id
*/
function um_register_profile_photo_set_temp_user_id() {
$temp_profile_id = isset( $_COOKIE['um-register-profile-photo'] ) ? $_COOKIE['um-register-profile-photo'] : null;
if ( ! $temp_profile_id ) {
setcookie( 'um-register-profile-photo', md5( time() ), time() + 3600, COOKIEPATH, COOKIE_DOMAIN );
}
}
add_action( 'template_redirect', 'um_register_profile_photo_set_temp_user_id' );
/**
* Set handler callback for filename
*/
function um_register_profile_photo_upload_handler( $override_handler ) {
if ( 'stream_photo' == UM()->uploader()->upload_image_type && 'register_profile_photo' == UM()->uploader()->field_key ) {
$override_handler['unique_filename_callback'] = 'um_register_profile_photo_name';
}
return $override_handler;
}
add_filter( 'um_image_upload_handler_overrides__register_profile_photo', 'um_register_profile_photo_upload_handler', 99999 );
/**
* Change filename
*/
function um_register_profile_photo_name( $dir, $filename, $ext ) {
$temp_profile_id = isset( $_COOKIE['um-register-profile-photo'] ) ? $_COOKIE['um-register-profile-photo'] : null;
return "profile_photo_{$temp_profile_id}_temp{$ext}";
}
/**
* Support profile photo uploader in Account form
*/
function um_register_display_profile_photo_in_account( $field_atts, $key, $data ) {
if ( 'register_profile_photo' == $key && um_is_core_page( 'account' ) ) {
$profile_photo = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . um_profile( 'profile_photo' ) . '?ts=' . current_time( 'timestamp' );
$field_atts['data-profile_photo'] = array( $profile_photo );
}
return $field_atts;
}
add_filter( 'um_field_extra_atts', 'um_register_display_profile_photo_in_account', 10, 3 );
/**
* Clear profile photo cache
*/
function um_register_display_profile_photo_script() {
if( ! um_is_core_page( 'account' ) ) return;
?>
<script type="text/javascript">
jQuery(document).on("ready", function(){
setTimeout(() => {
var register_profile_photo = jQuery("div[data-key='register_profile_photo']");
register_profile_photo.find(".um-field-area").find(".um-single-image-preview").find("img").attr("src", register_profile_photo.data("profile_photo"));
}, 1000);
var account_small_avatar = jQuery(".um-account-meta-img-b").find("a").find("img");
account_small_avatar.attr("src", account_small_avatar.attr("src") + "?ts=" + Math.floor(Date.now() / 1000) );
jQuery(document).ajaxSuccess(function(event, xhr, settings) {
if( typeof settings.data.indexOf !== "undefined" ){
if (settings.data.indexOf("action=um_resize_image") > -1) {
jQuery(".um-account .um-form form").submit();
}
}
});
});
</script>
<?php
}
add_action( 'wp_footer', 'um_register_display_profile_photo_script' );
/**
* Delete profile photo viam the account form
*/
function um_register_delete_profile_photo_from_account() {
if( isset( $_REQUEST['mode'] ) && "account" == $_REQUEST['mode'] ) {
UM()->files()->delete_core_user_photo( get_current_user_id(), 'profile_photo' );
}
wp_send_json_success();
}
add_action( 'wp_ajax_um_remove_file', 'um_register_delete_profile_photo_from_account', 1 );
When uploading the profile photo from the registration form with the 1:1 crop, it does not allow uploading a photo smaller than 600px, since it is not linked to the ultimate member settings.
This lock at 600px is located at line 1799 in the path ultimatemember/includes/core/class-fields.php
https://github.com/ultimatemember/ultimatemember/blob/master/includes/core/class-fields.php
if ( $array['min_width'] == '' && $array['crop'] == 1 ) {
$array['min_width'] = 600;
}
if ( $array['min_height'] == '' && $array['crop'] == 1 ) {
$array['min_height'] = 600;
}
if ( $array['min_width'] == '' && $array['crop'] == 3 ) {
$array['min_width'] = 600;
}
if ( $array['min_height'] == '' && $array['crop'] == 3 ) {
$array['min_height'] = 600;
Let's see if you can help me in the first code to unlock that 600px value and if you can, link it with the Ultimate Member profile photo settings.
Thank you very much for everything and greetings to the community.

Alternative way to store values to an array dynamically w.r.t the deprecated code to do the same

I'm working on a project version upgrade whereby emails are being fetched from Gmail and stored to database.
I'm seekng the alternative for line no.
"$this->_walk($obj, &$msg[], $main_content_type);"
as this doesn't work in new versions of PHP.
Is there any work around to achieve the same result which is a single array of all mail values?
function _walk( $object, $msg, $main_content_type = "" )
{
if ( !isset( $object->parts ) )
{
$ctype = "";
$ctype = trim( $object->ctype_primary ) . "/" . trim( $object->ctype_secondary );
if ( isset( $object->disposition ) && ( !strcasecmp( trim( $object->disposition ), "attachment" ) || ( !strcasecmp( trim( $object->disposition ), "inline" ) && ( ( strcasecmp( $ctype, "text/plain" ) && strcasecmp( $ctype, "text/html" ) ) ) ) ) )
{
$ctype .= trim( $object->disposition );
}
switch ( strtolower( $ctype ) )
{
case "text/html":
$msg .= $object->body;
break;
case "text/plain":
$enc = $object->headers[ 'content-transfer-encoding' ];
if ( $enc != "quoted-printable" ) {
$msg .= nl2br( $object->body );
} else {
$msg .= html_entity_decode( $object->body );
}
break;
case "image/jpeg":
case "image/gif":
case "image/jpg":
case "image/bmp":
$name = trim( $object->headers[ 'name' ] );
$cid = trim( $object->headers[ 'content-id' ] );
$cid = str_ireplace( "<", "", $cid );
$cid = str_ireplace( ">", "", $cid );
if ( empty( $name ) )
trim( strtok( $object->headers[ 'content-type' ], "=" ) );
$name = trim( strtok( "=\"" ) );
if ( empty( $name ) ) {
$name = $cid . "." . substr( $object->headers[ 'content-type' ], strrpos( $object->headers[ 'content-type' ], "/" ) + 1 );
}
$temp = $this->mailFolder . "/tmp/";
$name = mt_rand( 100, 999999 ) . "_" . $name;
#mkdir( $temp, 777 );
$tmpfile = $temp . $name;
$fp = fopen( $tmpfile, "w" );
fwrite( $fp, $object->body );
fclose( $fp );
$msg .= $name;
break;
default:
$name = trim( $object->headers[ 'name' ] );
if ( isset( $object->headers[ 'content-id' ] ) ) {
$cid = trim( $object->headers[ 'content-id' ] );
$cid = str_ireplace( "<", "", $cid );
$cid = str_ireplace( ">", "", $cid );
$extension = substr( $object->headers[ 'content-type' ], strpos( $object->headers[ 'content-type' ], "/" ) + 1, strpos( $object->headers[ 'content-type' ], ";" ) - strpos( $object->headers[ 'content-type' ], "/" ) - 1 );
$name = $cid . "." . $extension;
}
if ( isset( $object->ctype_parameters[ 'name' ] ) ) {
$name = trim( $object->ctype_parameters[ 'name' ] );
}
if ( empty( $name ) && isset( $object->d_parameters[ 'filename' ] ) ) {
$name = trim( $object->d_parameters[ 'filename' ] );
}
if ( empty( $name ) && strrpos( trim( $object->headers[ 'content-type' ] ), "=" ) !== FALSE ) {
$name = substr( trim( $object->headers[ 'content-type' ] ), strrpos( trim( $object->headers[ 'content-type' ] ), "=" ) + 2, -1 );
}
if ( empty( $name ) ) {
$name = 'ForwardedMessage.eml';
}
$temp = $this->mailFolder . "/tmp/";
$name = mt_rand( 100, 999999 ) . "_" . $name;
#mkdir( $temp, 777 );
$tmpfile = $temp . $name;
$fp = fopen( $tmpfile, "w" );
fwrite( $fp, $object->body );
fclose( $fp );
$msg .= $name;
break;
}
} else {
foreach ( $object->parts as $obj ) {
$this->_walk( $obj, &$msg[], $main_content_type );
}
}
return $msg;
}

Fatal error: Cannot redeclare class MinecraftQueryException

I have this error in my WordPress regarding this plugin, any ideas on how to fix it?
Thank you very much! ;D
<?php
class MinecraftQueryException extends Exception
{
// Exception thrown by MinecraftQuery class
}
class MinecraftQuery
{
/*
* Class written by xPaw
*
* Website: http://xpaw.me
* GitHub: https://github.com/xPaw/PHP-Minecraft-Query
*/
const STATISTIC = 0x00;
const HANDSHAKE = 0x09;
private $Socket;
private $Players;
private $Info;
public function Connect( $Ip, $Port = 25565, $Timeout = 3 )
{
if( !is_int( $Timeout ) || $Timeout < 0 )
{
throw new InvalidArgumentException( 'Timeout must be an integer.' );
}
$this->Socket = #FSockOpen( 'udp://' . $Ip, (int)$Port, $ErrNo, $ErrStr, $Timeout );
if( $ErrNo || $this->Socket === false )
{
throw new MinecraftQueryException( 'Could not create socket: ' . $ErrStr );
}
Stream_Set_Timeout( $this->Socket, $Timeout );
Stream_Set_Blocking( $this->Socket, true );
try
{
$Challenge = $this->GetChallenge( );
$this->GetStatus( $Challenge );
}
// We catch this because we want to close the socket, not very elegant
catch( MinecraftQueryException $e )
{
FClose( $this->Socket );
throw new MinecraftQueryException( $e->getMessage( ) );
}
FClose( $this->Socket );
}
public function GetInfo( )
{
return isset( $this->Info ) ? $this->Info : false;
}
public function GetPlayers( )
{
return isset( $this->Players ) ? $this->Players : false;
}
private function GetChallenge( )
{
$Data = $this->WriteData( self :: HANDSHAKE );
if( $Data === false )
{
throw new MinecraftQueryException( 'Failed to receive challenge.' );
}
return Pack( 'N', $Data );
}
private function GetStatus( $Challenge )
{
$Data = $this->WriteData( self :: STATISTIC, $Challenge . Pack( 'c*', 0x00, 0x00, 0x00, 0x00 ) );
if( !$Data )
{
throw new MinecraftQueryException( 'Failed to receive status.' );
}
$Last = '';
$Info = Array( );
$Data = SubStr( $Data, 11 ); // splitnum + 2 int
$Data = Explode( "\x00\x00\x01player_\x00\x00", $Data );
if( Count( $Data ) !== 2 )
{
throw new MinecraftQueryException( 'Failed to parse server\'s response.' );
}
$Players = SubStr( $Data[ 1 ], 0, -2 );
$Data = Explode( "\x00", $Data[ 0 ] );
// Array with known keys in order to validate the result
// It can happen that server sends custom strings containing bad things (who can know!)
$Keys = Array(
'hostname' => 'HostName',
'gametype' => 'GameType',
'version' => 'Version',
'plugins' => 'Plugins',
'map' => 'Map',
'numplayers' => 'Players',
'maxplayers' => 'MaxPlayers',
'hostport' => 'HostPort',
'hostip' => 'HostIp',
'game_id' => 'GameName'
);
foreach( $Data as $Key => $Value )
{
if( ~$Key & 1 )
{
if( !Array_Key_Exists( $Value, $Keys ) )
{
$Last = false;
continue;
}
$Last = $Keys[ $Value ];
$Info[ $Last ] = '';
}
else if( $Last != false )
{
$Info[ $Last ] = $Value;
}
}
// Ints
$Info[ 'Players' ] = IntVal( $Info[ 'Players' ] );
$Info[ 'MaxPlayers' ] = IntVal( $Info[ 'MaxPlayers' ] );
$Info[ 'HostPort' ] = IntVal( $Info[ 'HostPort' ] );
// Parse "plugins", if any
if( $Info[ 'Plugins' ] )
{
$Data = Explode( ": ", $Info[ 'Plugins' ], 2 );
$Info[ 'RawPlugins' ] = $Info[ 'Plugins' ];
$Info[ 'Software' ] = $Data[ 0 ];
if( Count( $Data ) == 2 )
{
$Info[ 'Plugins' ] = Explode( "; ", $Data[ 1 ] );
}
}
else
{
$Info[ 'Software' ] = 'Vanilla';
}
$this->Info = $Info;
if( $Players )
{
$this->Players = Explode( "\x00", $Players );
}
}
private function WriteData( $Command, $Append = "" )
{
$Command = Pack( 'c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04 ) . $Append;
$Length = StrLen( $Command );
if( $Length !== FWrite( $this->Socket, $Command, $Length ) )
{
throw new MinecraftQueryException( "Failed to write on socket." );
}
$Data = FRead( $this->Socket, 4096 );
if( $Data === false )
{
throw new MinecraftQueryException( "Failed to read from socket." );
}
if( StrLen( $Data ) < 5 || $Data[ 0 ] != $Command[ 2 ] )
{
return false;
}
return SubStr( $Data, 5 );
}
}
The error message is this:
Cannot redeclare class MinecraftQueryException
plugins/server-status-for-minecraft-pc-pe/libs/MinecraftQuery.php on
line 5

How to keep user submitted quotes as quotes in a picture

Hopefully someone will be able to tell me how to keep user quotes when generating an image. What I mean is if a user submits words like:
don't
or
John said "hello"
how can I keep them in the generated image. Currently it turns to
don\t
Here is my code:
<?php
function formattextimg( $text, $width = 960, $color = array( 0, 0, 0 ),$bgcolor = array( 255, 255, 255 ), $font = 2 ) {
$width = ( ( isset( $width ) && is_numeric( $width ) ) ? ( ( $width >= 100 ) ? (int)$width : 100 ) : 960 );
$text = str_replace( array( '<b>', '</b>', '<strong>', '</strong>' ), '|', $text );
$text_b = preg_split( '/\|/', $text, -1, PREG_SPLIT_OFFSET_CAPTURE );
foreach($text_b as $k => $tb){if($k%2!=0){$textbold[($tb[1]-1)]=$tb[0];}}
$text = str_replace('|','',$text);
for( $i = 0; $i < strlen( $text ); $i++ ) {
if( $string_c >= ( $width - ( (int)(imagefontwidth( $font ) / 2 ) ) ) ) {
$space = strrpos( $string, ' ' );
$string_sub = substr( $string, 0, $space );
$i = $i - ( strlen( $string ) - $space ) + 1;
$strings[] = $string_sub;
$string = '';
$string_c = 0;
}
$string .= $text{$i};
$string_c += imagefontwidth( $font );
}
$strings[] = $string;
$im = imagecreatetruecolor( $width, ( imagefontheight( $font ) * ( count( $strings ) ) ) );
imagesavealpha( $im, true );
$trans = imagecolorallocate( $im, $bgcolor[0], $bgcolor[1], $bgcolor[2] );
imagefill( $im, 0, 0, $trans );
$color = imagecolorallocate( $im, $color[0], $color[1], $color[2] );
$black = imagecolorallocate( $im, 0, 0, 0 );
foreach( $strings as $pos => $string ) {
imagestring( $im, $font, 5, ( $pos * imagefontheight( $font ) ), $string, $color );
}
$len = 0;
foreach( $strings as $pos => $string ) {
$len += ( strlen( $string ) + 1 );
if( count( $textbold ) > 0 ) {
foreach( $textbold as $cpos => $word ) {
if( $cpos <= $len ) {
$wpos = strpos( $string, $word );
if( $wpos !== false ) {
imagestring( $im, $font,
( $wpos * imagefontwidth( $font ) )+1,
( ( $pos ) * imagefontheight( $font ) ),
$word, $color
);
unset( $textbold[$cpos] );
}
}
}
}
}
return $im;
}
header( 'Content-type: image/png' );
imagepng( formattextimg( $text,300,array( 255, 255, 255 ),array( 128, 128, 128 ),16 ) );
exit;
?>
If that is not possible can someone please tell me how to remove the:
'
and
"
I tried:
$text=$_REQUEST['text'];
$text=str_replace('"', "", $text);
$text=str_replace("'", "", $text);
But it did not work.
thanks
This is caused by magic_quotes_gpc being enabled on the server.
You can reverse the effect of magic_quotes_gpc by calling stripslashes if get_magic_quotes_gpc (manual) returns true:
$text = $_REQUEST['text'];
if (get_magic_quotes_gpc())
{
$text = stripslashes($text);
}
It's important that you actually check the value of get_magic_quotes before calling stripslashes, as this feature has been deprecated in PHP 5.3 and removed altogether from PHP 5.4.

How to make a time limit for sockets?

How to make socket time limit ?
http://pastebin.com/0q3NeLAX
I tried socket_time_limit and others, but didnt help.
I want that if socket does not received any information, it will be closed after X seconds.
function QueryMinecraft( $IP, $Port = 25565 )
{
$Socket = Socket_Create( AF_INET, SOCK_STREAM, SOL_TCP );
if( $Socket === FALSE || #Socket_Connect( $Socket, $IP, (int)$Port ) === FALSE )
{
return FALSE;
}
Socket_Send( $Socket, "\xFE", 1, 0 );
$Len = Socket_Recv( $Socket, $Data, 256, 0 );
Socket_Close( $Socket );
if( $Len < 4 || $Data[ 0 ] != "\xFF" )
{
return FALSE;
}
$Data = SubStr( $Data, 3 );
$Data = iconv( 'UTF-16BE', 'UTF-8', $Data );
$Data = Explode( "\xA7", $Data );
return Array(
'HostName' => SubStr( $Data[ 0 ], 0, -1 ),
'Players' => isset( $Data[ 1 ] ) ? IntVal( $Data[ 1 ] ) : 0,
'MaxPlayers' => isset( $Data[ 2 ] ) ? IntVal( $Data[ 2 ] ) : 0
);
}
I would not use the sockets extension for this, I only use that for advanced socket operations that cannot be done using fsockopen(). The reason for this is that the sockets extension is not always available, whereas fsockopen() usually is.
Here is how I would write your code, with a data receive timeout:
function QueryMinecraft( $IP, $Port = 25565 )
{
// Seconds to wait for a successful connection
$connectTimeout = 5;
// Seconds to wait for data
$receiveTimeout = 5;
$Socket = fsockopen($IP, $port, $errNo, $errStr, $connectTimeout);
if( !$Socket || !stream_set_timeout( $Socket, $receiveTimeout ) )
{
return FALSE;
}
fwrite( $Socket, "\xFE" );
$Data = fread( $Socket, 256 );
fclose( $Socket );
if( strlen( $Data ) < 4 || $Data[ 0 ] != "\xFF" )
{
return FALSE;
}
$Data = SubStr( $Data, 3 );
$Data = iconv( 'UTF-16BE', 'UTF-8', $Data );
$Data = Explode( "\xA7", $Data );
return Array(
'HostName' => SubStr( $Data[ 0 ], 0, -1 ),
'Players' => isset( $Data[ 1 ] ) ? IntVal( $Data[ 1 ] ) : 0,
'MaxPlayers' => isset( $Data[ 2 ] ) ? IntVal( $Data[ 2 ] ) : 0
);
}

Categories