PHP - Php+mysql Game Server Player Database
Hello. I just inherited a game stats system but it's not working properly. I'm gonna post the entire script: <?php error_reporting(E_ERROR | E_WARNING | E_PARSE); $servername = "127.0.0.1"; $username = ""; $password = ""; $dbname = ""; $addresses = Array(); $nicknames = Array(); $servers = Array(); $times = Array(); $find_ip = $_GET["ip"]; $find_name = $_GET["nick"]; if(isset($_GET["format"])) { $format = $_GET["format"]; } else { $format = "include"; } $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { ReturnError("NO_CONNECTION"); } function ReturnError($error) { global $format; if($format == "mod") die("!DATA!ERROR:" .$error. "!DATA!"); else die("ERROR:" . $error); } function ReturnData($data) { global $format; if($format == "mod") die("!DATA!SUCCESS:" .$data. "!DATA!"); else die("SUCCESS:" .$data); } function GetServerIP() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP']; else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR']; else return $_SERVER['REMOTE_ADDR']; } function GetTimestamp() { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $now->format("m-d-Y H:i:s.u"); $local = $now->setTimeZone(new DateTimeZone('Europe/Prague')); return $local->getTimestamp(); } function GetFormatedTime() { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $now->format("m-d-Y H:i:s.u"); $local = $now->setTimeZone(new DateTimeZone('Europe/Prague')); return $local->format("Y-m-d H:i:s.u"); } function AddAddress($addr) { global $addresses; if(in_array($addr, $addresses, true)) { return false; } else { array_push($addresses, $addr); return true; } } function AddTime($time) { global $times; if(in_array($time, $times, true)) { return false; } else { array_push($times, $time); return true; } } function AddNickname($nick) { global $nicknames; if(in_array($nick, $nicknames, true)) { return false; } else { array_push($nicknames, $nick, true); return true; } } function AddServer($server) { global $servers; if(in_array($server, $servers, true)) { return false; } else { array_push($servers, $server, true); return true; } } function LookForIPs($ip) { global $conn; $sql = "SELECT * FROM `connections` WHERE `IP` = '".$ip."'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { AddAddress($row["IP"]); AddServer($row["serverIP"]); AddTime(Array($row["datestamp"], $row["datestring"], $row["serverIP"])); if(AddNickname($row["nickname"]) && $row["nickname"] != "Player" && $row["nickname"] != "A_Edition_V2") { LookForNicknames($row["nickname"]); } } return true; } else { return false; } } function LookForNicknames($nick) { global $conn; $sql = "SELECT * FROM `connections` WHERE `nickname` LIKE '".$nick."'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { AddNickname($row["nickname"]); AddServer($row["serverIP"]); AddTime(Array($row["datestamp"], $row["datestring"], $row["serverIP"])); if(AddAddress($row["IP"])) { LookForIPs($row["IP"]); } } return true; } else { return false; } } function SortTimes() { global $times; $good = false; while($good == false) { $good = true; for($i = 0; $i < count($times); $i++) { if($i+1 == count($times)) continue; if($times[$i][0] < $times[$i + 1][0]) { $tmp = $times[$i]; $times[$i] = $times[$i + 1]; $times[$i+1] = $tmp; $good = false; } } } } function GenerateLastSeenString($fromTime) { $time_now = GetTimestamp(); if($time_now < $fromTime) { return "N/A"; } if($fromTime == 0 || $fromTime =="") { return "N/A"; } $ss = $time_now - $fromTime; $seconds = $ss%60; $minutes = floor(($ss%3600)/60); $hours = floor(($ss%86400)/3600); $days = floor(($ss%2592000)/86400); $months = floor($ss/2592000); $str = ""; if($months != 0) { if($str != "") $str = $str . " "; if($days == 1) $str = $str . $months . " month"; else $str = $str . $months . " months"; } if($days != 0) { if($str != "") $str = $str . " "; if($days == 1) $str = $str . $days . " day"; else $str = $str . $days . " days"; } if($hours != 0) { if($str != "") $str = $str . " "; if($hours == 1) $str = $str . $hours . " hour"; else $str = $str . $hours . " hours"; } if($minutes != 0) { if($str != "") $str = $str . " "; if($minutes == 1) $str = $str . $minutes . " minute"; else $str = $str . $minutes . " minutes"; } if($seconds != 0) { if($str != "") $str = $str . " "; if($seconds == 1) $str = $str . $seconds . " second"; else $str = $str . $seconds . " seconds"; } return $str. " ago"; } function ClearResult($arr) { for($i = 0; $i < count($arr); $i++) { if(gettype($arr[$i]) == "boolean") { //echo "Found bool at $i"; array_splice($arr, $i, 1); } } return $arr; } function PrintArray($arr) { for($i = 0; $i < count($arr); $i++) { echo $arr[$i]; if($i + 1 != count($arr)) { echo ", "; } } } if($format == "mod") { LookForNicknames($find_name); LookForIPs($find_ip); $nicknames = ClearResult($nicknames); $addresses = ClearResult($addresses); $servers = ClearResult($servers); $conn->close(); /*if (!filter_var($find_ip, FILTER_VALIDATE_EMAIL) && $find_ip != "") { $find_ip = $addresses[0]; }*/ if($find_ip == "") { $find_ip = $addresses[0]; } if($find_ip == "") { $find_ip = "0.0.0.0"; } if(count($nicknames) == 0 && count($addresses) == 0) { ReturnError("NOT_FOUND"); } echo "!DATA!"; echo "Nicknames used: "; PrintArray($nicknames); echo "*-*"; echo "Total IPs used: "; echo count($addresses); echo "*-*"; echo "Location: "; echo file_get_contents("http://127.0.0.1/db/getlocation.php?ip=$find_ip"); echo "*-*"; echo "Connected: "; echo count($times); echo " times*-*"; SortTimes(); if(GetTimestamp() - $times[0][0] < 60 * 60) echo "Last seen: " . GenerateLastSeenString($times[1][0]) . "*-*"; else echo "Last seen: " . GenerateLastSeenString($times[0][0]) . "*-*"; echo "First seen: " . GenerateLastSeenString($times[count($times)-1][0]); echo "!DATA!"; } else if($format == "debug") { LookForNicknames($find_name); LookForIPs($find_ip); $nicknames = ClearResult($nicknames); $addresses = ClearResult($addresses); $servers = ClearResult($servers); $conn->close(); /*if (!filter_var($find_ip, FILTER_VALIDATE_EMAIL) && $find_ip != "") { $find_ip = $addresses[0]; }*/ if($find_ip == "") { $find_ip = $addresses[0]; } if($find_ip == "") { $find_ip = "0.0.0.0"; } if(count($nicknames) == 0 && count($addresses) == 0) { ReturnError("NOT_FOUND"); } echo "Nicknames used: "; PrintArray($nicknames); echo "<br>"; echo "IPs used: "; PrintArray($addresses); echo "<br>"; echo "Location: "; echo file_get_contents("http://127.0.0.1/db/getlocation.php?ip=$find_ip"); echo "<br>"; echo "Connected: "; echo count($times); echo " times<br>"; SortTimes(); echo "Last seen: " . GenerateLastSeenString($times[0][0]) . "<br>"; echo "First seen: " . GenerateLastSeenString($times[count($times)-1][0]) . "<br>"; echo $find_name; } ?> The problem is that for some nicknames it returns a proper output which should look like this:
But sometimes it just returns lots and lots of data even if the nickname I ask for is unique enough:
Here's how the database looks:
I don't know what's wrong with the script because I'm a PHP beginner. If someone could take a look at it and tell me what's the issue I'd appreciate. Edited September 22, 2020 by jevgienijSimilar TutorialsHi, When i am trying to run one script on my web server, i get following error Cannot connect to the database using the info you provided Access denied for user 'My_Username'@'localhost' (using password: NO) I filled all info like Host(localhost) Database name(created in cpanel) Username(created in cpanel) Password(i kept blank dont know where to find this) You help will highly appreciate Thanks, Ravindra Hello, I am building an online game(users make a character and move on a map and so on...)
All user data is stored in a mySQL database and I want the users to interact in real-time, but there can be a 1-3 second delay between the communication, but not exceed 3 seconds even if 500 players are playing at the same time.
But for the purpose of the question let's say the users can only chat between one another, if I'll have a solution for that then I can use the same method for more parts of the game.
I can't use websockets because my webhost doesn't support it( I don't want to use pusher.com).
I know I can make real-time apps with ajax long polling, but I think that with 500 players playing at the same time it's not the best solution.
So, finally:
How can I make user interaction as close as possible to a real-time game?
(Without too much load on the hosting server)
(I am sorry if some of my terms are not correct - I am just getting back to coding after a long time...)
Edited by Mythion, 17 August 2014 - 02:34 AM. I've been looking for a simple script that would connect to a game server to see if it is still online. I've found many, but not one of them work. They will permanently send back the text "Online", or "Offline". This is the simplest code I have found: <?php $ip = "66.79.190.40"; $port = "27960"; if (! $sock = @fsockopen($ip, $port, $num, $error, 5)) echo '<B><FONT COLOR=red>Offline</b></FONT>'; else{ echo '<B><FONT COLOR=lime>Online</b></FONT>'; fclose($sock); } ?> I'm also looking into getting it to pull the map name and player-list, but I should be able to figure that out on my own once I get this working. If it helps, this script is supposed to connect to the original Quake games(One, two, and three). This isn't exactly an application design question, but rather a system design one.
I am about to install an Inventory Control System inside this store I work in.
The store itself also owns a Linode VPS running Centos 6.4 which hosts our website.
This new Inventory System will come built in with a Microsoft SQL Server, and supposedly it is a SQL Anywhere database, but I'm not too sure what that means.
I need to make this database publicly accessible, but only via the Linode VPS. Surely, setting restrictions is easy enough to address that issue. That isn't my question.
My first idea is to put this server into the DMZ, easy. But it doesn't exactly sound safe. So my next idea was to put a middleman server in the DMZ, this way the Linode can send queries to that middleman server and it will send that data to the SQL Server and back. This is very vaguely described I know, but I don't want to get too much into details, but rather, understand how I can create that middleman server, and what could Install onto it that would allow me to securely process queries?
My first thought was to install a webservice, that accepts an XML/JSON request and returns an XML/JSON response.
Then, I realized directly afterwards that I don't have any experience setting up a webservice like that.
What kind of options are there out there? Ultimately, my question is, should I just put the Server in the DMZ or should I create the middleman, and if so, can someone point me in the right direction as to getting a webservice set up? Edited by Zane, 15 July 2014 - 11:28 PM. Hi All, Long question but I hope someone will be able to point me in the right direction. At the moment I am writing a cricket management game and and each hour each team is updated with the code Code: [Select] <?php #Players MUST be updated from this screen so they cna get team bonuses $teamUpdateTime=$team['teamUpdateTime']; #This is the time that the team is updated $teamMorale=$team['morale']; #Get the teams morale while($teamUpdateTime<$updateTime) { #Keep looping through this until we are up to date echo "<BR>".$team['name']; #Work out changes to team morale if($teamMorale>1000) $teamMorale -= mt_rand(0, 3); #If team morale is high then lower it if($teamMorale<1000) $teamMorale += mt_rand(0, 5); #If team morale is low then increase it $moraleBonus=0; #Reset the variable $confidenceBonus=0; #Reset the variable $injuryBonus=0; #Reset the variable $energyBonus=0; #Reset the variable $teamUpdateTime += 3600; #Add an hour to the time include("hourly_update_player.php"); #Do players now } #Save the team $sqlTeam = "UPDATE teams SET morale='$teamMorale', teamUpdateTime='$teamUpdateTime' WHERE teamID='{$team['teamID']}'"; if(!mysql_query($sqlTeam, $sqldb)) die('Error: ' . mysql_error()); //Update the record, if there is an error then show it ?> the line include("hourly_update_player.php"); #Do players now then activates the following code Code: [Select] <?php #Playeres will have to be updated with the team because we have to check for team medic $players = mysql_query("SELECT playerID, name, injuryTime, energy, morale, confidence, fitness FROM players WHERE teamPlayedFor='$team[teamID]'"); #Get all the players of the team while($player = mysql_fetch_array($players)) { #Go through all the players of the team echo "<BR>".$player['name']; # Do all the updating of player stats here. I won't put the full code here as it is not needed for the question on phpfreaks. $sqlPlayer = "UPDATE players SET energy='$energy', confidence='$confidence', morale='$morale', injuryTime='$injuryTime' WHERE playerID='{$player[playerID]}'"; #Update player if(!mysql_query($sqlPlayer,$sqldb)) die('Error: ' . mysql_error()); //Update the record, if there is an error then show it } ?> Each team has around 25 players to update. With ten teams (250 players all up) in the game (the game is still pre-alpha) to test it all this takes 8 seconds to go through all the teams and their players. Unfortunately in this 8 seconds nobody else can use the database as it locks it up. I tried to have the players update by itself (so it only has to go through the players database once) but cannot work out how to have team affects on the player - for example if the team has a specialist batting coach then the player gets an extra batting point each hour so it needs to go through the teams first. MY QUESTIONS A) How can I speed this up? When the game goes into the public domain I would like to see around 1-5 thousand teams, this could take up to 800-4,000 seconds - waaaay to long. B) When it is updating the database I can't play the game, it simply says loading until the updates are finished and then continues as normal; with thousands of teams I do expect a bit of delay but how can I keep parts of the database open that aren't being used? C) Each time I go through a team the players database is reloaded, can JOINS fix this? Or is there another way of doing this? I currently making a relatively simple turn-based strategy game (kind of like a rock, paper, scissors game) in flash and I have no idea as to what I should use as a socket (or like a socket) to relay players' interactions from one client to another. I have researched various APIs like nonoba and SmartFoxServer, etc but they either force their own interface on you or charge an arm and a leg. I've read that java would achieve what I want, but I just don't know enough about java, sockets or networking to make sense of any of it, let alone trying to utilize it. So I am thinking about using php and a mysql database since I am familiar with them, but I'm concerned about performance even though the game would not be very demanding as it is basically just passing values from client to client via php/mysql. Little info on the game: 3-6 players per room. I have no idea as to how many rooms would be necessary, of course that will be determined by its popularity. The timing is what will concern me, as it must be accurate -1 min intervals or less if all of the players make their selections sooner, but they must all be in sync. I only see about 6-10, small (<20 characters/per) variables needing to be passed per player - so if it were 10 variables, in a room with six players, player 1 would send 10 variables and receive 50 back Another option, that I admittedly haven't researched yet, is an xml socket, but I have no idea how to accomplish this and am concern with performance with that as well - probably just because I'm ignorant about it. So what do you guys think? Think php/mysql could handle this? Or do I need to learn another language/API? Any input would be greatly appreciated. well.. i have vbulletin 4 forum i try to put video player so if i upload mp4 file so i can play video but sad part is its working only at firefox browser can you help me out .. video code looks like this
<vb:if condition="$attachment[attachmentextension] == mp4"> pls i really want that put to work in every browser sadly it works only in firefox somehow.. the second database found on the cloud
i try to get JSON data but how to insert and update them to another online database with the same table my php script to return json data <?php include_once('db.php'); $users = array(); $users_data = $db -> prepare('SELECT id, username FROM users'); $users_data -> execute(); while($fetched = $users_data->fetch()) { $users[$fetchedt['id']] = array ( 'id' => $fetched['id'], 'username' => $fetched['name'] ); } echo json_encode($leaders);
i get
{"1":{"id":1,"username":"jeremia"},"2":{"id":2,"username":"Ernest"}} Edited March 24 by mahenda At the moment I am creating a search function for my website. The approach I have in mind is a pseudo-PHP database. To give an example: A HTML form will submit the results to a PHP file. HTML FORM - Colour: Black PHP RESULT PAGE - if ($_POST['color'] == 'Black') {readfile("./products/black/*.html");} HTML FORM - Price: <$50 PHP RESULT PAGE - if ($_POST['Price'] == '<$50') {readfile("./products/less50/*.html");} The problem here is if there is an item that is black and costs less than $50, then its going to be listed twice. There is probably some code I can write to ommit the listing of duplicate entries, but it is probably going to be messy, so I am wondering if its better to use a centralized MySQL database, rather than a pseudo-PHP database? I've never used MySQL and don't know much about it and this is my first real attempt at using PHP. For reasons unknown to me I installed this version of MSSQL 2008 R2 yesterday and it came with an attached database for which I was able to add my own database to. I had to uninstall and reinstall this version because I was having some permissions conflicts....now when I reinstalled the 2008 R2, there is no database attached. There is no preinstalled db engine. I do not know how to create this or drop my db into the object explorer because there is no db attached. I hope this makes sense.
What I am trying to do is set up a test server on my home computer. I saved the actual db from a work computer onto a thumbdrive. Now, I want to attach it to my home server. That option is not there to connect now. Thank you for any help.
I am trying to add a second image upload to a form I have, but I can't figure out how to get the insert statement and upload statement working properly. The first file uploads and inserts to the database properly, but can anyone tell me how to add a second image to the mix? Here is what I currently have: Code: [Select] //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { //echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //echo "Type: " . $_FILES["file"]["type"] . "<br />"; //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } I thought I could simply add a second move_uploaded_file line and replace "file" with "file2" (the name of my second file upload field from the form), but it's not working. Can anyone tell me the right way to do this, please? Thanks in advance! I'm not experienced with file uploads yet :-( Okay guys I have finished my db and I want to upload it to a live server but don't know exactly what to change in the code to get the ODBC_connect to open the path at the new server location please help. my database is located in a subfolder called Databases i.e. "www.mydomain.com/Databases/myEvents.mdb" what do i change in the connection string below to get it to open the file on the live server? Thanks in advance. $conn = odbc_connect('myEvents','',''); This topic has been moved to Installation in Windows. http://www.phpfreaks.com/forums/index.php?topic=312024.0 I have a script that is trying to connect from one server to another and it doesn't seem to let it. Could someone help me please Code: [Select] Can't connect to MySQL server on 'example.com' (4) Always humbling to be knocked on your arse by what you think would be so easy... How can I run a std mysql_query command like this from cron? $query_insert_new = mysql_query("INSERT INTO members (ID, name, date)VALUES (NULL,'$new_name',CURDATE())"); It is a long time since I firstt learnt how to access mysql from the command line via pUTTY or cmd... However I never learnt how to write a php script in the same fashion... I have configured cron to run correctly and the script runs. After testing however I was wondering how my database was not getting updated... then i realised I must have to enter the commands as if command line... I tried but don't know where to start. Do I have to connect to the database in the same fashion you do in cli: mysql -u username -p password ? This is my script. The idea is to cycle every 7 days and write over old files. It is very simple, but all i need. The table has 3 fields, ID name date. <?php $db_username = "username"; $db_password = "password"; $db_hostname = 'localhost'; $db_database = 'databasename'; //first log into the database $db_server = mysql_connect($db_hostname, $db_username, $db_password); //selecting databse mysql_select_db($db_database, $db_server); //now get the latest entry in the table 'database_backup_info' $query_latest_entry = mysql_query("SELECT name FROM database_backup_info ORDER BY ID DESC LIMIT 1 "); //if there are results in the table if(mysql_num_rows($query_latest_entry)>0) { //retrieving the info $query_latest_entry_row = mysql_fetch_assoc($query_latest_entry); //now determine the new file number based on the last entry if($query_latest_entry_row['name'] + 1 > 7) { $new_name = $query_latest_entry_row['name'] + 1; } else { $new_name = 1; } //insert the entry into the db $query_insert_new = mysql_query("INSERT INTO members (ID, name, date) VALUES (NULL,'$new_name',CURDATE())"); } //if no results then this will be the first entry else{ $new_name = 1; //insert the entry into the db $query_insert_new = mysql_query("INSERT INTO members (ID, name, date) VALUES (NULL,'$new_name',CURDATE())"); } //creating the file path and name $db_backupFile= dirname(__FILE__).'/sql_files/'.$new_name.'.sql'; //the mysql dump command $command = "mysqldump -u$db_username -p$db_password -h$db_hostname $db_database > $db_backupFile"; //running the mysql_dump command system($command, $result); ?> This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=310661.0 Hello, So I have a weird error where if I fetch more than a certain number of rows from a mysql table, it triggers a 500 Internal Server Error. I am using Apache Web Server (through GoDaddy) and the offending code is below: Code: [Select] set_time_limit(0); $this->Connect(); $Output = array(); $search = "SELECT * FROM <table> WHERE user_id = ?"; if($Statement = $this->MySQLi->prepare($search)){ $Statement->bind_param("i", $UserId); $Statement->execute(); $Statement->bind_result(<result variables>); $count = 0; while($Statement->fetch() && $count++ < 70){ ChromePhp::log(<result variables>); } $Statement->close(); } $this->Disconnect(); ChromePhp::log is a way of dumping things to the Javascript Console in your browser from within a PHP script just as a heads-up. So when I set the stop number as 70, everything is fine. If I try to fetch more than that it triggers a 500 internal server error on Apache Server port 443. I have looked through the error logs and can't figure out the cause but this is almost certainly a server configuration issue? I'd appreciate any feedback, especially anyone familiar with GoDaddy's hosting services Thanks This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=352526.0 hello I wanna replicate one table in a database test(in localhost-master) to another database table(slave) on remote server(on the internet) in godaddy.com. I was really tried my best to make it work. but it doesn't seems to be working. I red the MySQL documentation as well.
database name- test
master table - attendance -on the localhost(127.0.0.1)
slave table - attendance - on the internet(godaddy 184.x.x.x)
I want to copy data from my attendance table on the localhost to slave table on the internet. Please help me to configure these settings. Thank you
|