Jump to content

[TUT] PHP SDK


FatalTerror

Do you like this tutorial ?  

115 members have voted

  1. 1. Do you like this tutorial ?

    • Yes
      102
    • No
      13


Recommended Posts

logo_php.png

[Tutorial] PHP SDK

Hi everybody!

Today, it's the new year and i will make a tutorial for this community... It's my gift :mrgreen:

This tutorial is to teach to you how use the PHP SDK and what we can do with it.

The tutorial is offered by MTAScripts.net. Enjoy 8)

Summary

  • What is the PHP SDK
  • What we can do with it
  • How to install
  • How to use (SERVER)
  • How to use (WEB)
  • Download a demo

What is the PHP SDK

To begin, PHP is a dynamic programming language web. Why we say dynamic ? Because we can interact with the user and the webserver.

The PHP is the principal dynamic language used in the web with the HTML.

We can call this language "SUPER PHP" because he can make everything...

Examples:

  • Facebook.com
  • MTASA.com
  • Twitter.com
  • Every forums...
  • And more

Okey, we know what is the PHP, now the SDK ?

SDK mean Software Development Kit, it's a library allow to developpers to make his applications.

Multiple plateforms propose his SDK. Just search on Google :mrgreen:

Examples:

  • Facebook SDK
  • Have so much... Search on Google (Google have too his SDK) :mrgreen:

For continue this tutorial, you must download the PHP SDK from MTA.

Download

What we can do with it

The PHP SDK from MTA offer much possibility.

You can do everything with it if you have a great imagination :)

Examples ?

  • Login the player
    When the user join the server and he must login, if he have allready a login in the forum. We login the player with it
    And if he don't have, we create a new account in the server AND in the forum 8)
  • Stats of the player
    If the player play in the server and if he have an account in the server and the forum.
    We can show the stats of the player in the forum.
  • Facebook
    This is more hard but ITS POSSIBLE !
    If the player is logged in Facebook, the server send a request in the web and the web send a request to Facebook.
    If Facebook confirm, Facebook send informations to the webserver and the server will return this.
    So if you have an login panel, you can make a button "Login with Facebook".

I don't will write my ideas, find yours :D

So you can see, if you have great ideas... You can make some big things :mrgreen:

How to install

We attack ! :twisted:

First, you must:

  • A website
  • A FTP account of the website
  • Client FTP (Filezilla, ...)
  • The library PHP SDK

For this tutorial, i will use a fake website.

Now we can start :)

You must create a folder in the root of your website.

We will can him "MTA" :)

Result: http://www.yourwebsite.com/MTA

Now, we will create a new folder in the folder MTA

We call him "sdk".

Result: http://www.yourwebsite.com/MTA/sdk

Now your extract the mtaphpsdk_0.4.zip file into sdk folder.

You will have much files in this folder.

The principal file is mta_sdk.php.

Now you can access to the sdk via the web.

Result: http://www.yourwebsite.com/MTA/sdk/mta_sdk.php

If you don't have this result, try again 8)

Now, you create a new PHP File.

Every PHP files have the extention ".php" or ".php3" (for the new version)

You go to the MTA folder (http://www.yourwebsite.com/MTA) and you create a PHP file with the name "test"

Result: http://www.yourwebsite.com/MTA/test.php

You open this file with your text editor (Notepad++, Eclypse, Sublime Text, ...)

We will include the library to the file.

Before we start to include, you will start the php file.

For do it you write the balise PHP

Start: <?php

Close: ?>

  
<?php 
-- Your code here 
?> 
  

We have start the PHP file, now we want include "mta_sdk.php" to our file "test.php".

For do it, you must use the function include()

EDIT: The Include function work, but for more capacities. Use require function.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

For informations, every functions on PHP must finish with ";"

Now we include the file using include()

  
<?php 
require "sdk/mta_sdk.php"; 
?> 
  

The library is successfully inclued, now our library are installed :)

If you want be sure, you can access to this file (http://www.yourwebsite.com/MTA/test.php)

If you have an error, try again :mrgreen:

How to use (Server)

Ah :) The LUA part 8)

For start, you must create an resource in your server (local or not)

We will call him... "test".

You know how create an resource, if you don't know.. You are in the S.H.I.T :lol:

In your resource, you will have 3 files

  • Meta.xml
  • Client.lua
  • Server.lua

  
<meta> 
    <info name="My Test Script" author="FatalTerror" description="My first resource with PHP SDK" version="1.0.0" type="script"></info> 
     
    <script src="client.lua" type="client"></script> 
    <script src="server.lua" type="server"></script> 
</meta> 
  

Your client and server files are empy for a moment.

Before we start !

You must give admin right to the resource, we will use a function require admin rights.

You can do it with the Admin Panel or in the ACL.xml

More infos: Wiki Page

To start, you open the server.lua with your text editor and you write it.

  
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), 
function() 
     
  
end) 
  
function result() 
  
end 
  

Very simple code, 1 event when the resource start and a function "result".

For call an file in the web, we use the function callRemote().

This function allows you to call functions that have been exported with HTTP access by other MTA servers. The calls are asynchronous so you do not get an immediate result from the call, instead a callback function you specify is called when the call returns.

You can also use this function to access a standard web page on a server you own by specifying the URL. The arguments you specify to callRemote are passed to the web page using HTTP POST as a JSON array. This will always have an array as the root element. The page must return a JSON formated *array* in the page's body with the results of the call (or an empty array if there are no results).

You can use the PHP SDK to create PHP pages that can be called by this function. See the PHP SDK page for an example.

In the case when the call fails, a string containing "ERROR" followed by an integer containing the error reason will be passed to the callback function. The reason for failure will be similar to errors found with websites - file not found, server not found and timeouts.

So, we will use this function with basic parameters.

bool callRemote ( string URL, callback callbackFunction, [ arguments... ] ) 

Explain:

  • The url is the PHP file you want call.
  • The callback function is the function will call the website when the website return parameters.
  • The arguments are the infos you will send to the website.

Write it into the event handler.

  
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), 
function() 
    callRemote ("http://www.yourwebsite.com/MTA/test.php", result, "Hello") 
end) 
  

This will send the argument "Hello" to the test.php file.

We will see in the next step how get this argument in PHP file.

Imagine... We send 1 argument to the web and we want get 1 other argument (the name of ... my cat, YES My cat rockz ! )

The PHP file will return this argument and we will get it via the result function. Remember?

This function alone... (Poor function...)

  
function result(value) 
 if value ~= "ERROR" then 
  
 end 
end 
end 
  

If have an value, we continue

Now we have the cat's name, we show it with a simple outputChatBox()

  
function result(value) 
if value ~= "ERROR" then 
outputChatBox("Hello Mr."..value, getRootElement()) 
end 
end 
  

Great, we have finish this part. You can see, ITS SIMPLE OF SIMPLE

How to use (Web)

The web part start ! Get ready...Prepare your keyboard . GO !

To start, open your test.php file with your text editor.

And normally, we had already written the code in the file.

After the include (remember?) we will get the argument sended via the server.

How ? Using the mta::getInput() !

This function get arguments in an array.

  
$table = mta::getInput(); 
  

Yeah ! We have our table with informations

You are alive ? Okey !

  
$table = mta::getInput(); 
$text = $table[0]; 
  

Hm.. We get the argument of the table using this method and we set the argument into $text.

Small check if have an value...

  
$table = mta::getInput(); 
$text = $table[0]; 
if(isset($text)){ 
  
} 
  

Great.. We give a name of the cat ? Let me search.. Padawan ?

  
$table = mta::getInput(); 
$text = $table[0]; 
if(isset($text)){ 
$cat = "Padawan"; 
  
} 
  

Now we return $cat to the server using the function mta::doReturn()

  
$table = mta::getInput(); 
$text = $table[0]; 
if(isset($text)){ 
$cat = "Padawan"; 
mta::doReturn($cat); 
} 
  

Perfect !

Now when you start the script, he will send 1 info to the website and the website will return a thing... and this thing is the name of my cat

And when the server have the name of the cat, he say hello to him

Try it

Schema

mini_120101071248384531.jpg

Example 1: Use PHP/MYSQL

In this example, we will see what we can do with the PHP & the database MySQL.

Here, isn't the MySQL of the server but of the website.

Require things:


  • MySQL database
  • Read the tuto

OK, let's start.

In this tutorial, we will make list of who is online in your server and store it on database.

And for finish, show it.

First thing we will do, create a table in the MYSQL Database.

For that, we will store 3 things.

  • ID
  • Player name
  • Serial

Why the serial ? I don't know but it's usefull to store it

SQL Code:

  
CREATE TABLE  `DATABASE_NAME`.`players` ( 
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , 
`player` TEXT NOT NULL , 
`serial` TEXT NOT NULL 
) ENGINE = MYISAM ; 
  

Remplace DATABASE_NAME per the database name...

I don't explain this code cuz it's to much simple. I think you will learn it fast.

Create a new resource on your server. We call him "web".

In this resource, we have 2 files.


  • Meta.xml
  • Server.lua

On server.lua, we will put an event, when the map change (It's more usefull for race servers).

A council ! Never put an callRemote() when the player join !

Why ? It makes lag. If you have a big dedicated server, you can do it.

  
addEventHandler("onGamemodeMapStart", getRootElement(), 
function(theMap) 
  
  
end) 
  

Well, it's okey for this step.

Now we will create a new function to get an table with the player name without his hexcode.

  
addEventHandler("onGamemodeMapStart", getRootElement(), 
function(theMap) 
  
  
end) 
  
function getPlayersName() 
    local playerslist = {} 
    for i,p in ipairs (getElementsByType("player")) do 
        local thep = string.gsub(getPlayerName(p), "#%x%x%x%x%x%x", "") 
        table.insert(playerslist,tostring(thep)) 
    end 
    return playerslist 
end 
  

Not very hard for the moment. We create an callRemote in the event.

Like this:

addEventHandler("onGamemodeMapStart", getRootElement(), 
function(theMap) 
    local playerList = getPlayersName() 
    if playerList then 
        callRemote("http://wwww.website.com/MTA/players.php", returnFunction, playerList) 
    end 
end) 
  
function returnFunction(value) 
    if value ~= "ERROR" then 
         
    end 
end 
  
function getPlayersName() 
    local playerslist = {} 
    for i,p in ipairs (getElementsByType("player")) do 
        local thep = string.gsub(getPlayerName(p), "#%x%x%x%x%x%x", "") 
        table.insert(playerslist,tostring(thep)) 
    end 
    return playerslist 
end 

Put a small message to check if the player list is successfully save with outputDebugString().

Damn, let's start with the PHP.

Create a new document PHP in your website like that:

http://www.website.com/MTA/players.php

In this document, you include the PHP SDK AND the MySQL Connexion !

What is that? You must put 2 lines of code to connect the page to the MySQL database.

The line are:

  
        $base = mysql_connect ('127.0.0.1', 'USERNAME', 'PASSWORD');  
    mysql_select_db ('DATABASE_NAME', $base);  
  

You check if you have any errors, just access to your page.

TO BE CONTINUED... (I go to school xD)

It's the end of this tutorial, i hope it will be useful :P

Good luck and have fun :)

© MTAScripts.net, All rights reserved

Edited by Guest
  • Thanks 2
Link to comment
ok so if i want to send some stats from my script like death count i make a variable and uses that in callremote instead of Hello but now how can i get that into HTML part of the webstie ?

It's not very hard, you have just to stock the stats of player in database MySQL :wink:

Example:

  
local deads = getElementData(player, "deads") 
local wins = getElementData(player, "wins") 
local player = getPlayerName(player) 
  
callRemote("http://www.yourwebsite.com/MTA/test.php", result, deads, wins, player) 
  

And you get these informations in PHP file

  
$table = mta::getInput(); 
$deads= $table[0]; 
$wins = $table[1]; 
$player = $table[2]; 
  
// Send infos in MySQL 
$base = mysql_connect ('host', 'login', 'password');  
mysql_select_db ('database', $base);  
  
$sql = 'INSERT INTO player_stats VALUES("$player", "'.$deads.'", "'.$wins.'") '; 
mysql_query($sql); 
mysql_close(); 
  
// Return true if is added 
mta::doReturn(true); 
  

Now, in another file, you can get the informations only using PHP & MySQL ;)

Example, you have a file with stats of every players have played in your server

<?php 
    $base = mysql_connect ('host', 'login', 'password');  
    mysql_select_db ('database', $base);  
     
    $sql = 'SELECT * FROM player_stats'; 
    $req = mysql_query($sql); 
    while($data = mysql_fetch_array($req)){ 
        $playername = $data['name']; 
        $deads = $data['deads']; 
        $wins = $data['wins']; 
        echo "<b>$playername</b><br /> 
        Wins: $wins<br /> 
        Deads: $deads<br />"; 
    } 
    mysql_close(); 
?> 

Link to comment
ok so if i want to send some stats from my script like death count i make a variable and uses that in callremote instead of Hello but now how can i get that into HTML part of the webstie ?

It's not very hard, you have just to stock the stats of player in database MySQL :wink:

Example:

  
local deads = getElementData(player, "deads") 
local wins = getElementData(player, "wins") 
local player = getPlayerName(player) 
  
callRemote("http://www.yourwebsite.com/MTA/test.php", result, deads, wins, player) 
  

And you get these informations in PHP file

  
$table = mta::getInput(); 
$deads= $table[0]; 
$wins = $table[1]; 
$player = $table[2]; 
  
// Send infos in MySQL 
$base = mysql_connect ('host', 'login', 'password');  
mysql_select_db ('database', $base);  
  
$sql = 'INSERT INTO player_stats VALUES("$player", "'.$deads.'", "'.$wins.'") '; 
mysql_query($sql); 
mysql_close(); 
  
// Return true if is added 
mta::doReturn(true); 
  

Now, in another file, you can get the informations only using PHP & MySQL ;)

Example, you have a file with stats of every players have played in your server

<?php 
    $base = mysql_connect ('host', 'login', 'password');  
    mysql_select_db ('database', $base);  
     
    $sql = 'SELECT * FROM player_stats'; 
    $req = mysql_query($sql); 
    while($data = mysql_fetch_array($req)){ 
        $playername = $data['name']; 
        $deads = $data['deads']; 
        $wins = $data['wins']; 
        echo "<b>$playername</b><br /> 
        Wins: $wins<br /> 
        Deads: $deads<br />"; 
    } 
    mysql_close(); 
?> 

K so if i want to fill an html file with that how ? xD im a noob at PHP...

Link to comment
ok so if i want to send some stats from my script like death count i make a variable and uses that in callremote instead of Hello but now how can i get that into HTML part of the webstie ?

-SNIP :o-

Now, in another file, you can get the informations only using PHP & MySQL ;)

Example, you have a file with stats of every players have played in your server

-SNIP :o-

K so if i want to fill an html file with that how ? xD im a noob at PHP...

The third code is for displaying from mysql

Link to comment
Solidsnake14 said:

It's his tutorial, he can make it however he want's to.

He can do anything he want, that's OBVIOUS (THIS MEANS WE CAN USE PORN IN OUR TUTORIALS :))

But myonlake was just saying that actually he didn't like the emoticons, not saying "remove them or I will consider your tutorial as a noob one" or something related.

Btw, nice tutorial dude. I might use it for some of my projects.

Link to comment
  • 3 weeks later...

Thanks, and nice scripts,

I really learned how to use the php sdk now.

NIce Script How about a Email thing like this 'Email from MTA Welcome' and it goes to the peoples email that they have used in a Textbox that ...

You will have to use your php knowledge for that.

Link to comment
  • 1 month later...

The MYSQL is just for store informations.

You can use too Text file, XML file, etc...

For a player list per example.

You create a table with the LUA with players name like that

  
function getPlayersName() 
    local playerslist = {} 
    for i,p in ipairs">ipairs (getElementsByType("player")) do 
        local thep = string.gsub(getPlayerName(p), "#%x%x%x%x%x%x", "") 
        table.insert(playerslist,tostring">tostring">tostring(thep)) 
    end 
    return playerslist 
end  
  
 

(Don't copy xD, the forum change things :shock: )

Now you have a table of all members, you just being send this table via CallRemote

For the MySQL table, you must have a table contain 2 column.

ID - Player

When the script will receive the table contain users

He will erase the table and do a loop and add into the table an id(auto_increment) and the player name.

Example:

  
// Vide la table 
    $sql = 'DELETE FROM server_players';  
    mysql_query($sql); 
  
    $x = 0; 
    $start = 0; 
    while($x <= $players) { 
        $start = $start+1; 
        if(isset($playerlist[$start])){ 
            $sql = 'INSERT INTO server_players VALUES("", "'.$playerlist[$start].'", "Guest", "Guest")'; 
            mysql_query($sql); 
        } 
        $x++;  
    } 
  

You can see an example in my team website: http://www.amg-mta.net

Good luck.

Link to comment
  • 3 months later...

If i may make an suggestion:

Change the function "call" in php_sdk.php to:

  
    function call ( $function ) 
    { 
        $val = func_get_args ( ); 
        array_shift ( $val ); // Remove $function parameter. 
         
        return $this->server->callFunction ( $this->name, $function, $val ); 
    } 
  

Also, please don't place vars within quotes, it's old, and it will be blocked in the future, like ex: echo "$array['hello']";, this can be fixed by using brackets: { }, as you do now, but please, use the right php syntax like this:

  
// Bad: 
throw new Exception( "Unable to send request to {$host}:{$port}" ); 
  
// Good: 
throw new Exception ( 'Unable to send request to ' . $host . ':' . $port ); 
// echo example: 
echo 'Welcome back ' . $playername; 
  

P.s. also use the correct syntax for mysql query's:

mysql_query ( "SELECT fieldname FROM table WHERE id = '1' LIMIT 1" ); // This is the correct use of the quotes, as it ment to be.

-----

For the users of this script:

* Please build in mysql error handling, so you know whats wrong!

* Set the right indexes in the database table. (If you don't: your database and mta server will lag very badly! (if you have more then 5000 rows in an table))

* Keep in mind: Mysql injection! Use http://us.php.net/mysql_real_escape_string

* Choose the right characterset for your database and tables, otherwise characters like ö won't work.

P.s. Max 2 code blocks? Hmmm...

Happy coding!

:D

Link to comment
  • 2 weeks later...
If i may make an suggestion:

Change the function "call" in php_sdk.php to:

  
    function call ( $function ) 
    { 
        $val = func_get_args ( ); 
        array_shift ( $val ); // Remove $function parameter. 
         
        return $this->server->callFunction ( $this->name, $function, $val ); 
    } 
  

Also, please don't place vars within quotes, it's old, and it will be blocked in the future, like ex: echo "$array['hello']";, this can be fixed by using brackets: { }, as you do now, but please, use the right php syntax like this:

  
// Bad: 
throw new Exception( "Unable to send request to {$host}:{$port}" ); 
  
// Good: 
throw new Exception ( 'Unable to send request to ' . $host . ':' . $port ); 
// echo example: 
echo 'Welcome back ' . $playername; 
  

P.s. also use the correct syntax for mysql query's:

mysql_query ( "SELECT fieldname FROM table WHERE id = '1' LIMIT 1" ); // This is the correct use of the quotes, as it ment to be.

-----

For the users of this script:

* Please build in mysql error handling, so you know whats wrong!

* Set the right indexes in the database table. (If you don't: your database and mta server will lag very badly! (if you have more then 5000 rows in an table))

* Keep in mind: Mysql injection! Use http://us.php.net/mysql_real_escape_string

* Choose the right characterset for your database and tables, otherwise characters like ö won't work.

P.s. Max 2 code blocks? Hmmm...

Happy coding!

:D

Well, hi...

I don't make this sdk, i just learn for some guys how use it.

Sometimes i can use old syntax in my code that is true but it work x)

Regards, FatalTerror.

Link to comment
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...