JSON PHP Can't call value from Steam URL - php

I'm trying to create a website with Steam's login, but when I try to call a value from JSON, it doesn't work. Everything works in the source code, except for getting the JSON value. I've even tried printing the steam ID, so I know that ID works. The URL works also.
Here's my source code:
<?php
require 'openid.php';
try {
$openid = new LightOpenID('workinganonymouswebsite.com');
if (!$openid->mode) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
} elseif ($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
$steamurl = ($openid->validate() ? $openid->identity . '' : 'error');
if ($steamurl == 'error') {
print "There was an error signing in.";
} else {
$id = end(explode('/', $steamurl));
$jsonurl = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXXXXXXXXXXXXX&steamids=" . $id . "&format=json";
$json = file_get_contents($jsonurl, 0, null, null);
$json_output = json_decode($json);
echo $json_output['players']['personaname'];
}
}
} catch (ErrorException $e) {
echo $e->getMessage();
}
?>
Here's the JSON on the website.
{
"response": {
"players": [
{
"steamid": "76561198049205920",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "baseman101",
"lastlogoff": 1357603378,
"profileurl": "http://steamcommunity.com/id/baseman101/",
"avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/24/24bb7c0505db7efe1f1a602d09a5ea412e0ab4bd.jpg",
"avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/24/24bb7c0505db7efe1f1a602d09a5ea412e0ab4bd_medium.jpg",
"avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/24/24bb7c0505db7efe1f1a602d09a5ea412e0ab4bd_full.jpg",
"personastate": 1,
"primaryclanid": "103582791429521408",
"timecreated": 1316469294,
"loccountrycode": "US",
"locstatecode": "VA",
"loccityid": 3918
}
]
}
}
I've tried googling everything. I'm sorry if there is something I missed.

Thanks for all of your help. I basically put the JSON code in a variable, retrieving it from the Steam website. This is the best solution and I'm sticking to it.
<?php
require 'openid.php';
try {
$openid = new LightOpenID('blah.com');
if (!$openid->mode) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
} elseif ($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
$steamurl = ($openid->validate() ? $openid->identity . '' : 'error');
if ($steamurl == 'error') {
print "There was an error signing in.";
} else {
$id = end(explode('/', $steamurl));
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$json_source = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXXXXXXXXXXXXXXXXXXX&steamids=" . $id . "&format=json",false,$context);
$json_output = json_decode($json_source,true);
$json_output->response->players[0]->personaname;
echo $json_output["response"]["players"][0]["personaname"];
}
}
} catch (ErrorException $e) {
echo $e->getMessage();
}
?>
Thank you, Passerby and hakre for the help.
In the future, I have to create cookies, and all of the easy stuff. I'm actually starting that right now.

Related

I dont know this error or how to fix it can some one fix it for me?

I'm getting this error message if I try to start the bot:
[INFO] Try to initialize connection...
PHP Fatal error: Uncaught Error: Call to a member function getAdapter() on null in /var/www/vhosts/kaitomar.de/httpdocs/tsbot/myteamspeakid/bot.php:70
Stack trace:
#0 {main}
Currently I'm using the php version 7.0.33.
I hope someone can help me out with my issue
<?php
session_start();
require_once("ts3phpframework-1.1.32/libraries/TeamSpeak3/TeamSpeak3.php");
require_once("config.php");
require_once("myTeamSpeak.php");
require_once("lib/color.class.php");
$colors = new Colors();
echo $colors->getColoredString("== START ==", "white"), PHP_EOL;
function connectToServer(&$ts3_VirtualServer)
{
global $query, $colors;
try {
echo $colors->getColoredString("[INFO] Try to initialize connection...", "light_gray"), PHP_EOL;
$ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $query['username'] . ":" . $query['password'] . "#" . $query['ipAddress'] . ":" . $query['port'] . "/?server_port=" . $query['voicePort'] . "&nickname=" . urlencode($query['nickname']) . "&blocking=0");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("serverqueryWaitTimeout", "onTimeout");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyCliententerview", "onJoin");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyTextmessage", "onTextmessage");
$ts3_VirtualServer->notifyRegister("server");
$ts3_VirtualServer->notifyRegister("textprivate");
echo $colors->getColoredString("[INFO] Connection to Virtual Instance \"".$ts3_VirtualServer["virtualserver_name"]."\" successfully established!", "light_gray"), PHP_EOL;
echo $colors->getColoredString("[INFO] Memory usage: ".convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(),"MB"), "light_gray"), PHP_EOL;
$vVersion = $ts3_VirtualServer["virtualserver_version"];
$ex[1] = explode("]", $vVersion);
$ex[2] = explode(": ", $ex[1][0]);
(!"1530178919" >= $ex[2][1] ? stopBot() : '');
return true;
}
catch(TeamSpeak3_Transport_Exception $e){
$erromsg = $e->getMessage();
if(isset($erromsg) && $erromsg == "Connection refused"){
print_r($colors->getColoredString("[ERROR] Message from Framework: " . $erromsg . "\nThe query is not accessible.\nThe server is probably offline...", "white", "red"), PHP_EOL);
} else {
print_r($colors->getColoredString("[ERROR] " . $e->getMessage(), "white", "red"), PHP_EOL);
}
return false;
}
catch(Exception $e)
{
print_r($colors->getColoredString("[ERROR2] " . $e, "white", "red"), PHP_EOL);
return false;
}
}
function autoReconnect(&$ts3_VirtualServer, &$reconnectTime)
{
global $colors;
do{
echo $colors->getColoredString("gc_collect_cycles ".gc_collect_cycles(), "red"), PHP_EOL;
echo $colors->getColoredString("__destruct ". $ts3_VirtualServer->getAdapter()->__destruct(), "red"), PHP_EOL;
// sleep for wait to check if server is online
sleep(intval($reconnectTime));
}while(!connectToServer($ts3_VirtualServer));
}
$autoReconnectTime = $option['reconnect_int'];
while(true){
try{
if(!isset($ts3_VirtualServer)) connectToServer($ts3_VirtualServer);
try{
while(1) $ts3_VirtualServer->getAdapter()->wait();
}
catch(TeamSpeak3_Transport_Exception $e){
echo $colors->getColoredString("[EXC1] ".$e->getMessage(), "red"), PHP_EOL;
autoReconnect($ts3_VirtualServer, $autoReconnectTime);
}
catch(Exception $e){
echo $colors->getColoredString("[EXC2]", "red"), PHP_EOL;
echo $colors->getColoredString("ErrMsg: ".$e->getMessage(), "red", "white"), PHP_EOL;
echo $colors->getColoredString("Code: ".$e->getCode(), "white", "yellow"), PHP_EOL;
echo $colors->getColoredString("Sender: ".$e->getSender(), "red"), PHP_EOL;
}
}
catch(Exception $e){
echo $colors->getColoredString("[EXC0] ".$e->getMessage(), "red"), PHP_EOL;
autoReconnect($ts3_VirtualServer, $autoReconnectTime);
}
}
function stopBot(){
global $colors;
echo $colors->getColoredString("[WARNING] Stopping Bot...", "yellow"), PHP_EOL;
echo $colors->getColoredString("Reason you need minimum the Server-Version 3.3.0", "yellow"), PHP_EOL;
echo $colors->getColoredString("You can download the latest beta here: http://dl.4players.de/ts/releases/pre_releases/server/?C=M;O=D", "yellow"), PHP_EOL;
sleep(1);
exit();
}
function onTimeout($seconds, TeamSpeak3_Adapter_ServerQuery $adapter) {
$last = $adapter->getQueryLastTimestamp();
$time = time();
$newtime = $time-300;
$update = $last < $newtime;
//$update_str = ($update) ? 'true' : 'false';
//print_r("Timeout! seconds=$seconds last=$last time=$time newtime=$newtime update=$update_str\n");
if($update)
{
$adapter->request("clientupdate");
}
}
function onJoin(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host)
{
runChecker(getEvent($event, $host), $host);
}
function onTextmessage(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host)
{
global $settings, $db, $ts3_VirtualServer, $colors;
$client = $host->serverGetSelected()->clientGetById($event["invokerid"]);
$clientInfo = $client->getInfo();
if ($clientInfo["client_type"] == 0) {
if ($host->whoami()['client_unique_identifier'] != $event["invokeruid"]) {
if (isUID($clientInfo['client_unique_identifier'])) {
if (isCommand("!help", $event["msg"], $client)) {
$client->message("[u]Available command commands...[/u]");
$client->message("[B]!get info ram [KB|MB|GB][/B] | Shows the current RAM consumption of the bot.");
$client->message("[B]!get countKickedUser ofBadges[/B] | Shows the count of all kicked user if there have set badges (only on this session)");
} else if (isCommand("!get info ram KB", $event["msg"], $client) OR isCommand("!get info ram MB", $event["msg"], $client) OR isCommand("!get info ram GB", $event["msg"], $client)) {
if (isCommand("!get info ram KB", $event["msg"], $client)) {
$client->message("The RAM consumption is [B]" . convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(), "KB") . "[/B]");
} else if (isCommand("!get info ram MB", $event["msg"], $client)) {
$client->message("The RAM consumption is [B]" . convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(), "MB") . "[/B]");
} else if (isCommand("!get info ram GB", $event["msg"], $client)) {
$client->message("The RAM consumption is [B]" . convert($ts3_VirtualServer->getParent()->getAdapter()->getProfiler()->getMemUsage(), "GB") . "[/B]");
}
} else if (isCommand("!get info ram", $event["msg"], $client)) {
$client->message("Error, please use this command so [B]!get info ram [KB|MB|GB][/B]");
} else if (isCommand("!get countKickedUser ofBadges", $event["msg"], $client)) {
(!isset($_SESSION['countOfKickedBadgesUser']) ? $countKickedUserBadge = 0 : $countKickedUserBadge = $_SESSION['countOfKickedBadgesUser']);
$client->message("There were already " . $countKickedUserBadge . " users (in this session) kicked from the server because these badges had set!");
} else {
$client->message("Command not found, use \"!help\" for more informations...");
}
echo $colors->getColoredString("[EVENT][INCOMING][textprivate][" . date("d.m.Y h:i:sa") . "] '" . $clientInfo['client_nickname'] . "' send a message: " . $event["msg"], "light_blue"), PHP_EOL;
} else {
echo $colors->getColoredString("[" . date("d.m.Y h:i:sa") . "] Invalid Master '" . $clientInfo['client_nickname'] . "' send a message: " . $event["msg"], "light_blue"), PHP_EOL;
$client->message("You are not my Master!");
}
}
}
}

Facebook API - Required param "state" missing from persistent data

I know that this question is a duplicate of another, however after searching Google and Stack Overflow, I have still yet to find a solution.
I have some code which calls the Facebook API for a login URL. However, I am doing it in a somewhat indirect way. Basically here is the server flow:
Client chooses to login to app with FB
Client website (A) sends HTTP GET request to intermediate website (B)
Website B returns login URL on website B which includes 2 callbacks: a login URL to FB generated with fb->getLoginUrl() and a callback to website A.
Website A redirects to login page on Website B which redirects to login page on FB
User logs in and grants permissions to app on FB website
FB redirects to callback on website B which gets the access code.
Website B redirects to Website A callback passing the access code as a $_GET variable
Website A uses the access token as it wishes
So very complicated and I only include the flow to possibly make answering this question and understanding the code in PHP easier.
PHP
Website A Code:
if (!isset($_GET['code'])) {
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$request_url = "http://embocorp.com/factory/api.php/facebook/login?callback=".$callback;
header("Location: ".implode(json_decode(callAPI("GET", $request_url), true)['body']['data']));
} else {
echo $_GET['code'];
}
Website B Code:
api.php
if (!session_id()) {
session_start();
}
require_once("vendor/autoload.php");
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = $_SERVER['PATH_INFO'];
$table = array_shift($request);
$key = array_shift($request);
parse_str($_SERVER['QUERY_STRING'], $query_array);
$callback = "http://embocorp.com/factory/api.php/facebook/callback?call=";
function returnData($data, $options = "") {
$response = [
"data"=>$data
];
return json_encode($response, $options);
}
function getFacebookConnection($appid, $appsecret) {
return new Facebook\Facebook(['app_id' => $appid,'app_secret' => $appsecret,'default_graph_version' => 'v2.5', 'persistent_data_handler'=>'session']);
}
function facebookHandleRequest($request, $connection, $details = null) {
switch($request) {
case "login":
$callback_url = $GLOBALS["callback"].$GLOBALS['query_array']['callback'];
echo returnData("http://embocorp.com/factory/login.php?fb=".getFacebookLoginURL($connection, $callback_url), JSON_UNESCAPED_SLASHES);
break;
case "callback":
if (!empty($GLOBALS["query_array"])) {
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
$access = getFacebookAccessCode($connection);
$called = $GLOBALS['query_array']['called'];
header("location: ".$called."?code=".$access);
} else {
echo returnError(400, "Bad Request, missing authorization");
}
break;
case "me":
if (!empty($GLOBALS["query_array"]) && array_key_exists("accessToken", $GLOBALS["query_array"]) == true) {
$response = $connection->sendRequest('GET', '/me', [], $GLOBALS["query_array"]["accessToken"], 'eTag', 'v2.2');
$user = $response->getGraphUser();
echo returnData($user);
} else {
echo returnError(400, "Bad Request, missing authorization");
}
break;
default:
echo returnError(404, "Request URI Not Found");
break;
}
}
function getFacebookLoginURL($connection, $callback_url) {
$helper = $connection->getRedirectLoginHelper();
$permissions = ['manage_pages', 'publish_pages', 'read_insights'];
$loginUrl = $helper->getLoginUrl($callback_url, $permissions);
foreach ($_SESSION as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
if(setcookie($k, $v)) {
$_COOKIE[$k]=$v;
}
}
}
return $loginUrl;
}
function getFacebookAccessCode($fb){
if (!session_id()) {
$accessToken = $_SESSION['facebook_access_token'];
return $accessToken;
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string) $accessToken;
return (string) $accessToken;
} else {
return false;
}
}
}
switch ($table) {
case "facebook":
$fb = getFacebookConnection($appid, $appsecret);
facebookHandleRequest($key, $fb);
break;
case "twitter":
echo "no";
break;
default:
exit();
break;
}
session_write_close();
?>
login.php
if (!session_id()) {
session_start();
}
if (isset($_GET['fb'])) {
$redirect = str_replace("fb=", "", $_SERVER['QUERY_STRING']);
header("Location: ".$redirect);
} else {
echo "ni";
}
Again, thank you for any help, this has been driving me crazy for 72 hours now.
Just add,
if (!session_id()) {
session_start();
}
in start both file.

How to replace in PHP?

Here's the code I'm currently working with:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
echo $proxy->run($url, $_GET, $_POST);
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
This is the part of the code I'm having issues with specifically:
echo $proxy->run($url, $_GET, $_POST);
This will echo a website after running it through a proxy. What I'm trying to do is replace <head> with the following text: <head> this is a test
So, I tried changing to code to this:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
$proxy_replace = str_replace('<head>','<head> this is a test',$proxy);
echo $proxy_replace->run($url, $_GET, $_POST);
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
But this is the error I'm getting:
Catchable fatal error: Object of class Proxy could not be converted to string in /home/username/public_html/testfolder/index.php on line 249
Any help with this would be greatly appreciated....
You need to perform the replacement on the downloaded HTML, not on the Proxy instance. Something like this should work:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
$html = $proxy->run($url, $_GET, $_POST);
$html_replace = str_replace('<head>','<head> this is a test',$html);
echo $html_replace;
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}

PHP - Define file include in class for all methods to use

Is there a way on including a file at the beginning of a class for all methods to use. The example below is a simplified version of what I am trying to achieve. Currently I have to include the file within every method.
Example Logic (not working)
class Myclass
{
protected require_once 'folerd1/folder2/pear/HTTP/Request2.php'; // this does not work
public function aMethod()
{
$request = new HTTP_Request2('http://example1.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new HTTP_Request2('http://example2.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
// more methods
}
2 solution
1) require_once taken outside from class
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
2) Include in the construct
public function __construct() {
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
}
But it is better first option
The best way is to look at autoloading standard http://www.php-fig.org/psr/psr-0/
Have you tried this? I don't know what's your Request2.php file content. So my code is only a PoC!
require 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
public function aMethod()
{
$request = new Request2('http://example1.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new Request2('http://example2.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
As I commented out, just require the file in the constructor of the PHP class:
class Myclass{
function Myclass(){
require_once('folerd1/folder2/pear/HTTP/Request2.php');
}
I have not checked this, but it MIGHT be possible that what you're just doing is including it not only for all the class to see, but the entire script. Please, check that out if it is a problem for you. If not, the other 2 solutions might end up doing the same.
Cheers

php array function in class

I cant get this script to work, $users should hold the array data we take out of the database but it doesnt seem to work. Can anyone tell us what we are doing wrong? i posted the script bellow.
added
$users has to stay static becaus it gets used again later on in the script (this is just a small part)
$user1 does get the right data it just doesnt get passed on to $users
added
this is the intire script hope that helps
<?php
class SingleSignOn_Server
{
public $links_path;
protected $started=false;
protected static $brokers = array(
'FGPostbus' => array('secret'=>"FGPostbus123"),
);
protected static $users = array();
public function query_personen(){
mysql_connect('host','user','pass') or die("Kan helaas geen verbinding maken" . mysql_error());
mysql_select_db('db') or die("Kan geen database selecteren");
$sql = mysql_query('select p_gebruikersnaam, p_wachtwoord, p_id, p_md5 FROM personen');
while ($row_user = mysql_fetch_assoc($sql)) {
self::$users[] = $row_user;
}
}
protected $broker = null;
public function __construct()
{
if (!function_exists('symlink')) $this->links_path = sys_get_temp_dir();
}
protected function sessionStart()
{
if ($this->started) return;
$this->started = true;
$matches = null;
if (isset($_REQUEST[session_name()]) && preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $_REQUEST[session_name()], $matches)) {
$sid = $_REQUEST[session_name()];
if (isset($this->links_path) && file_exists("{$this->links_path}/$sid")) {
session_id(file_get_contents("{$this->links_path}/$sid"));
session_start();
setcookie(session_name(), "", 1);
} else {
session_start();
}
if (!isset($_SESSION['client_addr'])) {
session_destroy();
$this->fail("Not attached");
}
if ($this->generateSessionId($matches[1], $matches[2], $_SESSION['client_addr']) != $sid) {
session_destroy();
$this->fail("Invalid session id");
}
$this->broker = $matches[1];
return;
}
session_start();
if (isset($_SESSION['client_addr']) && $_SESSION['client_addr'] != $_SERVER['REMOTE_ADDR']) session_regenerate_id(true);
if (!isset($_SESSION['client_addr'])) $_SESSION['client_addr'] = $_SERVER['REMOTE_ADDR'];
}
protected function generateSessionId($broker, $token, $client_addr=null)
{
if (!isset(self::$brokers[$broker])) return null;
if (!isset($client_addr)) $client_addr = $_SERVER['REMOTE_ADDR'];
return "SSO-{$broker}-{$token}-" . md5('session' . $token . $client_addr . self::$brokers[$broker]['secret']);
}
protected function generateAttachChecksum($broker, $token)
{
if (!isset(self::$brokers[$broker])) return null;
return md5('attach' . $token . $_SERVER['REMOTE_ADDR'] . self::$brokers[$broker]['secret']);
}
public function login()
{
$this->sessionStart();
if (empty($_POST['p_gebruikersnaam'])) $this->failLogin("No user specified");
if (empty($_POST['p_wachtwoord'])) $this->failLogin("No password specified");
if (!isset(self::$users[$_POST['p_gebruikersnaam']]) || self::$users[$_POST['p_gebruikersnaam']]['p_wachtwoord'] != md5($_POST['p_wachtwoord'])) $this->failLogin("Incorrect credentials");
$_SESSION['user'] = $_POST['p_gebruikersnaam'];
$this->info();
}
public function logout()
{
$this->sessionStart();
unset($_SESSION['user']);
echo 1;
}
public function attach()
{
$this->sessionStart();
if (empty($_REQUEST['broker'])) $this->fail("No broker specified");
if (empty($_REQUEST['token'])) $this->fail("No token specified");
if (empty($_REQUEST['checksum']) || $this->generateAttachChecksum($_REQUEST['broker'], $_REQUEST['token']) != $_REQUEST['checksum']) $this->fail("Invalid checksum");
if (!isset($this->links_path)) {
$link = (session_save_path() ? session_save_path() : sys_get_temp_dir()) . "/sess_" . $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
if (!file_exists($link)) $attached = symlink('sess_' . session_id(), $link);
if (!$attached) trigger_error("Failed to attach; Symlink wasn't created.", E_USER_ERROR);
} else {
$link = "{$this->links_path}/" . $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
if (!file_exists($link)) $attached = file_put_contents($link, session_id());
if (!$attached) trigger_error("Failed to attach; Link file wasn't created.", E_USER_ERROR);
}
if (isset($_REQUEST['redirect'])) {
header("Location: " . $_REQUEST['redirect'], true, 307);
exit;
}
header("Content-Type: image/png");
readfile("empty.png");
}
public function info()
{
$this->sessionStart();
if (!isset($_SESSION['user'])) $this->failLogin("Not logged in");
header('Content-type: text/xml; charset=UTF-8');
echo '<?xml version="1.0" encoding="UTF-8" ?>', "\n";
echo '<user identity="' . htmlspecialchars($_SESSION['user'], ENT_COMPAT, 'UTF-8') . '">';
echo ' <p_id>' . htmlspecialchars(self::$users[$_SESSION['user']]['p_id'], ENT_COMPAT, 'UTF-8') . '</p_id>';
echo ' <p_md5>' . htmlspecialchars(self::$users[$_SESSION['user']]['p_md5'], ENT_COMPAT, 'UTF-8') . '</p_md5>';
echo '</user>';
}
protected function fail($message)
{
header("HTTP/1.1 406 Not Acceptable");
echo $message;
exit;
}
protected function failLogin($message)
{
header("HTTP/1.1 401 Unauthorized");
echo $message;
exit;
}
}
if (realpath($_SERVER["SCRIPT_FILENAME"]) == realpath(__FILE__) && isset($_GET['cmd'])) {
$ctl = new SingleSignOn_Server();
$ctl->$_GET['cmd']();
}
At the very least you probably want to:
self::$users[] = $users1[$row_user['p_gebruikersnaam']] = $row_user;
Since as is you where replacing the record every time and keeping only one.
You're building an array as a property of an object, but not using an instance of the object. You need to build a new instance ($usersObject = new ObjectName;), drop the static keywords, and instead of self::, use $this->. You also need square brackets after self::$users, like this: self::$users[].
Shouldn't this self::$users = $users1[$row_user['p_gebruikersnaam']] = $row_user; be:
array_push($this->users, $row_user)
You could put directly the result into the array:
while (false === ($row_user = mysql_fetch_array($sql, MYSQL_ASSOC)))
self::$users[$row_user['p_gebruikersnaam']] = $row_user;

Categories