MySQL script retrieves Steam ID and nothing else - php

I have a problem with the Steam Authentication for the web. As you know, Steam provides a script to allow people to connect on your site through the Steam database. My problem is my code only inserts the Steam ID in the database and not the name & avatar.
My code:
if (isset($_GET['login'])){
require 'db.php';
require 'openid.php';
require 'userInfo.php';
try {
require 'SteamConfig.php';
$openid = new LightOpenID($steamauth['domainname']);
if(!$openid->mode) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
} elseif ($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$_SESSION['steamid'] = $matches[1];
$sql_fetch_id = "SELECT * FROM member WHERE steamid = '".$_SESSION['steamid']."'";
$query_id = mysqli_query($db, $sql_fetch_id);
if (mysqli_num_rows($query_id) == 0) {
$sql_steam = "INSERT INTO member (name, steamid, avatar) VALUES ('".$_SESSION['personaname']."', '".$_SESSION['steamid']."', '".$_SESSION['avatar']."')";
mysqli_query($db, $sql_steam);
}
if (!headers_sent()) {
header('Location: '.$steamauth['loginpage']);
exit;
} else {
?>
<script type="text/javascript">
window.location.href="<?=$steamauth['loginpage']?>";
</script>
<noscript>
<meta http- equiv="refresh" content="0;url=<?=$steamauth['loginpage']?>" />
</noscript>
<?php
exit;
}
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
}
Screenshot

Looking at the output of var_dump($_SESSION) (which should be in the question) it seems as if you're not actually referencing the keys of the session correctly.
With this line of code:
$sql_steam = "INSERT INTO member (name, steamid, avatar) VALUES ('".$_SESSION['personaname']."', '".$_SESSION['steamid']."', '".$_SESSION['avatar']."')";
You're referencing $_SESSION['personaname'], however, only ['steam_personaname'] is provided in the session. So you're referencing something that isn't there.
So you should be using:
$sql_steam = "INSERT INTO member (name, steamid, avatar) VALUES ('".$_SESSION['steam_personaname']."', '".$_SESSION['steamid']."', '".$_SESSION['steam_avatarfull']."')";

Related

Add/attach a UserID based on Session PHP

Looking to add a UserID based on session variable to this post method.
I can display the diary posts based on the Session ID but want to actually add the User's ID into the corresponding table everytime an entry is posted.
I've included pictures of the database below and the Insert Query that already adds posts.
The diary and tblUseraccount are already linked using foreign keys
PHP functions
<?php
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['myEmail'])){ //if login in session is not set
header("Location: login.php");
}
if (!isset($_SESSION['myEmail'])) {
echo" <a href='login.php'";
}
else {
$myFName = $_SESSION['userFirstName'];
}
The code I want to insert the UserID too
<?php
// post_add.php
if(!empty($_POST)) {
include 'mysql.php';
if(mysql_safe_query('INSERT INTO posts (title,body,date,) VALUES (%s,%s,%s)', $_POST['title'], $_POST['body'], time()))
echo 'Entry posted. View';
else
echo mysql_error();
}
?>
The mysql.php portion
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri)
{
if (!headers_sent())
{
header('Location: '.$uri);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$uri.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$uri.'" />';
echo '</noscript>'; exit;
}
}
#mysql_connect('localhost','######','#######');
#mysql_select_db('######');
enter image description here
enter image description here
Firstly you need to set UserId in session
when you make the user login you can add the user id in session like you have added userFirstName
After that you can just start sessions in your file and then get the userId from session when you want to insert a post
session_start();
if(!empty($_POST)) {
include 'mysql.php';
$userId = $_SESSION['UserID']; //or whatever is your key in session where you store the user id
if(mysql_safe_query('INSERT INTO posts (title,body,date,UserID) VALUES (%s, %s, %s, %s)', $_POST['title'], $_POST['body'], time(), $userId)){
echo 'Entry posted. View';
}else{
echo mysql_error();
}
}
Also I noticed that your are using mysql_query to run your queries. You should use mysqli_query or PDO because mysql_query is deprecated in PHP 5.5 and it is removed in PHP 7.
You can read more in php page here

Steam Authentication Session

As you know, steam provides a script to allow people to connect on your site through the steam database.
I would like if I refresh the page I don't have to login again. But with steamapi I don't have any idea how to do it.
My Code:
<?php
require 'includes/lightopenid/openid.php';
include_once("db.php");
$_STEAMAPI = "MYAPI";
try {
$openid = new LightOpenID('http://test/dev1/index.php?id=1');
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'http://steamcommunity.com/openid/?l=english';
header('Location: ' . $openid->authUrl());
} else {
echo "<form action='?login' method='post'>";
echo "<input type='image' src='http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_small.png'>";
echo "</form>";
}
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
$sql_fetch_id = "SELECT * FROM member WHERE steamid = '$player->steamid'";
$query_id = mysqli_query($db, $sql_fetch_id);
if (mysqli_num_rows($query_id) == 0) {
$sql_steam = "INSERT INTO member (name, steamid, avatar) VALUES ('$player->personaname', '$player->steamid', '$player->avatar')";
mysqli_query($db, $sql_steam);
}
echo "Welcome back <b>" . $player->personaname . "</br>";
}
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
?>
The general approach would be to setup session - in PHP, you can use $_SESSION to store this information. This allows you to store persistent server-side data per user.
Once you retrieve user's SteamID64, save it in the $_SESSION, e.g.:
$_SESSION['steamid'] = $someVal;
You can check if it's set on every subsequent request and act accordingly.
You can see full example here: https://github.com/SmItH197/SteamAuthentication
(Disclaimer: I'm not the author of the lib.)

Problems returning to the index using steamapi login

So i am currently studying PHP and Java and i encountered an error while working on my code. I am working on a login button where the user is able to connect to my page using the SteamAPI login.
I am testing 2 codes to make this work. The first code is the following:
<?php
require('openid.php');
$db = mysqli_connect("localhost", "root", "(my pw of the database)", "(name of my database)");
$_STEAMAPI = "(My steam api key)";
try {
$openid = new LightOpenID("http://mypage.com?id=1");
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'http://steamcommunity.com/openid/?l=english';
header("Location: " . $openid->authUrl());
} else {
echo "<h2>Connect to Steam</h2>";
echo "<form action='?login' method='post'>";
echo "<input type='image' src='http://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_large_border.png'>";
echo "</form>";
}
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
$sql_fetch_id = "SELECT * FROM users_steam WHERE steamid = $player->steamid";
$query_id = mysqli_query($db, $sql_fetch_id);
$_SESSION['name'] = $player->personaname;
$_SESSION['steamid'] = $player->steamid;
$_SESSION['avatar'] = $player->avatar;
if (mysqli_num_rows($query_id) == 0) {
$sql_steam = "INSERT INTO users_steam (name, steamid, avatar) VALUES ('$player->personaname', '$player->steamid', '$player->avatar')";
mysqli_query($db, $sql_steam);
}
}
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
?>
`
The other code i am working with is:
<?php
require 'openid.php';
$_STEAMAPI = "(My steam api key)";
try
{
$openid = new LightOpenID('http://mypage.com/');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'http://steamcommunity.com/openid/?l=english'; // This is forcing english because it has a weird habit of selecting a random language otherwise
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<input type="image" src="http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_small.png">
</form>
<?php
}
elseif($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
if($openid->validate())
{
$id = $openid->identity;
// identity is something like: http://steamcommunity.com/openid/id/76561197960435530
// we only care about the unique account ID at the end of the URL.
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
echo "User is logged in (steamID: $matches[1])\n";
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
echo "
<br/>Player ID: $player->steamid
<br/>Player Name: $player->personaname
<br/>Profile URL: $player->profileurl
<br/>SmallAvatar: <img src='$player->avatar'/>
<br/>MediumAvatar: <img src='$player->avatarmedium'/>
<br/>LargeAvatar: <img src='$player->avatarfull'/>
";
}
}
else
{
echo "User is not logged in.\n";
}
}
}
catch(ErrorException $e)
{
echo $e->getMessage();
}
?>
So my problem is that i am trying to redirect to my index.html but it doesn't work. On the first code i get redirected to my index.html because i added a ?id=1 after the URL of my website. If i remove that it will leave me on a blank page. So, it does the work when adding the ?id=1, but it sends me to my website offline. In other words, it send me to my index.html but the login button is still there, showing as if i didn't log in at all (offline index).
On the second code (i haven't used it a lot), it will redirect me to a website showing the information i asked for (id steam, steam name, etc.). It gives me the information i asked for, but it doesn't redirect me to the index.html.
I searched all over the internet and i couldn't find an answer. If someone can help me and tell me where i should change the code so as to get redirected to the index.html and connected i would appreciate it a lot.
Thanks in advanced and sorry for my english, Davor.

validation php not working?

The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html

Why am I getting Error: Query was empty?

I am creating a login part to my web page. When a new person registers their details, pressing the register button goes to a register_ok part, showing below:
case 'register_ok':
if (!$_POST['client_username'] || !$_POST['client_password'] ||
!$_POST['client_email']) {
die('You did not fill in a required field.');
}
// check if username exists in database.
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
die('Sorry, the username: <strong>'.$_POST['client_username'].'</strong>'
. ' is already taken, please pick another one.');
}
}
// check e-mail format
if (!preg_match("/.*#.*..*/", $_POST['client_email']) ||
preg_match("/(<|>)/", $_POST['client_email'])) {
die('Invalid e-mail address.');
}
// no HTML tags in username, website, location, password
$_POST['client_username'] = strip_tags($_POST['client_username']);
$_POST['client_password'] = strip_tags($_POST['client_password']);
// now we can add them to the database.
// encrypt password
$_POST['client_password'] = md5($_POST['client_password']);
if (!get_magic_quotes_gpc()) {
$_POST['client_password'] = addslashes($_POST['client_password']);
$_POST['client_email'] = addslashes($_POST['client_email']);
}
$insert = "INSERT INTO client (
client_username,
client_password,
client_name,
client_email,
client_last_access)
VALUES (
'".$_POST['client_username']."',
'".$_POST['client_password']."',
'".$_POST['client_name']."',
'".$_POST['client_email']."',
'now()'
)";
if(!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else{
$id= mysql_insert_id();
session_start();
echo '<script>alert("You May Now Login");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
break;
}
When I register a new person, I get the following error:
Error: Query was empty
Why is this?
In the line if(!mysql_query($sql,$con)) {, do you mean $insert instead of $sql?
Do:
if(!mysql_query($sql,$con)) {
to
if(!mysql_query($insert,$con)) {
your variable name is not correct

Categories