PDA

View Full Version : How to make live stats images for your scripts



putonajonny
05-30-2012, 02:25 PM
Not yet complete...

I have had a few requests from people that like my live stats for some of my scripts, e.g.:

http://mytracker.net84.net/Stats/image.php

This tutorial is not just about how to create the image, but also how to collect the data. It assumes some php knowledge, but post any questions you have.

Contents:

Creating an SQL database
Using php and simba to collect data for your image
Collecting Stats from SRL Stats
Using php to create a stats image


1. Creating an SQL database
If you already have the data (or are using the data collected by SRL Stats then skip to section 3.

You are going to need a hosting service, I recomend 000webhost.com ($0.00 webhosting), you can use any that offer php and mySQL support, click the image below to go to 000.webhost.com:

http://www.000webhost.com/images/head.jpg (http://www.000webhost.com/order.php)



Sign up on that page, I would recommend you use their free subdomain since that is the only way you don't have to pay.
Once you have confirmed your email go to your control panel, go down to Software / Services and click on MySQL.
It will give you an option to "Create new database and user", do so.
Once you have go back to your control panel and select phpMyAdmin.
Click "Enter phpMyAdmin" on the database you just created.


You are now in phpMyAdmin, from here we will create your database.

You will see a box with the words "Create new table on database" above it, enter a name for your table here, You will only need one table for all of your script so don't give it something specific to a script. I'm going to call mine "Table1".
For the number of fields for now put 3 or 4, you can easily add more later.
You will be presented with something that looks like this:
http://i.imgur.com/THKlr.png
From here we need to come up with the names of our fields, since there is going to be no sensitive information in this table I shouldn't worry about the field names, if you ever do something that could possibly contain sensitive info then make sure you read up on it.
This is just like declaring the variables in simba, just they have slightly different names, we first of all want an ID field, set this to auto_increment and primary key (see image below).
We then want a script field, this field will contain the name of your script, you will notice a few selections for text, each of them can take a different number of characters:
TINYTEXT 256 bytes
TEXT 64 KiloBytes
MEDIUMTEXT 16 MegaBytes
LONGTEXT 4 GigaBytes
Since 256 bytes should be enough we can use TINYTEXT.
We then want a filed for all the variables we are going to use for example time and xp. There are different options for integers as well:
TINYINT Signed: -128 to 127. Unsigned: 0 to 255
SMALLINT Signed: -32768 to 32767. Unsigned: 0 to 65535
MEDIUMINT Signed: -8388608 to 8388607. Unsigned: 0 to 16777215
INT Signed: -2147483648 to 2147483647. Unsigned: 0 to 4294967295
BIGINT Signed: -9223372036854775808. Unsigned: 0 to 18446744073709551615
Think about the maximum size of each of the fields, for example if you measure time in seconds it is going to want a different variable than if you measure every millisecond.
My fields then look like this:
http://i.imgur.com/nTN0t.png
I plan to make it measure each second so the field will take up to 194 days, if you think your script will be run longer than this you may want to measure to less precision or use a different variable.
If you want to add more fields to measure things like monsters killed or rocks mined then do so.
Click Save.
You have now made your database, now we need to create a record which will the values will be increased in each time somebody runs your script.
Click on the insert tab at the top, leave the ID field blank, put in the name of your script without any ' or " for example Sorceress's Garden would be Sorceresss Garden.
For each of the other fields put 0, as this is what we are going to start on.
Click Go, then go to the browse tab, you should see something like this:
http://i.imgur.com/XbfIE.png
Notice how the ID field got a value automatically, you can do this for all of your scripts:
http://i.imgur.com/L3iAm.png
That's it, we have now made our database!


2. Using php and simba to collect data for your image
If you don't know any php this part won't make much sense to you, I suggest you find an online tutorial.
We are going to use the PostHTTPPageEx function in simba to do this, but first of all we will create the php part.
First of all an easy step, let's define our MySQL login details

<?PHP

$user_name = "usename"; //Username for the account you created earlier
$pass_word = "password"; //Password for the account you created earlier
$database = "database"; //The name of the database you created earlier
$server = "MySQLServer"; //With 000webhost this can be found by going to your control panel then clicking MySQL


?>
Then we are going to get the post data for our variables, note that variable names (like $time and $xp below) can't have spaces and must start with a letter

$time = $_POST['time'];//The things in the [] can be anything you want, but remember these for later
$xp = $_POST['xp'];
Then we are going to do something just incase your script messed up and reported an incorrect value:

if($time <= 0)
$time = 0;

if($xp <= 0)
$xp = 0;
Now some standard SQL functions

$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
$db_found is a boolean as to whether the database was found, we therefore need to do something like:

if ($db_found) {

}else
print "Database not found";
Then we want some more SQL functions to retrieve the results in the table.

$SQL = "SELECT * FROM Table1 WHERE Script = MyScript";//Or whatever you called your table and script
$result = mysql_query($SQL);
Now $result is a boolean as to whether it found your table was found, so therefore:

if($result){

}else
print "Table not found";
We then use this to get the data in the table:

while ($db_field = mysql_fetch_assoc($result)){

$time = $db_field['Time'] + $time;
$xp = $db_field['XP'] + $xp;

}
Now $time contains the amount of time that was in the table and the amount that we are committing, same with $xp.
Then we want to use an SQL statement to update the fields:

$SQL = "UPDATE `MyTable` SET `XP` = '".$xp."', `Time` = '".$time."' WHERE `Script` = MyScript";//You need to put all of your variables in this.
$result = mysql_query($SQL);
if($result)
print "True";
else
print "False";

Your whole script should look something like this:

<?PHP

$user_name = "usename"; //Username for the account you created earlier
$pass_word = "password"; //Password for the account you created earlier
$database = "database"; //The name of the database you created earlier
$server = "MySQLServer"; //With 000webhost this can be found by going to your control panel then clicking MySQL

$time = $_POST['time'];//The things in the [] can be anything you want, but remember these for later
$xp = $_POST['xp'];

if($time <= 0)
$time = 0;

if($xp <= 0)
$xp = 0;

$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

$SQL = "SELECT * FROM Table1 WHERE Script = MyScript";//Or whatever you called your table and script
$result = mysql_query($SQL);

if($result){
while ($db_field = mysql_fetch_assoc($result)){

$time = $db_field['Time'] + $time;
$xp = $db_field['XP'] + $xp;

}

$SQL = "UPDATE `MyTable` SET `XP` = '".$xp."', `Time` = '".$time."' WHERE `Script` = MyScript";//You need to put all of your variables in this.
$result = mysql_query($SQL);
if($result)
print "True";
else
print "False";

}else
print "Table not found";

}else
print "Database not found";

?>

Then in simba:
AddOnTerminate('SendData');//To make it send the data

Function SendData : Boolean;
Var
i : integer;
begin

i := InitializeHTTPClientWrap(False); //this creates a client

AddPostVariable(i, 'time', IntToStr(GetTimeRunning / 1000));//This adds our info to the client
AddPostVariable(i, 'runs', IntToStr(XPGained));

Result := Pos('true', Lowercase(PostHTTPPageEx(i, 'http://mywebsite.net/MyPage.php'))) <> 0;//Then this posts it

FreeHTTPClient(i);//Remember to free it

end;


3. Collecting Stats from SRL Stats
//To do

4. Using php to create a stats image
Most things from now on are credits to Frement
First of all we need to define the database info like earlier:

<?PHP

$user_name = "usename"; //Username for the account you created earlier
$pass_word = "password"; //Password for the account you created earlier
$database = "database"; //The name of the database you created earlier
$server = "MySQLServer"; //With 000webhost this can be found by going to your control panel then clicking MySQL

$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

$SQL = "SELECT * FROM Table1 WHERE Script = MyScript";//Or whatever you called your table and script
$result = mysql_query($SQL);

if($result){
while ($db_field = mysql_fetch_assoc($result)){

$time = $db_field['Time'];
$xp = $db_field['XP'];

}

}else
print "DB not found";


?>
Most things from now on are credits to Frement
We want to tell the page what type of page it is:

header("Content-type: image/png");
Then tell it the font path:

putenv("GDFONTPATH=".realpath("."));
We then need to create the image:

$img = imagecreatefrompng("blank.png"); //Where blank.png is stored in the same directory as this php file
If you want colours you can define them like this:

$color["yellow"] = imagecolorallocate( $img, 255, 255, 0 );
$color["white"] = imagecolorallocate( $img, 255, 255, 255 );
$color["green"] = imagecolorallocate( $img, 0, 255, 0 );
$color["orange"] = imagecolorallocate( $img, 254, 179, 0 );
$color["purple"] = imagecolorallocate( $img, 128, 0, 128 );
$color["dblue"] = imagecolorallocate( $img, 37, 84, 199 );
Now to display the image we are going to need 2 functions, place these in your script:

function formatMilliseconds($milliseconds) {
$seconds = floor($milliseconds / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$days = floor($hours / 24);
$milliseconds = $milliseconds % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
$hours = $hours % 24;

if($days == 0){
$format = '%uhours, %02uminutes and %02u seconds';
$time = sprintf($format, $hours, $minutes, $seconds);
return rtrim($time, '0');
}else{
$format = 'Úys, %uhours, %02uminutes and %02u seconds';
$time = sprintf($format, $days, $hours, $minutes, $seconds);
return rtrim($time, '0');
}

}

function imagettftextshadow($image, $size, $angle, $x, $y, $color, $fontfile, $text) { //credits to Frement
imagettftext($image, $size, $angle, $x + 1, $y + 1, imagecolorallocate($image, 0, 0, 0), $fontfile, $text);
imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text);
}
That first one turns milliseconds to time in the format Xdays, YHours, ZMinutes and nSeconds.
The second one adds shadow to our text, now let's use them:

function imagettftextshadow($image, $size, $angle, $x, $y, $color, $fontfile, $text)
In this function, image is the image we are adding the text to, size is the size of the text, angle is the angle it puts the text at (0 is horizontal) x and y are the co-ordinates that it puts the text, color is the colour of the text, fontfile is the name of the fontfile you are using, you can download some here (http://www.1001freefonts.com/), this needs to be placed in the same directory as the php file. Text is the text you are displaying.

imagettftextshadow($img, 20, 0, 10, 23, $color["dblue"], "myfont.ttf", "MyScript");
imagettftextshadow($img, 10, 0, 205, 23, $color["green"], "myfont.ttf", "Version: 1");
We then do that for our variables:

imagettftextshadow($img, 12, 0, 10, 50, $color["orange"], "myfont.ttf", "XP Gained: ");
imagettftextshadow($img, 12, 0, 90, 50, $color["purple"], "myfont.ttf", number_format($xp)); //Number_Format adds commas every thousand, you don't need to do this
imagettftextshadow($img, 12, 0, 10, 70, $color["orange"], "myfont.ttf", "Time Run: ");
imagettftextshadow($img, 12, 0, 90, 70, $color["purple"], "myfont.ttf", formatMilliseconds($time * 1000));//I collect time in seconds, so it needs to be multiplied by 1000
We then want to display our image, for that we use:

imagepng($img);
imagedestroy($img);
Overall it should look like:

<?PHP

function formatMilliseconds($milliseconds) {
$seconds = floor($milliseconds / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$days = floor($hours / 24);
$milliseconds = $milliseconds % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
$hours = $hours % 24;

if($days == 0){
$format = '%uhours, %02uminutes and %02u seconds';
$time = sprintf($format, $hours, $minutes, $seconds);
return rtrim($time, '0');
}else{
$format = 'Úys, %uhours, %02uminutes and %02u seconds';
$time = sprintf($format, $days, $hours, $minutes, $seconds);
return rtrim($time, '0');
}

}

function imagettftextshadow($image, $size, $angle, $x, $y, $color, $fontfile, $text) {
imagettftext($image, $size, $angle, $x + 1, $y + 1, imagecolorallocate($image, 0, 0, 0), $fontfile, $text);
imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text);
}

$user_name = "";
$pass_word = "";
$database = "";
$server = "";

$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);


if ($db_found) {

$SQL = "SELECT * FROM Table1 WHERE Script=MyScript";
$result = mysql_query($SQL);
if($result){
while ($db_field = mysql_fetch_assoc($result)){

$xp = $db_field['XP'];
$time = $db_field['Time'];
}

header("Content-type: image/png");
putenv("GDFONTPATH=".realpath("."));

$img = imagecreatefrompng("blank.png");

$color["yellow"] = imagecolorallocate( $img, 255, 255, 0 );
$color["white"] = imagecolorallocate( $img, 255, 255, 255 );
$color["green"] = imagecolorallocate( $img, 0, 255, 0 );
$color["orange"] = imagecolorallocate( $img, 254, 179, 0 );
$color["purple"] = imagecolorallocate( $img, 128, 0, 128 );
$color["dblue"] = imagecolorallocate( $img, 37, 84, 199 );

imagettftextshadow($img, 20, 0, 10, 23, $color["dblue"], "sans.ttf", "MyScript");
imagettftextshadow($img, 10, 0, 205, 23, $color["green"], "sans.ttf", "Version: 1");
imagettftextshadow($img, 12, 0, 10, 50, $color["orange"], "sans.ttf", "XP Gained: ");
imagettftextshadow($img, 12, 0, 90, 50, $color["purple"], "sans.ttf", number_format($xp));
imagettftextshadow($img, 12, 0, 10, 70, $color["orange"], "sans.ttf", "Time Run: ");
imagettftextshadow($img, 12, 0, 90, 70, $color["purple"], "sans.ttf", formatMilliseconds($time * 1000));

imagepng($img);
imagedestroy($img);
}else
print "False";

}
else
print "DB not Found, please report this";


?>

Warning
If you don't know about SQL injection attacks I suggest you look them up, 000webhost will block most of them, but be aware...

Credits to Frement for teaching me almost everything I know about putting text on images :)

Shatterhand
05-31-2012, 08:10 AM
Nice work, thanks jonny! :)
My question is: so basically u using own site instead of srl stats? What are the (dis)advantages of it?

Wizzup?
05-31-2012, 10:26 AM
You could also use SRL Stats API, json should be easily parseable: http://stats.villavu.com/api/user/235/script/21

Shatterhand
05-31-2012, 10:54 AM
You could also use SRL Stats API, json should be easily parseable: http://stats.villavu.com/api/user/235/script/21
Yea but variables doesnt work (for me at least).

putonajonny
05-31-2012, 11:50 AM
You could also use SRL Stats API, json should be easily parseable: http://stats.villavu.com/api/user/235/script/21

Yeah that's going to go in 3. Collecting Stats from SRL Stats just haven't done it yet :)

Flight
05-31-2012, 02:48 PM
You could also use SRL Stats API, json should be easily parseable: http://stats.villavu.com/api/user/235/script/21

Ah what fun.

Anyways, this is a great tutorial, nicely done indeed. :thumbsup:

Kyle Undefined
05-31-2012, 03:10 PM
You could also use SRL Stats API, json should be easily parseable: http://stats.villavu.com/api/user/235/script/21

That's what my stats site does :)

Shatterhand
05-31-2012, 05:48 PM
Ok I got that site and database. Stupid question: what should I do with the php code? How can I compile it (make it run)?
This seems difficult to me, I should start learning php from the beginning. You know any good sites/tutorials for it? :)

putonajonny
05-31-2012, 06:18 PM
Ok I got that site and database. Stupid question: what should I do with the php code? How can I compile it (make it run)?
This seems difficult to me, I should start learning php from the beginning. You know any good sites/tutorials for it? :)

You just upload the page (with a .php extension) to your website, it is compiled and run on the server

This is a good beginners tutorial:
http://www.homeandlearn.co.uk/php/php.html

Shatterhand
06-01-2012, 09:16 AM
OMG thanks! PHP is kool! :D
http://shatterhand.comuv.com/ChaosMossKiller/stats.php

putonajonny
06-01-2012, 10:03 AM
OMG thanks! PHP is kool! :D
http://shatterhand.comuv.com/chaosmosskiller.php

nice image :)

Shatterhand
06-01-2012, 12:05 PM
Trying to set up my own sql database, but I cannot connect to it.

$user_name = "username";
$pass_word = "pass";
$database = "a1409571_stats";
$server = "server26.000webhost.com";

$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);

Host 'my ip' is not allowed to connect to this MySQL server...
I tried username/pass with the ones using for 000webhost.com, and the ones using for my sql.
Edit: W00T im members! :D

Shatterhand
06-07-2012, 01:21 PM
Can you help me with that jonny, please? :)

putonajonny
06-07-2012, 01:52 PM
Can you help me with that jonny, please? :)

Are you sure the username and password are correct?

Kyle Undefined
06-07-2012, 01:53 PM
Are you trying to run it locally or actually on the webhost.com servers? Most hosting companies don't allow you to connect to their databases unless it's from their IPs.

Shatterhand
06-07-2012, 02:06 PM
Are you trying to run it locally or actually on the webhost.com servers? Most hosting companies don't allow you to connect to their databases unless it's from their IPs.
Im trying to run it with wamp server (local I guess). Im using the database of that site what jonny posted.
EDIT: so no way to test it out locally?

Kyle Undefined
06-07-2012, 04:54 PM
Im trying to run it with wamp server (local I guess). Im using the database of that site what jonny posted.
EDIT: so no way to test it out locally?

Yeah, you're going to have to upload your PHP files to that host to test it.

Silent
06-11-2012, 09:31 PM
Im trying to run it with wamp server (local I guess). Im using the database of that site what jonny posted.
EDIT: so no way to test it out locally?

Either do what Kyle suggested or look for a place in the control panel for remote Sql connections. Some hosts have it, others do not, just depends.

If you have a wamp server you should actually be able to test everything locally.. Wamp includes mysql if I remember correctly...and php. Just test everything on your local system, then export the database and use it with the web-host for actual deployment. :)

Frement
06-11-2012, 09:51 PM
You could've credited. I know it's not a big deal, but still :( (And sorry for off-topic)

J J
01-01-2013, 11:14 PM
Thanks for the tutorial :) Using this together with the help of Brad/Olly/Kyle I managed to get it working :P