Правила форума Гаранты форума
Размещение рекламы AMX-X компилятор

Здравствуйте, гость Вход | Регистрация

Наши новости:

14-дек
24-апр
10-апр
11-апр

Как вывести нужные переменные Source Query Class

, Ай нид Хелп
Статус пользователя drivemaster
сообщение 16.2.2015, 17:54
Сообщение #1


Стаж: 17 лет

Сообщений: 266
Благодарностей: 79
Полезность: 246

Как вывести нужные переменные Source Query Class

Есть php класс для работы с играми Source, ссылка:

Цитата


SourceQuery.class
Код
<?php
    /**
     * Class written by xPaw
     *
     * Website: http://xpaw.me
     * GitHub: https://github.com/xPaw/PHP-Source-Query-Class
     *
     * Special thanks to koraktor for his awesome Steam Condenser class,
     * I used it as a reference at some points.
     */
    
    if( !defined( '__DIR__' ) ) // PHP < 5.3
    {
        define( '__DIR__', dirname( __FILE__ ) );
    }
    
    require __DIR__ . '/Exceptions.class.php';
    require __DIR__ . '/Buffer.class.php';
    require __DIR__ . '/Socket.class.php';
    require __DIR__ . '/SourceRcon.class.php';
    require __DIR__ . '/GoldSourceRcon.class.php';

    use xPaw\SourceQuery\Exception\InvalidArgumentException;
    use xPaw\SourceQuery\Exception\TimeoutException;
    use xPaw\SourceQuery\Exception\InvalidPacketException;

    class SourceQuery
    {
        /**
         * Values returned by GetChallenge()
         *
         * TODO: Get rid of this? Improve? Do something else?
         */
        const GETCHALLENGE_FAILED          = 0;
        const GETCHALLENGE_ALL_CLEAR       = 1;
        const GETCHALLENGE_CONTAINS_ANSWER = 2;
        
        /**
         * Engines
         */
        const GOLDSOURCE = 0;
        const SOURCE     = 1;
        
        /**
         * Packets sent
         */
        const A2S_PING      = 0x69;
        const A2S_INFO      = 0x54;
        const A2S_PLAYER    = 0x55;
        const A2S_RULES     = 0x56;
        const A2S_SERVERQUERY_GETCHALLENGE = 0x57;
        
        /**
         * Packets received
         */
        const S2A_PING      = 0x6A;
        const S2A_CHALLENGE = 0x41;
        const S2A_INFO      = 0x49;
        const S2A_INFO_OLD  = 0x6D; // Old GoldSource, HLTV uses it
        const S2A_PLAYER    = 0x44;
        const S2A_RULES     = 0x45;
        const S2A_RCON      = 0x6C;
        
        /**
         * Source rcon sent
         */
        const SERVERDATA_EXECCOMMAND    = 2;
        const SERVERDATA_AUTH           = 3;
        
        /**
         * Source rcon received
         */
        const SERVERDATA_RESPONSE_VALUE = 0;
        const SERVERDATA_AUTH_RESPONSE  = 2;
        
        /**
         * Points to rcon class
         *
         * @var SourceQueryRcon
         */
        private $Rcon;
        
        /**
         * Points to buffer class
         *
         * @var SourceQueryBuffer
         */
        private $Buffer;
        
        /**
         * Points to socket class
         *
         * @var SourceQuerySocket
         */
        private $Socket;
        
        /**
         * True if connection is open, false if not
         *
         * @var bool
         */
        private $Connected;
        
        /**
         * Contains challenge
         *
         * @var string
         */
        private $Challenge;
        
        /**
         * Use old method for getting challenge number
         *
         * @var bool
         */
        private $UseOldGetChallengeMethod;
        
        public function __construct( )
        {
            $this->Buffer = new SourceQueryBuffer( );
            $this->Socket = new SourceQuerySocket( $this->Buffer );
        }
        
        public function __destruct( )
        {
            $this->Disconnect( );
        }

        /**
         * Opens connection to server
         *
         * @param string $Ip Server ip
         * @param int $Port Server port
         * @param int $Timeout Timeout period
         * @param int $Engine Engine the server runs on (goldsource, source)
         *
         * @throws InvalidArgumentException
         * @throws TimeoutException
         */
        public function Connect( $Ip, $Port, $Timeout = 3, $Engine = self :: SOURCE )
        {
            $this->Disconnect( );
            
            if( !is_int( $Timeout ) || $Timeout < 0 )
            {
                throw new InvalidArgumentException("Timeout must be an integer.", InvalidArgumentException::TIMEOUT_NOT_INTEGER);
            }
            
            if( !$this->Socket->Open( $Ip, (int)$Port, $Timeout, (int)$Engine ) )
            {
                throw new TimeoutException("Could not connect to server.", TimeoutException::TIMEOUT_CONNECT);
            }
            
            $this->Connected = true;
        }
        
        /**
         * Forces GetChallenge to use old method for challenge retrieval because some games use outdated protocol (e.g Starbound)
         *
         * @param bool $Value Set to true to force old method
         *
         * @returns bool Previous value
         */
        public function SetUseOldGetChallengeMethod( $Value )
        {
            $Previous = $this->UseOldGetChallengeMethod;
            
            $this->UseOldGetChallengeMethod = $Value === true;
            
            return $Previous;
        }
        
        /**
         * Closes all open connections
         */
        public function Disconnect( )
        {
            $this->Connected = false;
            $this->Challenge = 0;
            
            $this->Buffer->Reset( );
            
            $this->Socket->Close( );
            
            if( $this->Rcon )
            {
                $this->Rcon->Close( );
                
                $this->Rcon = null;
            }
        }
        
        /**
         * Sends ping packet to the server
         * NOTE: This may not work on some games (TF2 for example)
         *
         * @return bool True on success, false on failure
         */
        public function Ping( )
        {
            if( !$this->Connected )
            {
                return false;
            }
            
            $this->Socket->Write( self :: A2S_PING );
            $this->Socket->Read( );
            
            return $this->Buffer->GetByte( ) === self :: S2A_PING;
        }
        
        /**
         * Get server information
         *
         * @throws InvalidPacketException
         *
         * @return bool|array Returns array with information on success, false on failure
         */
        public function GetInfo( )
        {
            if( !$this->Connected )
            {
                return false;
            }
            
            $this->Socket->Write( self :: A2S_INFO, "Source Engine Query\0" );
            $this->Socket->Read( );
            
            $Type = $this->Buffer->GetByte( );
            
            if( $Type === 0 )
            {
                return false;
            }
            
            // Old GoldSource protocol, HLTV still uses it
            if( $Type === self :: S2A_INFO_OLD && $this->Socket->Engine === self :: GOLDSOURCE )
            {
                /**
                 * If we try to read data again, and we get the result with type S2A_INFO (0x49)
                 * That means this server is running dproto,
                 * Because it sends answer for both protocols
                 */
                
                $Server[ 'Address' ]    = $this->Buffer->GetString( );
                $Server[ 'HostName' ]   = $this->Buffer->GetString( );
                $Server[ 'Map' ]        = $this->Buffer->GetString( );
                $Server[ 'ModDir' ]     = $this->Buffer->GetString( );
                $Server[ 'ModDesc' ]    = $this->Buffer->GetString( );
                $Server[ 'Players' ]    = $this->Buffer->GetByte( );
                $Server[ 'MaxPlayers' ] = $this->Buffer->GetByte( );
                $Server[ 'Protocol' ]   = $this->Buffer->GetByte( );
                $Server[ 'Dedicated' ]  = Chr( $this->Buffer->GetByte( ) );
                $Server[ 'Os' ]         = Chr( $this->Buffer->GetByte( ) );
                $Server[ 'Password' ]   = $this->Buffer->GetByte( ) === 1;
                $Server[ 'IsMod' ]      = $this->Buffer->GetByte( ) === 1;
                
                if( $Server[ 'IsMod' ] )
                {
                    $Mod[ 'Url' ]        = $this->Buffer->GetString( );
                    $Mod[ 'Download' ]   = $this->Buffer->GetString( );
                    $this->Buffer->Get( 1 ); // NULL byte
                    $Mod[ 'Version' ]    = $this->Buffer->GetLong( );
                    $Mod[ 'Size' ]       = $this->Buffer->GetLong( );
                    $Mod[ 'ServerSide' ] = $this->Buffer->GetByte( ) === 1;
                    $Mod[ 'CustomDLL' ]  = $this->Buffer->GetByte( ) === 1;
                }
                
                $Server[ 'Secure' ]   = $this->Buffer->GetByte( ) === 1;
                $Server[ 'Bots' ]     = $this->Buffer->GetByte( );
                
                if( isset( $Mod ) )
                {
                    $Server[ 'Mod' ] = $Mod;
                }
                
                return $Server;
            }
            
            if( $Type !== self :: S2A_INFO )
            {
                throw new InvalidPacketException("GetInfo: Packet header mismatch. (0x' . DecHex( $Type ) . ')", InvalidPacketException::PACKET_HEADER_MISMATCH);
            }
            
            $Server[ 'Protocol' ]   = $this->Buffer->GetByte( );
            $Server[ 'HostName' ]   = $this->Buffer->GetString( );
            $Server[ 'Map' ]        = $this->Buffer->GetString( );
            $Server[ 'ModDir' ]     = $this->Buffer->GetString( );
            $Server[ 'ModDesc' ]    = $this->Buffer->GetString( );
            $Server[ 'AppID' ]      = $this->Buffer->GetShort( );
            $Server[ 'Players' ]    = $this->Buffer->GetByte( );
            $Server[ 'MaxPlayers' ] = $this->Buffer->GetByte( );
            $Server[ 'Bots' ]       = $this->Buffer->GetByte( );
            $Server[ 'Dedicated' ]  = Chr( $this->Buffer->GetByte( ) );
            $Server[ 'Os' ]         = Chr( $this->Buffer->GetByte( ) );
            $Server[ 'Password' ]   = $this->Buffer->GetByte( ) === 1;
            $Server[ 'Secure' ]     = $this->Buffer->GetByte( ) === 1;
            
            // The Ship (they violate query protocol spec by modifying the response)
            if( $Server[ 'AppID' ] === 2400 )
            {
                $Server[ 'GameMode' ]     = $this->Buffer->GetByte( );
                $Server[ 'WitnessCount' ] = $this->Buffer->GetByte( );
                $Server[ 'WitnessTime' ]  = $this->Buffer->GetByte( );
            }
            
            $Server[ 'Version' ] = $this->Buffer->GetString( );
            
            // Extra Data Flags
            if( $this->Buffer->Remaining( ) > 0 )
            {
                $Server[ 'ExtraDataFlags' ] = $Flags = $this->Buffer->GetByte( );
                
                // The server's game port
                if( $Flags & 0x80 )
                {
                    $Server[ 'GamePort' ] = $this->Buffer->GetShort( );
                }
                
                // The server's SteamID - does this serve any purpose?
                if( $Flags & 0x10 )
                {
                    $Server[ 'ServerID' ] = $this->Buffer->GetUnsignedLong( ) | ( $this->Buffer->GetUnsignedLong( ) << 32 ); // TODO: verify this
                }
                
                // The spectator port and then the spectator server name
                if( $Flags & 0x40 )
                {
                    $Server[ 'SpecPort' ] = $this->Buffer->GetShort( );
                    $Server[ 'SpecName' ] = $this->Buffer->GetString( );
                }
                
                // The game tag data string for the server
                if( $Flags & 0x20 )
                {
                    $Server[ 'GameTags' ] = $this->Buffer->GetString( );
                }
                
                // GameID -- alternative to AppID?
                if( $Flags & 0x01 )
                {
                    $Server[ 'GameID' ] = $this->Buffer->GetUnsignedLong( ) | ( $this->Buffer->GetUnsignedLong( ) << 32 );
                }
                
                if( $this->Buffer->Remaining( ) > 0 )
                {
                    throw new InvalidPacketException("GetInfo: unread data? " . $this->Buffer->Remaining( ) . " bytes remaining in the buffer. Please report it to the library developer.",
                        InvalidPacketException::BUFFER_NOT_EMPTY);
                }
            }
            
            return $Server;
        }
        
        /**
         * Get players on the server
         *
         * @throws InvalidPacketException
         *
         * @return bool|array Returns array with players on success, false on failure
         */
        public function GetPlayers( )
        {
            if( !$this->Connected )
            {
                return false;
            }
            
            switch( $this->GetChallenge( self :: A2S_PLAYER, self :: S2A_PLAYER ) )
            {
                case self :: GETCHALLENGE_FAILED:
                {
                    return false;
                }
                case self :: GETCHALLENGE_ALL_CLEAR:
                {
                    $this->Socket->Write( self :: A2S_PLAYER, $this->Challenge );
                    $this->Socket->Read( 14000 ); // Moronic Arma 3 developers do not split their packets, so we have to read more data
                    // This violates the protocol spec, and they probably should fix it: https://developer.valvesoftware.com/wiki/Server_queries#Protocol
                    
                    $Type = $this->Buffer->GetByte( );
                    
                    if( $Type === 0 )
                    {
                        return false;
                    }
                    else if( $Type !== self :: S2A_PLAYER )
                    {
                        throw new InvalidPacketException( 'GetPlayers: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH);
                    }
                    
                    break;
                }
            }
            
            $Players = Array( );
            $Count   = $this->Buffer->GetByte( );
            
            while( $Count-- > 0 && $this->Buffer->Remaining( ) > 0 )
            {
                $Player[ 'Id' ]    = $this->Buffer->GetByte( ); // PlayerID, is it just always 0?
                $Player[ 'Name' ]  = $this->Buffer->GetString( );
                $Player[ 'Frags' ] = $this->Buffer->GetLong( );
                $Player[ 'Time' ]  = (int)$this->Buffer->GetFloat( );
                $Player[ 'TimeF' ] = GMDate( ( $Player[ 'Time' ] > 3600 ? "H:i:s" : "i:s" ), $Player[ 'Time' ] );
                
                $Players[ ] = $Player;
            }
            
            return $Players;
        }
        
        /**
         * Get rules (cvars) from the server
         *
         * @throws InvalidPacketException
         *
         * @return bool|array Returns array with rules on success, false on failure
         */
        public function GetRules( )
        {
            if( !$this->Connected )
            {
                return false;
            }
            
            switch( $this->GetChallenge( self :: A2S_RULES, self :: S2A_RULES ) )
            {
                case self :: GETCHALLENGE_FAILED:
                {
                    return false;
                }
                case self :: GETCHALLENGE_ALL_CLEAR:
                {
                    $this->Socket->Write( self :: A2S_RULES, $this->Challenge );
                    $this->Socket->Read( );
                    
                    $Type = $this->Buffer->GetByte( );
                    
                    if( $Type === 0 )
                    {
                        return false;
                    }
                    else if( $Type !== self :: S2A_RULES )
                    {
                        throw new InvalidPacketException( 'GetRules: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH);
                    }
                    
                    break;
                }
            }
            
            $Rules = Array( );
            $Count = $this->Buffer->GetShort( );
            
            while( $Count-- > 0 && $this->Buffer->Remaining( ) > 0 )
            {
                $Rule  = $this->Buffer->GetString( );
                $Value = $this->Buffer->GetString( );
                
                if( !Empty( $Rule ) )
                {
                    $Rules[ $Rule ] = $Value;
                }
            }
            
            return $Rules;
        }

        /**
         * Get challenge (used for players/rules packets)
         *
         * @param $Header
         * @param $ExpectedResult
         * @throws InvalidPacketException
         * @return bool True if all went well, false if server uses old GoldSource protocol, and it already contains answer
         */
        private function GetChallenge( $Header, $ExpectedResult )
        {
            if( $this->Challenge )
            {
                return self :: GETCHALLENGE_ALL_CLEAR;
            }
            
            if( $this->UseOldGetChallengeMethod )
            {
                $Header = self :: A2S_SERVERQUERY_GETCHALLENGE;
            }
            
            $this->Socket->Write( $Header, 0xFFFFFFFF );
            $this->Socket->Read( );
            
            $Type = $this->Buffer->GetByte( );
            
            switch( $Type )
            {
                case self :: S2A_CHALLENGE:
                {
                    $this->Challenge = $this->Buffer->Get( 4 );
                    
                    return self :: GETCHALLENGE_ALL_CLEAR;
                }
                case $ExpectedResult:
                {
                    // Goldsource (HLTV)
                    
                    return self :: GETCHALLENGE_CONTAINS_ANSWER;
                }
                case 0:
                {
                    return self :: GETCHALLENGE_FAILED;
                }
                default:
                {
                    throw new InvalidPacketException( 'GetChallenge: Packet header mismatch. (0x' . DecHex( $Type ) . ')', InvalidPacketException::PACKET_HEADER_MISMATCH);
                }
            }
        }
        
        /**
         * Sets rcon password, for future use in Rcon()
         *
         * @param string $Password Rcon Password
         *
         * @return bool True on success, false on failure
         */
        public function SetRconPassword( $Password )
        {
            if( !$this->Connected )
            {
                return false;
            }
            
            switch( $this->Socket->Engine )
            {
                case SourceQuery :: GOLDSOURCE:
                {
                    $this->Rcon = new SourceQueryGoldSourceRcon( $this->Buffer, $this->Socket );
                    
                    break;
                }
                case SourceQuery :: SOURCE:
                {
                    $this->Rcon = new SourceQuerySourceRcon( $this->Buffer, $this->Socket );
                    
                    break;
                }
            }
            
            $this->Rcon->Open( );
            
            return $this->Rcon->Authorize( $Password );
        }
        
        /**
         * Sends a command to the server for execution.
         *
         * @param string $Command Command to execute
         *
         * @return string|bool Answer from server in string, false on failure
         */
        public function Rcon( $Command )
        {
            if( !$this->Connected )
            {
                return false;
            }
            
            return $this->Rcon->Command( $Command );
        }
    }


view из архива
Код
<?php
    require __DIR__ . '/SourceQuery/SourceQuery.class.php';
    
    // Edit this ->
    define( 'SQ_SERVER_ADDR', 'IP' );
    define( 'SQ_SERVER_PORT', PORT );
    define( 'SQ_TIMEOUT',     3 );
    define( 'SQ_ENGINE',      SourceQuery :: SOURCE );
    // Edit this <-
    
    $Query = new SourceQuery( );
    
    $Info    = Array( );
    
    try
    {
        $Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE );
        //$Query->SetUseOldGetChallengeMethod( true ); // Use this when players/rules retrieval fails on games like Starbound
        
        $Info    = $Query->GetInfo( );

    }
    catch( Exception $e )
    {
        $Exception = $e;
    }
    
    $Query->Disconnect( );

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Source Query PHP Class</title>

</head>

<body>
    <div class="container">

        
<?php if( isset( $Exception ) ): ?>
        <div class="panel panel-primary">
            <div class="panel-heading"><?php echo Get_Class( $Exception ); ?> at line <?php echo $Exception->getLine( ); ?></div>
            <p><b><?php echo htmlspecialchars( $Exception->getMessage( ) ); ?></b></p>
            <p><?php echo nl2br( $e->getTraceAsString(), false ); ?></p>
        </div>
<?php else: ?>

                <table class="table table-bordered table-striped">


<?php if( Is_Array( $Info ) ): ?>
<?php foreach( $Info as $InfoKey => $InfoValue ): ?>
                        <tr>
                            <td><?php echo htmlspecialchars( $InfoKey ); ?></td>
                            <td><?php
    if( Is_Array( $InfoValue ) )
    {
        echo "<pre>";
        print_r( $InfoValue );
        echo "</pre>";
    }
    else
    {
        if( $InfoValue === true )
        {
            echo 'true';
        }
        else if( $InfoValue === false )
        {
            echo 'false';
        }
        else
        {
            echo htmlspecialchars( $InfoValue );
        }
    }
?></td>
                        
<?php endforeach; ?>
<?php else: ?>
No information received

<?php endif; ?>
    
<?php endif; ?>

</body>
</html>


Т.е. в стандарте он выводит таблицу со всеми данными о сервере, а как выдернуть именно отдельные переменные используя данный класс?

Ну например,

Код
$Server[ 'Protocol' ]
$Server[ 'HostName' ]  
$Server[ 'Map' ]  
$Server[ 'ModDir' ]  
$Server[ 'ModDesc' ]


Чтобы уже дальше эти переменные можно было в дизайне использовать. Если кто уже разобрался с ним, помогите :)

Отредактировал: drivemaster, - 16.2.2015, 17:57
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   Цитировать сообщение
umprex
сообщение 16.2.2015, 18:23
Сообщение #2


Иконка группы

Стаж: 16 лет
Город: Киев

Сообщений: 2909
Благодарностей: 4781
Полезность: 2197

Код:
<?php
require __DIR__ . '/SourceQuery/SourceQuery.class.php';

define( 'SQ_SERVER_ADDR', 'IP' );
define( 'SQ_SERVER_PORT', PORT );

$Query = new SourceQuery( );

$Server = Array( );

if($Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, 3, SourceQuery :: SOURCE )){
$Server = $Query->GetInfo( );
}else die('error');
?>


ПС класс не работает с нонстим серверами.


Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя onotole
сообщение 16.2.2015, 21:02
Сообщение #3


Иконка группы

Стаж: 13 лет

Сообщений: 1572
Благодарностей: 1119
Полезность: 1550

Меценат Меценат

Цитата(umprex @ 16.2.2015, 19:23) *
Код:
<?php
require __DIR__ . '/SourceQuery/SourceQuery.class.php';

define( 'SQ_SERVER_ADDR', 'IP' );
define( 'SQ_SERVER_PORT', PORT );

$Query = new SourceQuery( );

$Server = Array( );

if($Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, 3, SourceQuery :: SOURCE )){
$Server = $Query->GetInfo( );
}else die('error');
?>


ПС класс не работает с нонстим серверами.

Даладно? У меня сё работает.
ТС. Выводи переменные там, где нужно и всё
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя drivemaster
сообщение 17.2.2015, 8:45
Сообщение #4


Стаж: 17 лет

Сообщений: 266
Благодарностей: 79
Полезность: 246

Код
<?php
    require __DIR__ . '/SourceQuery/SourceQuery.class.php';
    
    define( 'SQ_SERVER_ADDR', 'IP' );
    define( 'SQ_SERVER_PORT', PORT );
    
    $Query = new SourceQuery( );
    
    $Server    = Array( );
    
    if($Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, 3, SourceQuery :: SOURCE )){
         $Server    = $Query->GetInfo( );
    }else die('error');
?>

Если заменить на этот кусок, он вообще мне error возвращает.

to onotole

Цитата
Выводи переменные там, где нужно и всё


Вопрос звучал

Цитата
Как вывести нужные переменные Source Query Class


В том-то и вопрос, я не могу понять как их вывести
Цитата
echo $Server[ 'Address' ];

или как-то ещё.

Отредактировал: drivemaster, - 17.2.2015, 8:46
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя oxoTHuk.
сообщение 17.2.2015, 9:20
Сообщение #5


Иконка группы

Стаж: 17 лет

Сообщений: 879
Благодарностей: 515
Полезность: 867

Код:
print_r($Query->GetInfo()["HostName"]);

Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя drivemaster
сообщение 17.2.2015, 9:32
Сообщение #6


Стаж: 17 лет

Сообщений: 266
Благодарностей: 79
Полезность: 246

Цитата(oxoTHuk. @ 17.2.2015, 10:20) *
Код:
print_r($Query->GetInfo()["HostName"]);



Код:
<?php
require __DIR__ . '/SourceQuery/SourceQuery.class.php';

// Edit this ->
define( 'SQ_SERVER_ADDR', '10.194.112.151' );
define( 'SQ_SERVER_PORT', 27777 );
define( 'SQ_TIMEOUT', 3 );
define( 'SQ_ENGINE', SourceQuery :: SOURCE );
// Edit this <-

$Query = new SourceQuery( );

$Info = Array( );

try
{
$Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE );
//$Query->SetUseOldGetChallengeMethod( true ); // Use this when players/rules retrieval fails on games like Starbound

$Info = $Query->GetInfo( );

}
catch( Exception $e )
{
$Exception = $e;
}

$Query->Disconnect( );

print_r($Query->GetInfo()["HostName"]);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>

<body>
</body>
</html>


Выводит пустую страницу.
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя oxoTHuk.
сообщение 17.2.2015, 9:45
Сообщение #7


Иконка группы

Стаж: 17 лет

Сообщений: 879
Благодарностей: 515
Полезность: 867

Гениально =)
Сначала
Код:
 $Query->Disconnect( );

Потом пытаешься вывести =)
Выводи в try, там же где автор ловит это дело в екзампле =)
Ну и catch и дисконнектом в самый низ =)
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя onotole
сообщение 17.2.2015, 11:37
Сообщение #8


Иконка группы

Стаж: 13 лет

Сообщений: 1572
Благодарностей: 1119
Полезность: 1550

Меценат Меценат

Цитата(oxoTHuk. @ 17.2.2015, 10:45) *
Гениально =)
Сначала
Код:
 $Query->Disconnect( );

Потом пытаешься вывести =)
Выводи в try, там же где автор ловит это дело в екзампле =)
Ну и catch и дисконнектом в самый низ =)

Выводить в try?? Более гениального я не видел. И пусть меня сейчас закидают всеми возможными камнями, что я опять критикую. Дак если люди говнокодят, и из-за таких людей все и ненавидят РНР!
Зачем объявлять константы, которые нужны всего 1 раз...

ТС, вот набросал пример
http://paste2.org/_N39xN6j6

Отредактировал: onotole, - 17.2.2015, 11:41
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя oxoTHuk.
сообщение 17.2.2015, 11:58
Сообщение #9


Иконка группы

Стаж: 17 лет

Сообщений: 879
Благодарностей: 515
Полезность: 867

onotole, я не претендовал на гениальность, просто взял экзампл из архива, и вывел то, что прописал автор.
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя drivemaster
сообщение 17.2.2015, 12:25
Сообщение #10


Стаж: 17 лет

Сообщений: 266
Благодарностей: 79
Полезность: 246

Цитата(onotole @ 17.2.2015, 12:37) *
Выводить в try?? Более гениального я не видел. И пусть меня сейчас закидают всеми возможными камнями, что я опять критикую. Дак если люди говнокодят, и из-за таких людей все и ненавидят РНР!
Зачем объявлять константы, которые нужны всего 1 раз...

ТС, вот набросал пример
http://paste2.org/_N39xN6j6

Огромное спасибо! Как раз то, что нужно было.

Отредактировал: drivemaster, - 17.2.2015, 12:26
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя miRror
сообщение 17.2.2015, 12:55
Сообщение #11


Стаж: 15 лет

Сообщений: 1151
Благодарностей: 1002
Полезность: 967

Меценат Меценат

https://github.com/xPaw/PHP-Source-Query-Cl...master/View.php тут всё давным давно за вас всё сделано. Выводит ошибку, потому что вы опрашиваете сервер через SOURCE протокол, а надо через GOLDSOURCE.
Т.е. SourceQuery :: SOURCE заменить на SourceQuery :: GOLDSOURCE
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя drivemaster
сообщение 17.2.2015, 13:11
Сообщение #12


Стаж: 17 лет

Сообщений: 266
Благодарностей: 79
Полезность: 246

Цитата(miRror @ 17.2.2015, 13:55) *
https://github.com/xPaw/PHP-Source-Query-Cl...master/View.php тут всё давным давно за вас всё сделано. Выводит ошибку, потому что вы опрашиваете сервер через SOURCE протокол, а надо через GOLDSOURCE.
Т.е. SourceQuery :: SOURCE заменить на SourceQuery :: GOLDSOURCE
в View.php выводится весь массив и вся инфа о сервере, а мне нужны были только некоторые переменные, для блока слайдера-мониторинга.

Отредактировал: drivemaster, - 17.2.2015, 14:23
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
umprex
сообщение 17.2.2015, 14:40
Сообщение #13


Иконка группы

Стаж: 16 лет
Город: Киев

Сообщений: 2909
Благодарностей: 4781
Полезность: 2197

onotole, он попросил что бы ему в $server выводило, я поменял переменную, да использовал if, else, мне так удобней чем через try, cathc. Не понимаю к чему твоё "Даладно? У меня сё работает", если к тому, что я написал о нон стим серверах, тогда у тебя магические ручки, ибо xPaw создавал класс без поддержки нон стим серверов, о чем сам писал.
Если ТС работает только с кс серварами, тогда данный класс нужно выкинуть, думаю понятно из-за чего.


Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя drivemaster
сообщение 17.2.2015, 16:36
Сообщение #14


Стаж: 17 лет

Сообщений: 266
Благодарностей: 79
Полезность: 246

Не мне класс нужен был, для вывода доп блока Сервера для стим сервера КС ГО. Для основных серверов, на странице использован LGSL, но так, как КС ГО должен идти в другом дизайне, пришлось использовать этот класс. Всё что хотел от этого класса, всё получил.

Отредактировал: drivemaster, - 17.2.2015, 16:38
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя onotole
сообщение 17.2.2015, 16:51
Сообщение #15


Иконка группы

Стаж: 13 лет

Сообщений: 1572
Благодарностей: 1119
Полезность: 1550

Меценат Меценат

Цитата(umprex @ 17.2.2015, 15:40) *
onotole, он попросил что бы ему в $server выводило, я поменял переменную, да использовал if, else, мне так удобней чем через try, cathc. Не понимаю к чему твоё "Даладно? У меня сё работает", если к тому, что я написал о нон стим серверах, тогда у тебя магические ручки, ибо xPaw создавал класс без поддержки нон стим серверов, о чем сам писал.
Если ТС работает только с кс серварами, тогда данный класс нужно выкинуть, думаю понятно из-за чего.

Выводить нужно там, где нужно. Сначала заполняешь переменные, делаешь чтото, очищаешь память и прочее, а потом выводишь то, что насобрал.
И с ностим серверами распрекраснейше он работает =)
Первый попавшийся сервер в мониторинге арены
Вывод инфы с этого сервера при помощи класса xPaw
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
umprex
сообщение 17.2.2015, 17:40
Сообщение #16


Иконка группы

Стаж: 16 лет
Город: Киев

Сообщений: 2909
Благодарностей: 4781
Полезность: 2197

onotole, https://github.com/xPaw/PHP-Source-Query-Class/issues/16
При написании мониторинга использовал данный класс, в итоге, пришлось писать свой. Не пойму, зачем спорить.

Хотя, возможно за последние пару мес он добавил поддержку нон стим, не уверен.


Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя miRror
сообщение 18.2.2015, 2:09
Сообщение #17


Стаж: 15 лет

Сообщений: 1151
Благодарностей: 1002
Полезность: 967

Меценат Меценат

Поддерживает класс нонстим сервера. Новый dproto просто не всегда дает получить информацию.
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя onotole
сообщение 18.2.2015, 8:26
Сообщение #18


Иконка группы

Стаж: 13 лет

Сообщений: 1572
Благодарностей: 1119
Полезность: 1550

Меценат Меценат

Цитата(umprex @ 17.2.2015, 18:40) *
onotole, https://github.com/xPaw/PHP-Source-Query-Class/issues/16
При написании мониторинга использовал данный класс, в итоге, пришлось писать свой. Не пойму, зачем спорить.

Хотя, возможно за последние пару мес он добавил поддержку нон стим, не уверен.

Я и не спорю. Я вывел инфу с ностим сервера прекрасно
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя Orty_Hart
сообщение 18.2.2015, 11:19
Сообщение #19
Стаж: 14 лет

Сообщений: 1399
Благодарностей: 408
Полезность: 725

drivemaster,

Просто скопируй в файл, и посмотри результат.

Пример всех выводов
Код
<?php
    require __DIR__ . '/SourceQuery/SourceQuery.class.php';
    
    // Edit this ->
    define( 'SQ_SERVER_ADDR', 'localhost' );
    define( 'SQ_SERVER_PORT', 27015 );
    define( 'SQ_TIMEOUT',     1 );
    define( 'SQ_ENGINE',      SourceQuery :: SOURCE );
    // Edit this <-
    
    $Timer = MicroTime( true );
    
    $Query = new SourceQuery( );
    
    $Info    = Array( );
    $Rules   = Array( );
    $Players = Array( );
    
    try
    {
        $Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE );
        
        $Info    = $Query->GetInfo( );
        $Players = $Query->GetPlayers( );
        $Rules   = $Query->GetRules( );
    }
    catch( Exception $e )
    {
        $Exception = $e;
    }
    
    $Query->Disconnect( );
    
    $Timer = Number_Format( MicroTime( true ) - $Timer, 4, '.', '' );
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Source Query PHP Class</title>
    
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <style type="text/css">
        .jumbotron {
            margin-top: 30px;
            border-radius: 0;
        }
        
        .table thead th {
            background-color: #428BCA;
            border-color: #428BCA !important;
            color: #FFF;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="jumbotron">
            <h1>Source Query PHP Class</h1>
            
            <p>This class was created to query game server which use the Source (Steamworks) query protocol.</p>
            
            <p>
                <a class="btn btn-large btn-primary" href="http://xpaw.me">Made by xPaw</a>
                <a class="btn btn-large btn-primary" href="https://github.com/xPaw/PHP-Source-Query-Class">View on GitHub</a>
                <a class="btn btn-large btn-danger" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">CC BY-NC-SA 3.0</a>
            </p>
        </div>
        
<?php if( isset( $Exception ) ): ?>
        <div class="panel panel-primary">
            <div class="panel-heading"><?php echo Get_Class( $Exception ); ?> at line <?php echo $Exception->getLine( ); ?></div>
            <p><b><?php echo htmlspecialchars( $Exception->getMessage( ) ); ?></b></p>
            <p><?php echo nl2br( $e->getTraceAsString(), false ); ?></p>
        </div>
<?php else: ?>
        <div class="row">
            <div class="col-sm-6">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th colspan="2">Server Info <span class="label label-<?php echo $Timer > 1.0 ? 'danger' : 'success'; ?>"><?php echo $Timer; ?>s</span></th>
                        </tr>
                    </thead>
                    <tbody>
<?php if( Is_Array( $Info ) ): ?>
<?php foreach( $Info as $InfoKey => $InfoValue ): ?>
                        <tr>
                            <td><?php echo htmlspecialchars( $InfoKey ); ?></td>
                            <td><?php
    if( Is_Array( $InfoValue ) )
    {
        echo "<pre>";
        print_r( $InfoValue );
        echo "</pre>";
    }
    else
    {
        if( $InfoValue === true )
        {
            echo 'true';
        }
        else if( $InfoValue === false )
        {
            echo 'false';
        }
        else
        {
            echo htmlspecialchars( $InfoValue );
        }
    }
?></td>
                        </tr>
<?php endforeach; ?>
<?php else: ?>
                        <tr>
                            <td colspan="2">No information received</td>
                        </tr>
<?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="col-sm-6">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Player</th>
                            <th>Frags</th>
                            <th>Time</th>
                        </tr>
                    </thead>
                    <tbody>
<?php if( Is_Array( $Players ) ): ?>
<?php foreach( $Players as $Player ): ?>
                        <tr>
                            <td><?php echo htmlspecialchars( $Player[ 'Name' ] ); ?></td>
                            <td><?php echo $Player[ 'Frags' ]; ?></td>
                            <td><?php echo $Player[ 'TimeF' ]; ?></td>
                        </tr>
<?php endforeach; ?>
<?php else: ?>
                        <tr>
                            <td>No players in da house</td>
                        </tr>
<?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th colspan="2">Rules</th>
                        </tr>
                    </thead>
                    <tbody>
<?php if( Is_Array( $Rules ) ): ?>
<?php foreach( $Rules as $Rule => $Value ): ?>
                        <tr>
                            <td><?php echo htmlspecialchars( $Rule ); ?></td>
                            <td><?php echo htmlspecialchars( $Value ); ?></td>
                        </tr>
<?php endforeach; ?>
<?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
<?php endif; ?>
    </div>
</body>
</html>
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
umprex
сообщение 18.2.2015, 14:13
Сообщение #20


Иконка группы

Стаж: 16 лет
Город: Киев

Сообщений: 2909
Благодарностей: 4781
Полезность: 2197

miRror, onotole, хз, это было и во время прошлой версии dproto, тоже не могу говорить что все нон стим не поддерживает, но такие сервера были. Ладно, уже немного отошли от темы, а автор, думаю, проблему решил.


Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
  Тема закрытаНачать новую тему
 
0 пользователей и 1 гостей читают эту тему: