how can set counter limit? - php

Hi i have a counter code. I want to stop when (example) 11 result. how can i stop curl when script count 11 result?
<?php
class instaAuth
{
public function _userlistesi() {
$klasor = opendir("cookieboq/");
while(false !== ($veriler = readdir($klasor))) {
if(strstr($veriler,'selco')) {
$bir_veri = str_replace('.selco','',$veriler);
$user_ekle .= "$bir_veri,";
}
}
$userler = substr($user_ekle,0,-1);
$users_arr = explode(",",$userler);
return $users_arr;
}
public function _authLike($_ID,$userlist, $DELETE = NULL)
{
if ( !empty($userlist) )
{
$type = ($DELETE == TRUE) ? 'unlike' : 'like';
$members = array();
$params = array();
foreach ( $userlist as $username )
{
$_cookie = $this->_cookieFolder . $username . $this->_cookieExtension;
$randomProxy = ( count($this->_proxy) > 0 ) ? $this->_proxy[rand(0, (count($this->_proxy) - 1))] : NULL;
if ( !file_exists($_cookie) )
{
continue;
}
$members[] = $username;
$fake_ip = $this->fakeIP();
$header = array(
"Accept: */*",
"Accept-Language: tr;q=1",
"HTTP_CLIENT_IP" => $fake_ip,
"HTTP_FORWARDED" => $fake_ip,
"HTTP_PRAGMA" => $fake_ip,
"HTTP_XONNECTION" => $fake_ip,);
$options = array(
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $this->signed(json_encode(array())),
CURLOPT_HTTPHEADER => $header,
CURLOPT_COOKIEJAR => $_cookie,
CURLOPT_COOKIEFILE => $_cookie,
CURLOPT_USERAGENT => $this->_useragent,
);
$params[] = array(
'url' => "https://i.instagram.com/api/v1/media/{$_ID}/{$type}/",
'options' => $options
);
}
} else {
throw new Exception('Error: _authLike() - Beğeni yaptırabilmeniz için {cookies} tanımlamalısınız.');
}
$multiCURL = new \RollingCurl\RollingCurl();
foreach ($params as $param) {
$request = new \RollingCurl\Request($param['url'], 'POST');
$request->setOptions($param['options']);
$multiCURL->add($request);
}
$this->_result = 0;
$multiCURL
->setCallback(function(\RollingCurl\Request $request, \RollingCurl\RollingCurl $rollingCurl) {
$result = $request->getResponseText();
if ( is_string($result) )
{
$result = json_decode($result);
if ( is_object($result) )
{
if ($result->status == 'ok') $this->_result++;
}
}
})
->setSimultaneousLimit(100)
->execute()
;
$result = array(
'success' => $this->_result,
'errors' => NULL
);
return json_decode(json_encode($result));
}
}
and this insterested other code page
<form action="" method="POST">
Pictures ID : <input type="text" name="apifotoId">
<br>
Limits : <input type="text" name="limit">
<br>
<input type="submit" value="Like Send">
</form>
<?php
include("class.php")
if(isset($_POST['apifotoId'])) {
$start = time();
$y = new instaAuth();
$user_list = $y->_userlistesi();
$limit = $_POST["limit"];
$_ID = $_POST['apifotoId'];
$y->_authLike($_ID,$user_list);
$fark = round(time()-$start)/60;
echo "Likes Complete (".$fark." dk.)";
}
?>
I want to stop when (example) 11 result. how can i stop curl when script count 11 result?

you can make an if statement only in function "authLike" condition if(result ==11) break;
and you if you clear your answer to help you more .

Related

GAPI.LOL API throwing unknown error while opening Game

I am integrating gapi.lol API into a website and the examples are in core PHP and so I had to rewrite them to Laravel because it is the framework the website is using. The API has no support team and so there is no one I can ask a question when need be. I did everything as instructed, however, the problem comes when opening a single game, it throws an unknown error!
The following is the guidance on their website on how to integrate the API.
Importand when a player wins EGT jackpot, Our api server sends writeBet api call with game ID 2500 and your api server should answer with success message
Global jackpot will sends the id of the game player playing.
EXAMPLE
return $apiresult = array(
"status" => "success",
"error" => '',
"login" => ExampleAccount,
"balance" => PlayerBalance,
);
#1 Create users table (you can use your existing table)
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`score` bigint(20) DEFAULT '0',
`callback_key` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ext` (`callback_key`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
#2 Create table user_bets (save bet/wins)
-- ----------------------------
-- Table structure for user_bets
-- ----------------------------
DROP TABLE IF EXISTS `user_bets`;
CREATE TABLE `user_bets` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`in` bigint(20) DEFAULT '0',
`out` bigint(20) DEFAULT '0',
`user_id` bigint(20) DEFAULT NULL,
`date` datetime DEFAULT '1970-01-01 00:00:01',
`game_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=49 DEFAULT CHARSET=latin1;
#3 Create wallet
This is php example you can use any language you want.
if you use your own table do not forget to change the fields on mysql querys
header('Access-Control-Allow-Headers: *'); // This is only for test your wallet
header('Access-Control-Allow-Origin: *'); // This is only for test your wallet
header('Access-Control-Allow-Methods: POST'); // This is only for test your wallet
header('Access-Control-Max-Age: 1000'); // This is only for test your wallet
$db_host = "localhost"; // CHANGE THIS LINE
$db_name = "database"; // CHANGE THIS LINE
$db_user = "root"; // CHANGE THIS LINE
$db_password = "password"; // CHANGE THIS LINE
function sqlsafe($s)
{
global $conn;
$str = strval($s);
return $conn->real_escape_string($str);
}
$inputJSON = file_get_contents('php://input');
if ($inputJSON != '') {
$input = json_decode($inputJSON, TRUE); //convert JSON into array
if (count($input) != '') {
foreach ($input as $name => $value) {
$_POST[$name] = $value;
}
}
} else {
$apiresult = array(
"status" => "fail",
"error" => "101"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$conn = new mysqli($db_host, $db_user, $db_password, $db_name);
if ($conn->connect_error) {
$apiresult = array(
"status" => "fail",
"error" => $conn->connect_error
);
echo json_encode($apiresult);
exit();
}
$cmd = $_POST['cmd'];
$login = sqlsafe($_POST['login']);
if(isset($_POST['gameId'])){
$gameId = $_POST['gameId'];
}
$balance = '1000';
$operationId = '100';
$key = sqlsafe($_POST['key']);
switch ($cmd) {
case 'getBalance':
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
if ($result) {
if ($result->num_rows > 0) {
$userfound = true;
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$apiresult = array(
"status" => "success",
"error" => "",
"login" => $login,
"balance" => $balance
);
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found1"
);
echo json_encode($apiresult);
exit();
}
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found2"
);
echo json_encode($apiresult);
exit();
}
if (!$userfound) {
$apiresult = array(
"status" => "fail",
"error" => "user_not_found3"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
break;
case 'writeBet':
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$winLose = $_POST['winLose'];
$bet = $_POST['bet'];
$out = $winLose + $bet;
$gameId = $_POST['gameId'];
if ($balance < $bet) {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$winLose = (int)floor($winLose * 100 + 0.00001);
$sql = "update `users` set `score` = (`score` + ($winLose)) where (`score`+($winLose)) >= 0 and `id`='$login' and callback_key='$key'";
//writeLog($sql);
$result = $conn->query($sql);
if ($result) {
$bet = (int)floor($bet * 100 + 0.00001);
$out = (int)floor($out * 100 + 0.00001);
$sql = "INSERT INTO user_bets set `in` =$bet, `out`=$out, game_id = $gameId, date=now(), user_id = $login";
$result = $conn->query($sql);
//echo $result;
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$apiresult = array(
"status" => "success",
"error" => '',
"login" => $login,
"balance" => $balance,
"operationId" => $operationId
);
} else {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance " . $conn->error
);
}
break;
}
$response = json_encode($apiresult);
echo $response;
#4 Create play page
require_once('lib/ApiClient.php'); //class for api calls
//AMATIC API VARIABLES
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_ID = 'API ID'; // CHANGE THIS LINE
$API_KEY = 'API KEY'; // CHANGE THIS LINE
$GAME_URL = 'https://play.gapi.lol/play/';
//YOUR API VARIABLES
$CALLBACK_URL = 'http://yourdomain.com/wallet.php'; // CHANGE THIS LINE URL FROM wallet.php yourdomain.com/wallet.php
$CALLBACK_KEY = '12345'; //change to api key of your wallet api
$parentid = "walletshop"; //change this to Hall ID on your server the user belongs to
$userid = "1"; // user from wallet API
//GAME INVIROMENT VARIABLES
$game = "arisingphoenix";// You can get all valid games with API 'action'=> 'getgames'
$lang = "en"; // Valid values: "en","de","es","ru","tr","cz","gr","ee"
$exiturl = "back.html"; // url to go to when player clicks exit. Your menu url for example.
if(isset($_GET['game']))
$game = $_GET['game'];
//PREPARE API REQUEST
$params = array(
'action' => 'inituser',
'api_id' => $API_ID,
'hash' => $userid,
'parenthash' => $parentid,
'callbackurl' => $CALLBACK_URL,
'callbackkey' => $CALLBACK_KEY
);
//print_r($params);
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
if($resjson===false)
{
echo 'ERROR:'.$client->lasterror;
}
else
{
$resarray = json_decode($resjson,true);
if($resarray['success']=='true') //API CALL WAS SUCCESSFUL
{
echo '
<iframe src="'.$GAME_URL.'?game='.$game.'&hash='.$userid.'&api_id='.$API_ID.'&lang='.$lang.'&exit='.$exiturl.'"
style="border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%" allowfullscreen>
<iframe>';
}
else
{
echo 'error occured:'.$resarray['error'];
}
}
//ApiClient.php
class ApiClient {
public $apiurl;
public $apikey;
public $lasterror;
public function __construct($url = '', $key = '')
{
$this->apiurl = $url;
$this->apikey = $key;
$this->lasterror = '';
}
function SendData($params)
{
$this->lasterror = '';
//CHECK FOR ERRORS
if($this->apikey=='')
{
$this->lasterror = "API KEY NOT SET";
return false;
}
if($this->apiurl=='')
{
$this->lasterror = "API URL NOT SET";
return false;
}
if(count($params)==0)
{
$this->lasterror = "PARAMETERS NOT SET";
return false;
}
if(!$this->is_assoc($params))
{
$this->lasterror = "WRONG PARAMETERS VARIABLE. MUST BE ASSOCIATIVE ARRAY";
return false;
}
//END CHECKING FOR ERRORS
$joinparams = '';
$rand = md5(time());
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$enc_val = urlencode($val);
$post_params[] = $key.'='. $enc_val;
$joinparams = $joinparams.$enc_val;
}
$post_params[] = 'callid'.'='. $rand; //add random unique call identifier
$joinparams = $joinparams.$rand; //add it to sign
$sign = hash_hmac("sha1",$joinparams,$this->apikey);
$post_string = implode('&', $post_params).'&sign='.$sign;
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiurl);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'curl');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
if($result==false)
{
$this->lasterror = curl_error($ch);
return false;
}
}
catch (Exception $e)
{
$this->lasterror = "Exception :".$e->getMessage();
return false;
}
curl_close($ch);
return $result;
}
function is_assoc(array $array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
}
This is how I rewrote the same in Laravel:
WalletController.php:
<?php
namespace App\Http\Controllers;
use App\Wallet;
use App\User_bet;
use App\User;
use App\GameUrl;
use App\Classes\ApiClient;
use Illuminate\Http\Request;
class WalletController extends Controller
{
public function wallet(Request $request)
{
$inputJSON = file_get_contents('php://input');
if ($inputJSON != '') {
$input = json_decode($inputJSON, TRUE); //convert JSON into array
if (count($input) != '') {
foreach ($input as $name => $value) {
$request->$name = $value;
}
}
} else {
$apiresult = array(
"status" => "fail",
"error" => "101"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$cmd = $request->cmd;
$login = $request->login;
if($request->gameId){
$gameId = $request->gameId;
}
$balance = '1000';
$operationId = '100';
$key = $request->key;
switch ($cmd) {
case 'getBalance':
$user = auth()->user();
if ($user) {
$userfound = true;
$balance = floatval($user->score) / 100.00;
$apiresult = array(
"status" => "success",
"error" => "",
"login" => $login,
"balance" => $balance
);
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found1"
);
echo json_encode($apiresult);
exit();
}
if (!$userfound) {
$apiresult = array(
"status" => "fail",
"error" => "user_not_found3"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
break;
case 'writeBet':
$user = auth()->user();
$balance = floatval($user->score) / 100.00;
$winLose = $request->winLose;
$bet = $request->bet;
$out = $winLose + $bet;
$gameId = $request->gameId;
if ($balance < $bet) {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$winLose = (int)floor($winLose * 100 + 0.00001);
$user = auth()->user();
$user->score = $user->score +($winLose);
if ($user->save()) {
$bet = (int)floor($bet * 100 + 0.00001);
$out = (int)floor($out * 100 + 0.00001);
$user_bet = new User_bet();
$user_bet->in = $bet;
$user_bet->out = $out;
$user_bet->game_id = $gameId;
$user_bet->date = now();
$user_bet->user_id = $login;
$user_bet->save();
$user = auth()->user();
$balance = floatval($user->score) / 100.00;
$apiresult = array(
"status" => "success",
"error" => '',
"login" => $login,
"balance" => $balance,
"operationId" => $operationId
);
} else {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance " . $conn->error
);
}
break;
}
}
public function home(){
return view('slot.home');
}
public function getgames()
{
$user = auth()->user();
if($user){
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_KEY = 'LP8CGiNnTTyNxhb3BGxMcLMWdSOMGQRJ';
$params = array(
'api_id' => 'eErNZwJ36onh9qoq5sOek2zN8yWZZePe',
'action' => 'getgames',
'callbackurl' => 'http://127.0.0.1:8000/api/slot/wallet ',
'callbackkey' => 'SDFSD8FHSHD0N');
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
// dd($resjson);
$games =\json_decode($resjson);
return response()-> json($games);
}else{
$error = "User not found".$url;
return response()->json($error);
}
}
public function getUrl($gameName)
{
//AMATIC API VARIABLES
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_ID = 'eErNZwJ36onh9qoq5sOek2zN8yWZZePe'; // API_ID
$API_KEY = 'LP8CGiNnTTyNxhb3BGxMcLMWdSOMGQRJ'; // API_KEY
$GAME_URL = 'https://play.gapi.lol/play/';
//YOUR API VARIABLES
$CALLBACK_URL = 'http://127.0.0.1:8000/api/slot/wallet'; // CHANGE THIS LINE URL FROM wallet.php yourdomain.com/wallet.php
$CALLBACK_KEY = '12345'; //change to api key of your wallet api
$parentid = "walletshop"; //change this to Hall ID on your server the user belongs to
$userid = auth()->user()->id;
//GAME INVIROMENT VARIABLES
$game = $gameName;// You can get all valid games with API 'action'=> 'getgames'
$lang = "en"; // Valid values: "en","de","es","ru","tr","cz","gr","ee"
$exiturl = "http://127.0.0.1:8000/api/slot/home"; // url to go to when player clicks exit. Your menu url for example.
//PREPARE API REQUEST
$params = array(
'action' => 'inituser',
'api_id' => $API_ID,
'hash' => $userid,
'parenthash' => $parentid,
'callbackurl' => $CALLBACK_URL,
'callbackkey' => $CALLBACK_KEY
);
//print_r($params);
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
if($resjson===false)
{
$error = 'ERROR:'.$client->lasterror;
return \response()->json($error);
}
else
{
$resarray = json_decode($resjson,true);
if($resarray['success']=='true') //API CALL WAS SUCCESSFUL
{
$URL =
$GAME_URL.'?game='.$game.'&hash='.$userid.'&api_id='.$API_ID.'&lang='.$lang.'&exit='.$exiturl;
$gameUrl = new GameUrl();
$gameUrl->url = $URL;
$gameUrl->user_id = \auth()->user()->id;
if($gameUrl->save()){
return response()->json($URL);
}
}
else
{
$error = 'error occured:'.$resarray['error'];
return \response()->json($error);
}
}
}
public function play()
{
$user = auth()->user()->id;
$gameUrl = GameUrl::where("user_id", $user)->latest()->first();
$link= $gameUrl->url;
return view('slot.play', compact('link'));
}
}
I am handling it in a way that I list all the games from the API on the home page when someone clicks on any single game, I generate the game URL in the getURL method in wallets controller, the redirect the user to that page. It works well but when someone opens the game, it throws an error in the process of opening.
```Game opening```
Showing CONTINUE button:
Error on localhost

How to execute a specific php script method giving parameters from url

I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.

PHP Loop Function with different parameters

I have a function which queries an api and outputs the response as an array. I can run this function once and then I can echo the array output.
But problem for me is, I can call this function once and have output. But I'd like to loop through these function parameters and call it for multiple usernames. Example:
<?php
require("./include/function.php");
$Player=fetchCharacterDescriptions("Senaxx", "2");
echo "<tr>";
echo "<th class=\"col-md-3\">" . $Player[0]['username'] . "</th>";
foreach ( $Player as $var )
{
echo "<th class=\"col-md-3\">",$var['class']," ",$var['light'],"</th>";
}
echo "</tr>";
echo "</thead>";
echo "</table>";
?>
And this call's the function fetchCharacterDescriptions in function.php which is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$hash = array(
'3159615086' => 'Glimmer',
'1415355184' => 'Crucible Marks',
'1415355173' => 'Vanguard Marks',
'898834093' => 'Exo',
'3887404748' => 'Human',
'2803282938' => 'Awoken',
'3111576190' => 'Male',
'2204441813' => 'Female',
'671679327' => 'Hunter',
'3655393761' => 'Titan',
'2271682572' => 'Warlock',
'3871980777' => 'New Monarchy',
'529303302' => 'Cryptarch',
'2161005788' => 'Iron Banner',
'452808717' => 'Queen',
'3233510749' => 'Vanguard',
'1357277120' => 'Crucible',
'2778795080' => 'Dead Orbit',
'1424722124' => 'Future War Cult',
'2033897742' => 'Weekly Vanguard Marks',
'2033897755' => 'Weekly Crucible Marks',
);
function translate($x)
{
global $hash;
return array_key_exists($x, $hash) ? $hash[$x] : null;
}
//BungieURL
function callBungie($uri)
{
$apiKey = '145c4aff30864167ac4548c02c050679';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-API-Key: ' . $apiKey
));
if (!$result = json_decode(curl_exec($ch) , true))
{
$result = false;
}
curl_close($ch);
return $result;
}
//Request Player
function fetchPlayer($username, $platform)
{
$result = false;
$uri = 'http://www.bungie.net/Platform/Destiny/SearchDestinyPlayer/' . $platform . '/' . $username;
$json = callBungie($uri);
if (isset($json['Response'][0]['membershipId']))
{
$result = array(
'membershipId' => $json['Response'][0]['membershipId'],
'membershipType' => $platform
);
}
return $result;
}
//Request characters
function fetchCharacters($username, $platform)
{
$result = array();
if($player = fetchPlayer($username, $platform)) {
$uri = 'http://bungie.net/Platform/Destiny/'.$player['membershipType'].'/Account/'.$player['membershipId'].'?ignorecase=true';
if( $json = callBungie($uri) ) {
foreach ($json['Response']['data']['characters'] as $character) {
$result[] = $character;
}
}
}
return $result;
}
//Request character descriptions
function fetchCharacterDescriptions($username, $platform)
{
$character_descriptions = array();
if($characters = fetchCharacters($username, $platform)) {
foreach ($characters as $character) {
$class = translate($character['characterBase']['classHash']);
$emblem = $character['emblemPath'];
$backgroundpath = $character['emblemPath'];
$level = $character['characterLevel'];
$character_id = $character['characterBase']['characterId'];
$light = $character['characterBase']['stats']['STAT_LIGHT']['value'];
$username = $username;
$character_descriptions[] = array(
'class'=> $class,
'emblem'=> $emblem,
'backgroundpath'=>$backgroundpath,
'character_id' => $character_id,
'characterlevel' => $level,
'light' => $light,
'username' => $username
);
}
return $character_descriptions;
}
return false;
}
?>
So my function call is: fetchCharacterDescriptions("Senaxx", "2"); and i'd like to add more players to this (from an array or something) So i can request the stats for multiple usernames.
You just have to loop over the players an perform fetchCharacterDescriptions for each of them.
$players = array(
"Senaxx" => "2",
"SomeoneElse" => "2",
);
foreach ($players as $playerName => $platformId) {
$Player = fetchCharacterDescriptions($playerName, $platformId);
// do your other stuff
}
Keep in mind that your webpage will load veeery slow because every call to fetchCharacterDescriptions() executes 2 curl requests. Also - if the API is down, your site effectivly is as well (or blank at least).
You are probably better off fetching the data beforehand (in certain intervalls) and storing it into a database/csv file or something.

Refactoring smartrecruiter api

I'm currently implementing smartrecruiter api in my project. I'm using two endpoints namely /jobs-list and /job-details. The problem is that every time I'm extracting the details in the second endpoint which is the /job-details, the execution time is so slow.
Here's what I've done so far:
function getContext()
{
$opts = array(
'http'=> array(
'method' => 'GET',
'header' => 'X-SmartToken: xxxxxxxxxxxxxxxxx'
)
);
return $context = stream_context_create($opts);
}
function getSmartRecruitmentJob($city, $department)
{
$tmp = array();
$results= array();
$limit = 100; //max limit for smartrecruiter api is 100
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs?limit='.$limit.'&city='.$city.'&department='.$department, false, $this->getContext());
$lists= json_decode($file, true);
foreach($lists['content'] as $key => $list)
{
if ($list['status'] == 'SOURCING' || $list['status'] == 'INTERVIEW' || $list['status'] == 'OFFER')
{
$results['id'] = $list['id'];
$tmp[] = $this->getSmartRecruitmentJobDetails($results['id']);
}
}
return $tmp;
}
function getSmartRecruitmentJobDetails($id)
{
$results = array();
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}
Solved it by caching the function for extracting the data:
function getCache()
{
if ($this->cache === null)
{
$cache = \Zend\Cache\StorageFactory::factory(
array(
'adapter' => array(
'name' => 'filesystem',
'options' => array(
'ttl' => 3600 * 7, // 7 hours
'namespace' => 'some-namespace',
'cache_dir' => 'your/cache/directory'
),
),
'plugins' => array(
'clear_expired_by_factor' => array('clearing_factor' => 10),
),
)
);
$this->cache = $cache;
}
return $this->cache;
}
function getSmartRecruitmentJobDetails($id)
{
$cache = $this->getCache();
$key = md5('https://api.smartrecruiters.com/jobs/'.$id);
$lists = unserialize($cache->getItem($key, $success));
$results = array();
if($success && $lists)
{
header('Debug-cache-recruit: true');
}
else
{
header('Debug-cache-recruit: false');
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$cache->addItem($key, serialize($lists));
}
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country'] = isset($lists['location']['country']) ? $lists['location']['country'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}

How could I fix this Auto Increment?

So, here is my problem on login through steam id it creates an account on my website but it also decides on next login to skip an Auto Increment causing the next registered member to gain a ton of Auto Incremented member id's
<?php
require ("common.php");
class SteamSignIn
{
const STEAM_LOGIN = 'https://steamcommunity.com/openid/login';
public static function genUrl($returnTo = false, $useAmp = true)
{
$returnTo = (!$returnTo) ? (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] : $returnTo;
$params = array(
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => 'checkid_setup',
'openid.return_to' => $returnTo,
'openid.realm' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'],
'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
);
$sep = ($useAmp) ? '&' : '&';
return self::STEAM_LOGIN . '?' . http_build_query($params, '', $sep);
}
public static function validate()
{
$params = array(
'openid.assoc_handle' => $_GET['openid_assoc_handle'],
'openid.signed' => $_GET['openid_signed'],
'openid.sig' => $_GET['openid_sig'],
'openid.ns' => 'http://specs.openid.net/auth/2.0',
);
$signed = explode(',', $_GET['openid_signed']);
foreach($signed as $item)
{
$val = $_GET['openid_' . str_replace('.', '_', $item)];
$params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($val) : $val;
}
$params['openid.mode'] = 'check_authentication';
$data = http_build_query($params);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' =>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content' => $data,
),
));
$result = file_get_contents(self::STEAM_LOGIN, false, $context);
preg_match("#^http://steamcommunity.com/openid/id/([0-9]{17,25})#", $_GET['openid_claimed_id'], $matches);
$steamID64 = is_numeric($matches[1]) ? $matches[1] : 0;
return preg_match("#is_valid\s*:\s*true#i", $result) == 1 ? $steamID64 : '';
}
}
$steam_login_verify = SteamSignIn::validate();
if(!empty($steam_login_verify))
{
// Grab Data From Steam API
$json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $sapik . '&steamids='. $steam_login_verify .'&format=json');
//Decode Data From Steam API
$data = json_decode($json);
foreach($data->response->players as $player)
{
$query = "INSERT INTO steam (steamid, personaname, profileurl, avatar, avatarmedium, avatarfull ) VALUES ( :steamid, :personaname, :profileurl, :avatar, :avatarmedium, :avatarfull) ";
$query_params = array(
':steamid' => $player->steamid,
':personaname' => $player->personaname,
':profileurl' => $player->profileurl,
':avatar' => $player->avatar,
':avatarmedium' => $player->avatarmedium,
':avatarfull' => $player->avatarfull,
);
}
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
switch( $ex->errorInfo[1] )
{
case 1062:
$ps = $db->prepare("SELECT * FROM `steam` WHERE steamid = :sid");
$ps->bindParam(':sid', $steam_login_verify);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_ASSOC);
foreach ($ps as $row)
{
$_SESSION['sid'] = $row['steamid'];
}
header('Location:'.$basedir);
die('redirecting to'.$basedir);
;
}
}
$ps = $db->prepare("SELECT * FROM `steam` WHERE steamid = :sid");
$ps->bindParam(':sid', $steam_login_verify);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_ASSOC);
foreach ($ps as $row)
{
$_SESSION['sid'] = $row['steamid'];
}
header('Location:'.$basedir);
die('redirecting to'.$basedir);
} else {
$steam_sign_in_url = SteamSignIn::genUrl();
}

Categories