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.
Related
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
I am trying to save images from dropbox to my server. I have already done the code for that. I am also checking the HTTP status of the url before downloading the images with code. I am getting proper status but the issue is it always throws an error 401 even when i have put a condition to download images with status code 200 or 302. I am having the links of images in an excel file that i am reading with a laravel package. Please help me.
Image Download Function
public function ImportImagesProcess(Request $request)
{
$product_type = $request->get('product_type');
$category_id = $request->get('category_id');
$category_level = $request->get('category_level');
$filepath = $request->get('file_path');
$total_rows = $request->get('total_rows');
$start_index = $request->get('start_index');
$row_counter_break = $request->get('row_counter_break');
$data = Excel::load($filepath)->limit(false, ($start_index))->get();
$dataArr = $data->toArray();
$array = array_map('array_filter', $dataArr);
$array = array_filter($array);
if ($start_index > $total_rows) {
return response()->json([
'status' => 'complete',
'product_type' => $product_type,
'category_id' => $category_id,
'category_level' => $category_level,
'file_path' => $filepath,
'total_rows' => $total_rows,
'start_index' => 0,
'row_counter_break' => $row_counter_break,
]);
} else {
$rowCounter = 0;
foreach ($array as $value) {
$image_list = [];
if (!empty($value['image1'])) {
array_push($image_list, $value['image1']);
}
if (!empty($value['image2'])) {
array_push($image_list, $value['image2']);
}
if (!empty($value['image3'])) {
array_push($image_list, $value['image3']);
}
if (!empty($value['image4'])) {
array_push($image_list, $value['image4']);
}
if (!empty($value['image5'])) {
array_push($image_list, $value['image5']);
}
foreach ($image_list as $il) {
if ($rowCounter >= $row_counter_break)
break;
$status = self::CheckLinkStatus($il);
if ($status == 200) {
if (strpos($il, "?dl=0") !== false) {
$image_url = str_replace("?dl=0", "", $il);
$image_url = str_replace("www.dropbox.com", "content.dropboxapi.com", $il);
$info = pathinfo($image_url);
$contents = file_get_contents($image_url, true);
$file = $info['basename'];
file_put_contents(public_path('datauploads') . "/" . $file, $contents);
} else {
$img_status = self::CheckLinkStatus($il);
if ($img_status !== 404 && $img_status !== 401) {
$image_url = str_replace("www.dropbox.com", "content.dropboxapi.com", $il);
$info = pathinfo($image_url);
$contents = file_get_contents($image_url, true);
$file = $info['basename'];
file_put_contents(public_path('datauploads') . "/" . $file, $contents);
}
}
}
}
$rowCounter++;
}
return response()->json([
'status' => 'success',
'product_type' => $product_type,
'category_id' => $category_id,
'category_level' => $category_level,
'file_path' => $filepath,
'total_rows' => $total_rows,
'start_index' => $start_index,
'row_counter_break' => $row_counter_break,
]);
}
}
Image Status Check Function
public static function CheckLinkStatus($image)
{
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $retcode;
}
Try this:
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpCode != 404) //# if error code is not "404"
{
/* Your Function here. */
}
else
{
/* Handle 404 here. */
}
Try setting an array of http codes, like:
$httpCodes = [401,404];
And than just check:
if(!in_array(CheckLinkStatus($image),$httpCodes){
// YOur logic
} else {
// Handle 401 && 404
}
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 .
i'm writing a script to execute import of a csv using the admin panel: AdminImport.
The script execute a login into the admin panel and post csv with opportune parameters to import the file.
I've founded this class on web:
<?php
class PSRequest {
protected $_eol = "\r\n";
protected $_useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
protected $_cookieFileLocation = './cookie.txt';
protected $_referer = "http://www.google.com";
protected $_url;
protected $_followlocation;
protected $_timeout;
protected $_maxRedirects;
protected $_post = false;
protected $_multipart = false;
protected $_file = false;
protected $_postFields;
protected $_postFile;
protected $_session;
protected $_includeHeader;
protected $_noBody;
protected $_status;
protected $_binaryTransfer;
protected $_file_to_upload = null;
protected $_file_to_upload_size = 0;
protected $_file_name = '';
protected $_file_transfer_codebase = false;
protected $_file_content_type = '';
protected $_boundary = 'boundaryAAAbbb';
public $_webpage;
public $authentication = 0;
public $auth_name = '';
public $auth_pass = '';
protected $ch; // curl handler
public function __construct($url = '', $followlocation = true, $timeOut = 30, $maxRedirecs = 4, $binaryTransfer = false, $includeHeader = true, $noBody = false)
{
$this->_url = $url;
$this->_followlocation = $followlocation;
$this->_timeout = $timeOut;
$this->_maxRedirects = $maxRedirecs;
$this->_noBody = $noBody;
$this->_includeHeader = $includeHeader;
$this->_binaryTransfer = $binaryTransfer;
$this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';
$this->ch = curl_init();
}
public function __destruct() {
curl_close($this->ch);
}
public function useAuth($use){
$this->authentication = 0;
if($use == true) $this->authentication = 1;
}
public function setEndOfLine($chars) {
$this->_eol = $chars;
}
public function setName($name){
$this->auth_name = $name;
}
public function setPass($pass){
$this->auth_pass = $pass;
}
public function setBoundary($boundary) {
$this->_boundary = $boundary;
}
public function setReferer($referer){
$this->_referer = $referer;
}
public function setCookiFileLocation($path)
{
$this->_cookieFileLocation = $path;
}
public function setFileToUpload($filePath, $filename, $contentType='plain/text')
{
$this->setPostMultipart(array('post'=>'true'));
$this->_file = true;
$this->_file_name = $filename;
$this->_file_content_type = $contentType;
//$this->_file_to_upload = fopen($filePath,'r');
$handle = fopen($filePath, "r");
$this->_file_to_upload_size = filesize($filePath);
$this->_file_to_upload = fread($handle, $this->_file_to_upload_size);
fclose($handle);
}
public function setPostMultipart($postFields)
{
$this->_post = true;
$this->_multipart = true;
if (is_array($postFields)) {
$fields_string = $this->multipart_build_query($postFields);
}
else {
$fields_string = $postFields;
}
$this->_postFields = $fields_string;
}
public function setPost($postFields)
{
$this->_post = true;
if (is_array($postFields)) {
$fields_string = http_build_query($postFields);
}
else {
$fields_string = $postFields;
}
$this->_postFields = $fields_string;
}
public function setUserAgent($userAgent)
{
$this->_useragent = $userAgent;
}
public function call($url = null, $header = null)
{
if(is_null($header)) {
if( $this->_multipart == true ) {
$header = array("Content-Type: multipart/form-data; boundary=".$this->_boundary);
} else {
$header = array('Content-Type: application/x-www-form-urlencoded');
}
}
if ($url) {
$this->_url = $url;
}
if (!$url) {
throw new Exception('You should set an URL to call.');
}
curl_setopt($this->ch,CURLOPT_URL,$this->_url);
curl_setopt($this->ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($this->ch,CURLOPT_TIMEOUT,$this->_timeout);
curl_setopt($this->ch,CURLOPT_MAXREDIRS,$this->_maxRedirects);
curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
curl_setopt($this->ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch,CURLOPT_COOKIESESSION, true );
curl_setopt($this->ch,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
curl_setopt($this->ch,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
if ($this->authentication == 1) {
curl_setopt($this->ch, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
}
if ($this->_multipart) {
curl_setopt($this->ch,CURLOPT_POST,true);
if($this->_file) {
$this->_postFields .= $this->add_multipart_build_file('file',$this->_file_name,$this->_file_content_type);
$this->_postFields .= "--".$this->_eol;
curl_setopt($this->ch, CURLOPT_INFILESIZE, $this->_file_to_upload_size);
curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, 1);
}
} else if ($this->_post) {
curl_setopt($this->ch,CURLOPT_POST,true);
}
curl_setopt($this->ch,CURLOPT_POSTFIELDS,$this->_postFields);
if ($this->_includeHeader) {
curl_setopt($this->ch,CURLOPT_HEADER,true);
}
if ($this->_noBody) {
curl_setopt($this->ch,CURLOPT_NOBODY,true);
}
/* if ($this->_file_to_upload_size > 0 && !is_null($this->_file_to_upload)) {
curl_setopt($this->ch, CURLOPT_READFUNCTION, 'uploadFileCall');
} */
curl_setopt($this->ch,CURLOPT_USERAGENT,$this->_useragent);
curl_setopt($this->ch,CURLOPT_REFERER,$this->_referer);
$this->_webpage = curl_exec( $this->ch );
$this->_status = curl_getinfo( $this->ch, CURLINFO_HTTP_CODE );
return $this->_webpage;
}
public function getHttpStatus()
{
return $this->_status;
}
public function __tostring(){
return $this->_webpage;
}
/*function uploadFileCall($ch, $data){
return fread($this->_file_to_upload, $this->_file_to_upload_size);
}*/
function multipart_build_query($fields){
$retval = '';
foreach($fields as $key => $value){
$retval .= "--".$this->_boundary.$this->_eol."Content-Disposition: form-data; name=\"".$key."\"".$this->_eol.$this->_eol.$value.$this->_eol;
}
//$retval .= "--". $this->_boundary ."--".$this->_eol;
$retval .= "--". $this->_boundary .$this->_eol;
return $retval;
}
function add_multipart_build_file($key,$filename='file.csv',$contentType ="application/csv") {
$retval = '';
$retval .= "Content-Disposition: form-data; name=\"$key\"; filename=\"$filename\"".$this->_eol;
$retval .= "Content-Type: $contentType ".$this->_eol.$this->_eol;
if($this->_file_transfer_codebase == true) {
$retval .= 'Content-Transfer-Encoding: base64'.$this->_eol.$this->_eol;
$retval .= chunk_split(base64_encode($this->_file_to_upload));
} else {
$retval .= $this->_file_to_upload;
}
$retval .= "--". $this->_boundary; // ."--".$this->_eol;
return $retval;
}
}
?>
This is the main script:
$request = new PSRequest();
$request->setCookiFileLocation( __DIR__ . '/PScookie.txt' );
debug( "Login..." );
$request->setPost( array( "email" => $adminLoginEmail, "passwd" => $adminLoginPass, "submitLogin" => "Connexion" ) ); // you must be a super admin
$request->call( $adminUrl . "index.php?controller=AdminLogin" );
$response = $request->_webpage;
preg_match( "/&token=([a-z0-9]+)/", $response, $matches );
// $token = Tools::getAdminTokenLite( 'AdminImport' );
$token = $matches[ 1 ];
debug( "Token: ".$token );
$csvname = $upload_dir . 'prestashop_products.csv';
// Send POST datas just like the admin form would do it, those datas depends on what you want to do : check the import admin page.
$request->setPost(array(
"controller" => "AdminImport",
"token" => $token,
"skip" => 1,
"csv" => $csvname,
"convert" => '',
"regenerate" => '',
"entity" => 1, //1 is for products import
"iso_lang" => "it",
"truncate" => 0,
"forceIDs" => 1,
"match_ref" => 1,
"separator" => ";",
"multiple_value_separator" => ",",
"import" => 1,
"type_value" => array( 1 => 'active', 2 => 'reference', 3 => 'name', 4 => 'category', 5 => 'price_tex', 6 => 'supplier', 7 => 'weight', 8 => 'quantity', 9 => 'description' )
)
);
debug( "call AdminImport and POST datas..." );
$request->call( $adminUrl."index.php?controller=AdminImport&token=".$token );
The script initially works: i can get the admin panel and i succesfully get token!!
but when i POST data, the request fails due to 'token invalid'!!
But the token is ok!!
I've tryed to use the function:
Tools::getAdminTokenLite( 'AdminImport' )
the token is different to the token i get from page, but also not work!!
I think problem regardling php sessions but i don't know hot to resolve it!!
someone can help me?
What my problem is that I can not send array to solr machine in order to update. I am using codeigniter as a framework and here is my code:
$solrData = array();
$solrData['id'] = $this->data['profil_data']['id'];
$solrData['site'] = $this->data['profil_data']['site'];
$solrData['url_Domain'] = $this->data['profil_data']['url_Domain'];
$solrData['url_Page'] = $this->data['profil_data']['url_Page'];
$solrData['url_Profil'] = $this->data['profil_data']['url_Profil'];
$solrData['scr_Kobi_Rank'] = $this->data['profil_data']['scr_Kobi_Rank'];
$solrData['scr_A'] = $this->data['profil_data']['scr_A'];
$solrData['scr_B'] = $this->data['profil_data']['scr_B'];
$solrData['scr_C'] = $this->data['profil_data']['scr_C'];
$solrData['scr_D'] = $this->data['profil_data']['scr_D'];
$solrData['loc_City'] = $this->input->post('plakano');
$solrData['loc_Lat_Lon'] = $this->input->post('loc_Lat_Lon');
$solrData['com_Category'] = explode(',', $this->input->post('category'));
$urunData = $this->input->post('urun_list');
foreach($urunData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Products'][] = $ontoData['baslik'];
}
$hizmetData = $this->input->post('hizmet_list');
foreach($hizmetData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Services'][] = $ontoData['baslik'];
}
$solrData['com_Type'] = $this->input->post('sirketturu');
$solrData['com_Description'] = $this->input->post('description');
$solrData['com_Title_Selected'] = $this->input->post('title');
$solrData['com_Title_Long'] = $this->data['profil_data']['com_Title_Long'];
$solrData['crm_Tel'] = $this->input->post('tel');
$solrData['crm_Fax'] = $this->input->post('fax');
$solrData['crm_Email'] = $this->input->post('email');
$this->solr->updateSolrProfilData($solrData);
And solr process:
public function updateSolrProfilData($arrData)
{
if(count($arrData) == 0)
return FALSE;
$solrClientOptions = $this->solrClientOptionsYazProfil;
$solrClientOptionsCommit = $this->solrClientOptionsYazProfilCommit;
$solrClient = new SolrClient($solrClientOptions);
$solrDoc = new SolrInputDocument();
foreach($arrData as $firmaField => $firmaValue)
{
if(! is_array($firmaValue))
{
$solrDoc->addField($firmaField, $firmaValue);
}
else
{
foreach($firmaValue as $firmaField2 => $firmaValue2)
{
if($firmaValue2 != '')
{
$solrDoc->addField($firmaField, $firmaValue2);
}
}
}
}
try {
$this->_solrCommit($solrClientOptionsCommit);
} catch (Exception $e) {
echo $e->getMessage();
}
}
Solr Commit function:
private function _solrCommit($solrArr)
{
$urlCommit = 'http://' . $solrArr['hostname'] . ":" . $solrArr['port'] . '/' . $solrArr['path'] . "/update?stream.body=%3Ccommit/%3E&wt=json";
$output = file_get_contents($urlCommit);
$outputArr = json_decode($output, TRUE);
if ($outputArr['responseHeader']['status'] === 0)
return TRUE;
else
return FALSE;
}
And that is the options:
private $solrClientOptionsYazProfilCommit = array(
'hostname' => SOLR_HOST_YAZ,
'login' => '',
'password' => '',
'port' => SOLR_PORT,
'path' => 'solr/collection1'
);
Altough try-catch returns no error, the data can not be updated. Moreover, code sends solr commit succesfully. I checked the url but it is in correct form. What is wrong in here?
Dont use PHP/Pecl solr libs. If you can access solr via a URL then you should just use PHP and CURL:
static function doCurl($url, $username = null, $password = null) {
if (!function_exists('curl_init')) {
// throw error
}
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY
);
if ($password != null && $username != null) {
$opts[CURLOPT_USERPWD] = "$username:$password";
}
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
usage is:
doCurl("http://hostNameHere:8983/solr/select/?q=solr&start=0&rows=10&indent=on", "user", "pass");
Your issue is that you are never issuing a command to Solr to add the document that you have built to your index. You are only issuing the commit command, which is executing successfully.
Since you are using PHP, I would recommend using the PHP SolrClient. This will save you from having to manually write all of the functions (add, delete, commit, etc.) yourself. In this case, you would need to call the addDocument function.