PHP & Unity - Moving Info back and forth - php

I posted not long ago and decided to make another thread.
In our application we ask the players to create a new account, when they do we add this information to our DB.
The next step is to now grab the account they created, so that we can add more data to it. So the player creates an account with us, after this is done we then login with Google Play Services, and we now need to add info from google to the account they created, locale, id, etc
My problem here being new to php is im not sure on the correct way to do this so im asking for some guidance on it and have a couple of questions that may or may not make any sense.
When a user creates an account i now need to reference and keep a hold of this account they created so that we can easily access and edit/add info to it. How would you accomplish this?
When i need information from the database to display in the application how would i grab this info specific to the player and read it directly into unity? I think i could use the JsonEncode but im not sure if this is the most efficient way to do this.
There is more but i don't want to ask to much all at once haha.
Thanks for any and all help.
John
<?php
/// Check to make sure there is data in these fields
/// Only accept user when they have confirmed thier email
error_reporting('E_All');
include 'db_header.php';
$error = '';
$firstName = $_GET['firstName'];
$lastName = $_GET['lastName'];
$email = $_GET['email'];
$password = $_GET['password'];
$sql = "INSERT INTO Player (FirstName, LastName, Email, Password)
VALUES ('$firstName', '$lastName', '$email', '$password')";
// Here i need to make sure this is correct
if ($conn->query($sql) === TRUE)
{
$id = $conn->insert_id;
echo "Welcome " . $firstName . " You are now an Rcader! ";
}
else
{
//echo "Error: " . $sql . "<br>" . $conn->error;
$error = $conn->error;
echo $error;
}

First of all you should need to learn about the basic PHP and Unity3d integration through this simple unity3d Tut at unity wiki which is Server Side High Score.
Now come to your questions:
You should first authenticate user by asking user name and p/w in unity3d if his login is valid save its id/primary key into player prefs. Later use this player prefs value to store user specific information into database. You can also use this player prefs value to retrieve data from database. And never forget to remove player prefs values before exiting the game.

Related

How can I use OpenID for Steam to print user's fields on a different database?

I have the following PHP code:
<php>
$servername = "host";
$username = "username";
$password = "password";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT steamid, bananas FROM es_player";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "PLAYER'S STEAM ID: " . $row["steamid"]. " - PLAYER'S BANANAS: "
.$row["bananas"]. " <br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
It just fetches specific fields from my database. When user's login, they use OpenID, and it is not through an actual database under my control. It is through Steam, users login with their Steam account through OpenID. I am able to fetch the user's SteamID with this when they log in, and there is even a variable for it.
I need to use this SteamID variable when they are logged in to specify which row they are on the database, and print ONLY the logged in user's profile fields, rather than just printing all rows in the database. This will be done using the SteamID of the user that logs in which will be compared against the SteamID field on my database, so that it will know which user you are when you log in.
I do not know how to accomplish this, which is why I am posting here. I just need the PHP code, or some help writing it.
You have several related problems that need more research. Since I've voted to close the question as too broad, I will mark this answer as Community Wiki. I really want to help, but in common with the values of the community here, I would encourage you to take the following points and to use them as avenues for further search-engine research. Your post for "just [needing] the PHP code" is a request for free work, which we try to discourage here.
I think I understand the problem, but I have no experience of the Steam API, so you may need to read their docs and adapt the following. If you have not used APIs or sessions before, hiring a freelancer in your locality may be the quickest and easiest route to getting your project on the road. You may only need a few hours of their time, so it need not be expensive.
Your OpenID script should deliver to your application one of the profile IDs you've described. When a user first creates an account in your site, you need to capture that profile ID and store it against other information of interest. At this point you should run the conversion routine, so that you have the other profile ID, and you can then store that too.
When the user logs on, you need to create a session. This is usually as simple as using session_start() and then saving the user record primary key as a variable, thus:
$_SESSION['user_id'] = $userId;
The user ID will come from your login screen, where you get an OpenID callback to prove that the current user does indeed own the Steam profile ID they have supplied to you. Having a session set up means that any subsequent page browsed by the user will have their user ID available, until they log off. This means that you don't need to do an OpenID call on every page.
Using this session ID, you can now obtain either of profile IDs you require, since they are both in your database. This is a trivial SELECT database operation involving the session ID, which you can read from $_SESSION['user_id].
Here is an example of a table in an OAuth application I wrote (it's open source, so you can pull it apart if you like). When the user logs on, this record is either created (if it does not exist) or updated (if it does exist):
mysql> SELECT * FROM user_auth;
+----+---------+---------------------------+----------+---------------------+
| id | user_id | username | provider | last_login_at |
+----+---------+---------------------------+----------+---------------------+
| 1 | 1 | https://github.com/halfer | github | 2015-01-13 18:05:49 |
+----+---------+---------------------------+----------+---------------------+
1 row in set (0.00 sec)
The username is the OpenID identifier, the provider is useful if you allow the user to choose from several authorisation systems (Steam being another), and of course the last_login_at is self-explanatory.
I also advised in the comments that you may have to write this code. Library re-use is a commendable habit to get into, but unfortunately there is not a library for every eventuality - sometimes the programmer just has to write something him or herself. We frequently see requests on Stack Overflow for a "library/tutorial/step-by-step guide for [project X]" here, and if readers can persuade posters that programming isn't really like that, they will have passed on a very useful lesson.
So, try the above in order? Feel free to ask for further help if I have misunderstood some basic part of the structure, but otherwise, please do use the keywords I've mentioned and pop them in a search engine. It's the only way to learn. Good luck!
It was actually quite simple. First, I took the SteamID 64 variable $steamid and ran it through this conversion, which will output the SteamID 32
$id = $steamid;
function parseInt($string) {
if(preg_match('/(\d+)/', $string, $array)) {
return $array[1];
} else {
return 0;
}}
$steamY = parseInt($id);
$steamY = $steamY - 76561197960265728;
$steamX = 0;
if ($steamY%2 == 1){
$steamX = 1;
} else {
$steamX = 0;
}
$steamY = (($steamY - $steamX) / 2);
And then to finish it off, I just made a variable that combined it into the full STEAM_0:000000000 combination.
$steamID = "STEAM_0:" . (string)$steamX . ":" . (string)$steamY;
I can now use $steamID as a variable on any page that I include this code on. I answered this myself so that if anybody else has troubles with this like I originally did, the answer will be here for them :)

A secure enough way of identifying and activating a user in MySQL PHP with a URL

Is checking against my table with the user's email and dedicated hash enough to verify and activate an account if a match is found against those two values?
A user is asked to register themselves with user data and their email id. They are then sent a URL to their email which they are asked to click on to confirm and activate their account.
This is my current setup:
<?php //The user-account-creation processing page
$email_id = taken from user input;
$randomnessWhateverItsCalled = "lots-of-randomness-here";
UPDATE advert SET advert_hash = SHA1(CONCAT($email_id, $randomnessWhateverItsCalled))
//For simplicity's sake I omitted the PDO stuff
INSERT INTO table_name (..., user_email, hash, account_activated, ...) VALUES (..., usersEmail, advert_hash, NO, ...)
/**
Send an email with some php code with the URL that would look like this
URL to click on attached to email body:
*/
$attachStringToEmailBody = "http://www.domainname.com/activate-user?email_id=" . $usersEmail . "&hash=" . $randomnessWhateverItsCalled;
enter code here
//Send email from this process page with a little email php code
//Redirect user to a page informing the user to activate the account by visiting their email and clicking on the url
?>
Then in the activate-user.php page I have the following:
<?ph
$user_email = $_GET['email_id'];
$hash = $_GET['hash'];
/**
search database and return a row if there is a match containing both the $user_email and the $hash
if(match){
Update database and set the `account_activated` column to `YES`
}
else{
//Tell if there was no match then activation failed
//Let the user know that we do not recognise the link they used to try and activate their account.
}
*/
?>
It seems secure enough, as long as you made the "randomness" part hard to guess. You can put there the email, username, password, etc. and mix them up with another key - all encrypted - that's what I usually do.
But I would advise you to use 0/1 for active/inactive - why using strings, when you can do the same with smallint (1) - and save some space, thus making the database a bit lighter ?

Facebook regsitration plugin - async validation (email)

We have an existing membership site setup in php/MySQL, and are looking to integrate Facebook registration and login. The login and registration forms have been imported, and are hooked up to php/MySQL code which creates new users in the database. However, in order that we can prevent a single user having multiple logons (eg. one site logon, one Facebook logon), we need to check the email address of the user before adding a new line to the members database table.
We can do this through php/MySQL code, but that gets needlessly complex when you have to cater for all the permutation of cross-site/FB membership, plus we do not want the user to connect to the FB registration app without becoming a site member. A better solution would be to prevent the user from registering under an email address which is already present in the database (rather directing them to obtain a new password, and update connect their facebook profile to the existing profile). We have been looking for weeks for a solution, and have consulted the Facebook Developers Async Validation (http://developers.facebook.com/docs/plugins/registration/advanced/), as well as the stackexchange forum, but have not been able to implement a solution which validates the email address against the database, and prevents/allows registration accordingly.
The code we have so far is
<fb:registration redirect-uri="http://www.mysite.com/register.php"
fields='[{"name":"name"},{"name":"email"}
{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"></fb:registration>
<script src="https://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
function validate_async(form, cb) {
$.getJSON('http://www.mysite.com/register_check.php/' + form.email + '?callback=?',
function(response) {
if (response.error) {
// Username isn't taken, let the form submit
cb();
}
cb({username: 'That email is taken'});
});
}
</script>
register_check.php
//connect to the database
include 'mysql_connect.php'
$email = $_GET('email');
$data = array();
$sqlCommand = "SELECT * FROM members WHERE email='$email'";
$query = mysql_query($sqlCommand) or die (mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows>0){
$email_check = $row['email'];
$data['email'] = $email_check;
} else {
$data['error'] = "true";
}
echo json_encode($data);
Unfortunately, this process is not working at all. The registration form simply hangs endlessly, without validating nor passing the information to the database. We have done considerable research into how to properly code getJSON and the server-side php, but have come up against brick wall, so would very much appreciate any help or advice on this issue.
I hope this isn't too late, but after facing the same problem I found out the registration plugin doesn't send with the form object the preset details (name, email, gender, birthdate) -- only sends any custom fields. Quite dumb imo but could have an advantage or two.
Solution was to override the description of the email so as to trick it into thinking it's custom (which it would be) -- disadvantage being your regular checks will not be checked against (valid email et al) so you'll need to take care of those manually.
This may be late, but:
Change your JSON address to
http://www.mysite.com/register_check.php?email=' + form.email +
You were using facebook's check for existing user. Change:
cb({username: 'That email is taken'});
to:
cb({email: 'That email is taken'});
You want error message to appear next to email field.

Handling Sessions

Need some help with how to handle sessions. I am using ajax techniques to implement a group discussion platform and alot of its success depends on whether or not i can handle sessions properly, be able to see who is online etc. How can i do this efficiently. Remember, this is a typical single url ajax application where the server only responds to request. All of the form validation is done on the client side as the user enters his data. I need help with this. Below what have written so far.
<?php
include_once "../database/dbconnect.php";
session_start();
$username = isset($_POST["userNameLogin"]) ? $_POST["userNameLogin"] : $_SESSION["userNameLogin"];
$pwd = isset($_POST["passwordLogin"]) ? $_POST["passwordLogin"] : $_SESSION["passwordLogin"];
// Sending these messages to my client side validation code json-style.
if(!isset($username)){
echo("{message : 'NoName'}");
}
elseif(!isset($pwd)){
echo("{message : 'NoPW'}");
}
// creating the session variables to hold username and pwd
$_SESSION['userNameLogin'] = $username;
$_SESSION['passwordLogin'] = $pwd;
// calling the function incuded above to make connection to mysql db
dbConnection();
//query retrieves username and pwd from db and counts the result. if it is one, then they //certianly exist and if not unset the variables created above. The varibles were created
//above so i do not have to check if they exist before unsetting them.
$sQuery = "SELECT * FROM users WHERE
username = '$username' AND password = '$pwd'";
$result = mysql_query($sQuery) or die(mysql_error());
$intFound = mysql_num_rows($result);
if ($intFound == 0) {
unset($_SESSION['userNameLogin']);
unset($_SESSION['passwordLogin']);
// AD - Access Denied
echo("{message : 'AD'}");
}
else{
//a flag to set in the database who is currently online. value of 1 for users who are //online and zero for users who are not. If i want a list of those online, i check the //column called online and then check to see if the $_SESSION['username'] exist. If it //does then i know the user is online. That is what the second script is for. New to this //stuff, and do not know a better way of doing it
mysql_query("UPDATE users SET online = '1' WHERE username = '$username'") or die(mysql_error);
}
The above script should let the user login or deny access by sending messages to the validation code on client side.
As you can see, i am new to this stuff i having my share of problems. What can i do to make sure that sessions are set and unset properly i.e when user logs out.
secondly how can i monitor who is online and who is not using sessions. This is how i am trying to check who is currently online and then building a json file with the user names and sending it to the client. Json is easier to parse.
The script below tries to determine who is online
<?php
// this script determines which sessions are currently active by
// 1.) checking to see which online fields in the users table are set to 1
// 2.) by determining if a session variable has been set for these users.
// If it is not set, it means user is no longer active and script sets its online field in the users table to zero.
// After doing this, the script, then queries the users table for online fields with values one, writes them to an
// array and passes them to the client.
include_once "../database/dbconnect.php";
//include "../validation/accessControl.php";
$tempActiveUsers = array();
$activeUsers = array();
$nonActiveUsers = array();
dbConnection();
$sql = "SELECT username from users WHERE online = '1' ";
$active_result = mysql_query($sql) or die(mysql_error);
if($active_result){
while($aValues = mysql_fetch_array($active_result)){
array_push($tempActiveUsers, $aValues['username']);
}
}
forEach($tempActiveUsers as $value){
/*if($_SESSION['$value'] == $value){
$activeUsers += $value;
} */
if(isset($_SESSION['userNameLogin']) == $value){
array_push($activeUsers, $value);
}else{
array_push($nonActiveUsers, $value);
}
}
forEach($nonActiveUsers as $value1){
$sql1 = "UPDATE users SET online='0' WHERE username = '$value1'";
$set_result = mysql_query($sql1) or die(mysql_error);
}
$length = sizeof($activeUsers);
$len = 1;
$json ='{"users" : {';
$json .= '"user":[';
forEach($activeUsers as $value2){
$json .= '{';
$json .= '"username" : "' .$value2.'" }';
if($len != $length){
$json .= ',';
}
$len++;
}
$json .= ']';
$json .= '}}';
echo $json;
Please look through and give some advice. Will appreciate that very much. My project framework is up and good, but i can implement much user functionality yet because i cann't track who is online and how to manage thier sessions. If you need more background info let me know. Thanks in advance
Add 'Log out' button and click event handler on it which makes an ajax request to server to stop session by unsetting session vars or destroying session completely, and on ajax completion callback put a function to update user interface to show user is logged out.
Log in procedure can be done as follows: user clicks 'Log in' button and some form asking for user name and password appears. Then submit this form with ajax to a server script like your first one. Server script checks whether user name and password are valid and returns authentication information to a client via callback: failure notice upon failed login or some information about user currently logged in, e.g. user name, fullname and anything you might need about this user on client side in js. Then your client script proceeds according to login status returned from server-side script.
You should always remember about security.
Before sending any sensitive data to a client side with json, you shoud always check if session is valid and started. Client-side scripts could be easily modified and executed without your control and you should prevent undesired activity only on server side.
You should apply some escaping on user-POSTed fields before using them in sql queries to avoid sql injection attacks, e.g. by using mysql_escape_string().
And instead of building json strings, you can use json_encode() which works good for primitives, objects and arrays, you'll save some time.

PHP Links to User Profiles After Membership

I already have written a login and register script. The user can login to their account edit their details etc. The details are stored in a users table which has many different data properties related to the user.
I was wondering, how do I make it so they can view their profile and it shows all the data they input. For example, if somebody with username "bob" registered and changed his data, he can click a link "view profile" and he can see his public user profile. I know how to fetch entries and display the data but my problem is I don't understand how to make a profile for my users that can be seen by others and/or themselves. I want these pages to be dynamically created for each user.
Also, if I had a page that retrieved all the recently registered members, it could link to their profile pages.
It is a very common thing across websites and I know there are CMS's that already do this like drupal but I want to code a small controlled solution by myself. Thanks!
Make your page 'profile.php'
1) Pass id to that page using Get String. Link would be : ....../profile.php?id=3
To learn more about Get and Post Method of form submission. And how PHP handles it ($_POST & $_GET) google it.
2) In that page 'profile.php'
$id=isset($_GET['id'])?$_GET['id']:-1;
settype($id , "int");
if($id<1)
{
//wrong id, may be redirect
header('Location : another-page.php');
die();
}
// use this $id to get information from db and display the information
3) If you want to dynamically tell the person that what his profile link is:
Supposing you have $id of that person :
$link = '...../profile.php?id=' . $id;
Please consider learning basic php first. Like cookies, get, post, functions, db handling, sessions, string handling, array handling, global variables.
Well, just create a page say userprofile.php that gets a parameter called id (I assume your users have id's .. otherwise have username). If the page is called with no parameter, the page will use the current session user as the profile id and will make all fields editable, otherwise, if it's passed with say "userprofile.php?id=123", then it will display a non-editable version for other members. You can also do a check to see if the session user is the same as the one whose profile is requested, in which case, you want to make the page editable as well.
Are you looking for something like this (an amalgamation of what has been posted and some extra stuff):
$SQL = "SELECT ID, First_Name, Last_Name, User_Name FROM Users" .
"WHERE ID = " . $_GET['id'];
$con = mysql_connect('server', 'user', 'password');
$db = mysql_select_db('database_name', $con);
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print "User ID: " . $db_field['ID'] . "<BR>";
print "User Name: " . $db_field['User_Name'] . "<BR>";
print "First Name: " . $db_field['First_Name'] . "<BR>";
print "Last Name: " . $db_field['Last_Name'] . "<BR>";
}
When you want to create a link to their user page, something like this:
print "" . $db_field['User_name'] . "";
This takes the ID you pass through from a link on a page, such as http://servername/page/list.php?ID=123 and then the above code retreives whatever information you want (via the SELECT statement) in the database. Then you just lay the information out however you want.

Categories