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.
Related
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.
I have built a custom front-end multipage donation form on Wordpress, saving the data via session variables across the pages. I then use save_post hook to run a function to redirect the user, after submitting the form, to an online payment portal. The problem is, when users access the form via mobile, the function wp_insert_post fires multiple time.
This is the code that I have on the php page used for processing the data from the form.
<?php
header('Cache-Control: no cache'); //no cache
session_cache_limiter('private_no_expire'); // works
//session_cache_limiter('public'); // works too
//let's start the session
session_start();
require_once 'library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
//LISTING ALL VARIABLES AVAILABLE FROM FRONTEND FORM
$negara = $_SESSION['negara'];
$binatang = $_SESSION['binatang'];
if($_SESSION['ekor']) {
$ekorBahagian = $_SESSION['ekor'];
} else {
$ekorBahagian = $_SESSION['bahagian'];
}
$nama1 = $_SESSION['nama'];
$kp1 = $_SESSION['kp'];
$telefon1 = $_SESSION['telefon'];
$emel1 = $_SESSION['emel'];
$alamat11 = $_SESSION['alamat1'];
$alamat21 = $_SESSION['alamat2'];
$poskod1 = $_SESSION['poskod'];
$bandar1 = $_SESSION['bandar'];
$negeri1 = $_SESSION['negeri'];
$peserta1 = $_SESSION['peserta'];
$kempen = $_POST['kempen'];
$bank = $_POST['bank'];
if($telefon1) {
$mobile = preg_replace("/[^0-9]/", "", $telefon1);
$custTel = $mobile;
$custTel2 = substr($mobile, 0, 1);
if ($custTel2 == '+') {
$custTel3 = substr($mobile, 1, 1);
if ($custTel3 != '6') {
$custTel = "+6" . $mobile;
}
} elseif ($custTel2 == '6') {
} else {
if ($custTel != '') {
$custTel = "+6" . $mobile;
}
}
}
//purifying the texts
$nama = $purifier->purify($nama1);
$kp = $purifier->purify($kp1);
$telefon = $purifier->purify($custTel);
$emel = $purifier->purify($emel1);
$alamat1 = $purifier->purify($alamat11);
$alamat2 = $purifier->purify($alamat21);
$poskod = $purifier->purify($poskod1);
$bandar = $purifier->purify($bandar1);
$negeri = $purifier->purify($negeri1);
$peserta = $purifier->purify($peserta1);
if($_SESSION['ekor']) {
$bil = $_SESSION['ekor']; //capturing bilangan ekor into a var
switch ($_SESSION['negara']){
case 'Malaysia':
$jumlahHarga = $bil*(650*7);
break;
case 'ASEAN':
$jumlahHarga = $bil*(450*7);
break;
case 'Timur Tengah':
$jumlahHarga = $bil*(1300*7);
break;
case 'Afrika':
$jumlahHarga = $bil*(350*7);
break;
default:
}
} else {
$bil = $_SESSION['bahagian']; //capturing bilangan bahagian into a var
switch ($_SESSION['negara']){
case 'Malaysia':
$jumlahHarga = $bil*650;
break;
case 'ASEAN':
$jumlahHarga = $bil*450;
break;
case 'Timur Tengah':
$jumlahHarga = $bil*1300;
break;
case 'Afrika':
$jumlahHarga = $bil*350;
break;
default:
}
}
$post = array(
'post_title' => wp_strip_all_tags( $nama ),
'post_status' => 'publish',
'post_type' => 'qurban',
'meta_input' => array(
'pilihan_negara' => $negara,
'pilihan_lembu' => $binatang,
'bilangan_ekorbahagian' => $ekorBahagian,
'jumlah_bayaran' => $jumlahHarga,
'nama_penuh' => $nama,
'nombor_kad_pengenalan' => $kp,
'nombor_telefon' => $telefon,
'emel' => $emel,
'alamat_rumah_1' => $alamat1,
'alamat_rumah_2' => $alamat2,
'poskod' => $poskod,
'bandar' => $bandar,
'negeri' => $negeri,
'senarai_nama_peserta' => $peserta,
'bank' => $bank,
'kempen' => $kempen
)
);
$post_id = wp_insert_post($post);
get_header();
?>
<?php
get_footer();
?>
Below is the code that uses save_post to redirect the user to external payment site:
?php
require_once "Mobile_Detect.php";
////////////////////////////
//// PAYMENT REDIRECTION FUNCTION
////////////////////////////
function my_save_post_iq( $post_id ) {
debug_to_console( "save post function fired" );
$billplzApi = get_field('iq_secret_key', 'option');
$billplzId = get_field('iq_collection_id', 'option');
// bail early if not a donation post
if( get_post_type($post_id) !== 'qurban' ) {
return;
}
// bail early if editing in admin
if( is_admin() ) {
return;
}
$post = get_post( $post_id);
$jumlah_bayaran_iq = get_field('jumlah_bayaran', $post_id);
//check & update user device type
$detect = new Mobile_Detect;
if($detect->isMobile()){
update_field('devices', 'mobile' , $post);
} else {
update_field('devices', 'desktop', $post);
}
$name = get_field('nama_penuh', $post);
$email = get_field('emel', $post);
$mobile = get_field('nombor_telefon', $post);
$bank = get_field('bank', $post);
$billplz_data = array(
'amount' => $jumlah_bayaran_iq * 100,
'name' => $name,
'mobile' => $mobile,
'email' => $email,
'collection_id' => $billplzId,
'deliver' => false,
'reference_1_label' => 'Bank Code',
'reference_1' => $bank,
'reference_2_label' => 'Post ID',
'reference_2' => $post_id,
'description' => 'xxx',
'redirect_url' => home_url('qurbanv2/paymentredirectv2'),
'callback_url' => home_url('paymentcallback')
);
$process = curl_init('https://www.billplz.com/api/v3/bills/');
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $billplzApi . ":");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($billplz_data));
$return = curl_exec($process);
curl_close($process);
$arr = json_decode($return, true);
$billplz_url = $arr['url'];
$billplz_id = $arr['id'];
//update payment status
update_field('billplz_iq', $billplz_id , $post);
//$hzpost_name = array(
// 'ID' = $post,
// 'post_name' = $billplz_url
//);
//
//wp_update_post($hzpost_name);
header('Location: '. $billplz_url . '?auto_submit=true');
exit();
}
add_action('save_post', 'my_save_post_iq', 10, 1);
I am new to Wordpress development, so please help.
Found the bug. It's got to do with how the payment gateway treats mobile number. I've added a line to add '+' in front of the numbers, and the duplication stops.
if($telefon1) {
$mobile = preg_replace("/[^0-9]/", "", $telefon1);
$custTel = $mobile;
$custTel2 = substr($mobile, 0, 1);
if ($custTel2 == '+') {
$custTel3 = substr($mobile, 1, 1);
if ($custTel3 != '6') {
$custTel = "+6" . $mobile;
}
} elseif ($custTel2 == '6') {
$custTel = "+" . $mobile; //added this line.
} else {
if ($custTel != '') {
$custTel = "+6" . $mobile;
}
}
}
I am working on Opencart API (opencart v2.3) and I follow this link for documentation (Opencart ) . But there is no data on opencart APIs and how to use it, So I follow steps from other websites and using that code I receive this message when call login api, Success: API session successfully started!
But whenever I use another API for add product in cart or view cart or add order, I receive permission issue. I debug code and found that it required session app_id and when I check, it store only token, not app_id
I use following code which I found by googling.
common.php
<?php
function do_curl_request($url, $params=array()) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'E:\practice\oc2.3\tmp\apicookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'E:\practice\oc2.3\tmp\apicookie.txt');
$params_string = '';
if (is_array($params) && count($params)) {
foreach($params as $key=>$value) {
$params_string .= $key.'='.$value.'&';
}
rtrim($params_string, '&');
curl_setopt($ch,CURLOPT_POST, count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string);
}
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
login.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/login';
$fields = array(
'key' => 'FpafURRNAHgVcaUXZozahVdEOV7mtp1Q0ejvAMAIAfiZyVqIptqZ2uV9eQvT3PytlzELULH1vQwLKikFGBOm3yky1rTuFO6sEi0eBkH1y6WgpaNWIsB0ZMiRCCbGCBZZak2uR1CBg0TpOzcbevXWGStvoUsaKgl0B3OKRoHk6mRj7e6S63HJQzQksbbz0JfCuZsY9cvhY4ArQPzNf3XfrdgE3nTG5hYQCXaKPVqtS3R2Vqr4sazwjgXYajy7h6Dv',
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
if (isset($data->token)) {
$token = $data->token;
}
var_dump($data);
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
customer api
public function index() {
$this->load->language('api/customer');
// Delete past customer in case there is an error
unset($this->session->data['customer']);
$json = array();
if (!isset($this->session->data['api_id'])) {
$json['error']['warning'] = $this->language->get('error_permission');
} else {
// Add keys for missing post vars
$keys = array(
'customer_id',
'customer_group_id',
'firstname',
'lastname',
'email',
'telephone',
'fax'
);
foreach ($keys as $key) {
if (!isset($this->request->post[$key])) {
$this->request->post[$key] = '';
}
}
// Customer
if ($this->request->post['customer_id']) {
$this->load->model('account/customer');
$customer_info = $this->model_account_customer->getCustomer($this->request->post['customer_id']);
if (!$customer_info || !$this->customer->login($customer_info['email'], '', true)) {
$json['error']['warning'] = $this->language->get('error_customer');
}
}
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$json['error']['firstname'] = $this->language->get('error_firstname');
}
if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
$json['error']['lastname'] = $this->language->get('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL))) {
$json['error']['email'] = $this->language->get('error_email');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = $this->language->get('error_telephone');
}
// Customer Group
if (is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
} elseif (($custom_field['location'] == 'account') && ($custom_field['type'] == 'text') && !empty($custom_field['validation']) && !filter_var($this->request->post['custom_field'][$custom_field['custom_field_id']], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $custom_field['validation'])))) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if (!$json) {
$this->session->data['customer'] = array(
'customer_id' => $this->request->post['customer_id'],
'customer_group_id' => $customer_group_id,
'firstname' => $this->request->post['firstname'],
'lastname' => $this->request->post['lastname'],
'email' => $this->request->post['email'],
'telephone' => $this->request->post['telephone'],
'fax' => $this->request->post['fax'],
'custom_field' => isset($this->request->post['custom_field']) ? $this->request->post['custom_field'] : array()
);
$json['success'] = $this->language->get('text_success');
}
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Put the token right after your request URL will make it works.
Assume token returned by api/login is KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo.
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct&token=KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
Make sure server's IP address is added to the allowed IP addresses.
To check that, go to System → Users → API then edit the Default one.
Once there, click on IP Address tab and insert the server IP address.
To get the server IP address, you can use the following command line:
$ curl ipinfo.io/ip
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 .
Hi i am trying to get Goto meeting OAuth access token via php curl. but it returns nothing when i make a call. please guide me how i can get it, Code is given below.
$api_key = "123456";
$redirect_url = urlencode("URL");
$webinar_url = "https://api.citrixonline.com/oauth/authorize?client_id=".$api_key."&redirect_uri=".$redirect_url;
function getWebinarData($link)
{
$headers = array(
"HTTP/1.1",
"Content-type: application/json",
"Accept: application/json"
);
$curl = curl_init($link);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //2
$response = curl_exec($curl);
echo "<pre>DATA: ";print_r($response);echo "</pre>";
curl_close($curl);
return $response;
}
/**
* goto api
* Author: Ahad Ali
* Date: valentines day 2013
* Classes Curl, OAuth, GotoTraining
*/
define ("API_KEY", "");
define ("REDIRECT_URL","");
define ("AUTH_AUTOLOGIN_URL","https://developer.citrixonline.com/oauth/g2t/authorize.php");
define ("AUTH_EXCHANGE_URL", "https://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code=<CODE>&client_id=" . API_KEY);
define ("MANAGE_TRAINING_URL","https://api.citrixonline.com/G2T/rest/organizers/<ORGANIZERKEY>/trainings");
class Curl
{
public $result;
public function __construct()
{
}
public function request($url, $data="", $method="get", $headers="")
{
$ch = curl_init();
// this is autologiM USING CURL POST
// avoiding the redirect to gotos site where it asks for email and password and redirects back to the URL with a code
curl_setopt($ch, CURLOPT_URL, $url);
if($method == "post")
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, true);
}
if($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->result = (string) curl_exec($ch);
curl_close($ch);
return $this->result;
}
public function __destruct()
{
}
}
class OAuth
{
public $autologin_url;
public $exchange_url;
public $code;
public $auth_result;
//https://api.citrixonline.com/oauth/authorize?client_id= used this URL to get all the field names
public $login_data = array(
'emailAddress' => '',
'password' => '',
'client_id' => '',
'access_type'=> 'G2T',
'app_name' => '',
'redirect_uri' => '',
'submitted' => 'form_submitted',
);
public function __construct($autologin_url = AUTH_AUTOLOGIN_URL, $exchange_url = AUTH_EXCHANGE_URL, $apikey=API_KEY)
{
$this->autologin_url = $autologin_url;
$this->exchange_url = $exchange_url;
$this->login_data['client_id'] = $apikey;
}
public function authorize()
{
$this->getCode();
$this->exchangeCodeForAccessToken();
}
public function getCode()
{
$curl = new Curl();
$result = $curl->request($this->autologin_url, $this->login_data, "post");
$arr = explode("\n", $result);
foreach($arr as $k=>$v)
{
if(strstr($v,"Location: http:"))
$return_url = $v;
}
$query = trim(parse_url($return_url, PHP_URL_QUERY));// adds one unnecessary _ (underscore) at the end of the query string
$this->code = substr($query, 5, (strlen($query) - 6));//starting from 5 get me ...number of chars
}
function exchangeCodeForAccessToken()
{
$this->exchange_url = str_replace("<CODE>", $this->code, $this->exchange_url);
$curl = new Curl();
$result = $curl->request($this->exchange_url);
$this->auth_result = json_decode($result);
}
public function __destruct()
{
}
}
class GotoTraining extends OAuth
{
public $manage_training_url;
public $training_result;
public $error_list = array("AuthFailure", "AccessDenied", "ExpiredToken", "InternalError", "InvalidRequest", "InvalidMethod", "MissingToken", "NoSuchTraining", "InvalidToken");
public function __construct($url = MANAGE_TRAINING_URL)
{
$this->manage_training_url = $url;
parent::__construct();
}
/**
*Arguement List for goto CreateTraining service
* [name] => Representational State Transfer 101
[description] => The REST-ful way to APIs.
[timeZone] => America/Los_Angeles
[times] => Array
(
[0] => stdClass Object
(
[startDate] => 2011-09-08T18:25:00Z
[endDate] => 2011-09-08T19:25:00Z
)
[1] => stdClass Object
(
[startDate] => 2011-09-09T18:25:00Z
[endDate] => 2011-09-09T19:25:00Z
)
)
[registrationSettings] => stdClass Object
(
[disableWebRegistration] => false
[disableConfirmationEmail] => false
)
[organizers] => Array
(
[0] => 6512477
[1] => 38712
[2] => 9876466
)
*/
public function createTraining($name, $desc, $times)
{
$registrationSettings["disableWebRegistration"] = "false";
$registrationSettings["disableConfirmationEmail"] = "false";
$json["name"] = $name;
$json["description"] = $desc;
$json["timeZone"] = "Australia/Sydney";
$json["times"] = $times;//array for startDate, endDate
$json["registrationSettings"] = $registrationSettings;
$json["organizers"][0] = $this->auth_result->organizer_key;
$this->manage_training_url = str_replace("<ORGANIZERKEY>", $this->auth_result->organizer_key, $this->manage_training_url);
$json = json_encode($json);
//$post_data[] = "Authorization:OAuth oauth_token=" . $this->auth_result->access_token;
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token=' . $this->auth_result->access_token
);
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$curl = new Curl();
$this->training_result = $curl->request($this->manage_training_url, $json, "post", $headers);
$arr = explode("\n", $this->training_result);
$this->webCode = trim($arr[count($arr)-1], '"');
$this->checkError();
return $this->webCode;
}
public function checkError()
{
foreach($this->error_list as $val)
{
if(strstr($this->training_result, $val))
$this->webCode = $val;
}
return 0;
}
}