I wrote a script that communicates with a popular game, called kahoot. It logs in and answer's each question, and then echo's when it is finished. Here is it working on the command line. However, when I add this functionality to my website, when I run it it gives me a 504 gateway timeout, even though before the timeout it should have produced some output and echoed it to the page.
Here is the website code:
Full execution code:
<html>
<head>
<title>Kahoot bot</title>
</head>
<body>
<?php
$username = 'kahootbot28#gmail.com';
$password = 'botkahoot28';
$loginUrl = 'https://create.kahoot.it/rest/authenticate';
$kahootId = $_GET['quizid'];
$type = $_GET['what'];
if ($type == "bot") {
$call = "~/www/reteps.tk/go/kahoot-auto " . $_GET['gamepin'] . " " . $_GET['username'] . " ";
echo($call);
}
$pageUrl = 'https://create.kahoot.it/rest/kahoots/' . $kahootId;
$loginheader = array();
$loginheader[] = 'content-type: application/json';
$loginpost = new stdClass();
$loginpost->username = $username;
$loginpost->password = $password;
$loginpost->grant_type = "password";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($loginpost));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$loginheader);
$store = curl_exec($ch);
curl_close($ch);
$token = json_decode($store,true)["access_token"];
//get questions
$quizheader = array();
$quizheader[] = 'authorization: ' . $token;
$options = array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: ".$token."\r\n"
)
);
$pairs = array(
0 => "red",
1 => "blue",
2 => "yellow",
3 => "green",
);
$context = stream_context_create($options);
$raw_result = file_get_contents($pageUrl, false, $context);
$result = json_decode($raw_result,true)["questions"];
echo("<a href='kahoot_bot'>back</a><br>");
foreach($result as $value) {
if ($type == "text") {
echo($value['question']." ");
}
$choices = $value['choices'];
for($i=0;$i<count($choices);$i++) {
if ($choices[$i]['correct'] == true) {
if ($type == "text") {
echo($choices[$i]['answer']."<br>");
} elseif ($type == "bot") {
$call .= $i;
} else {
echo($pairs[$i].", ");
}
break 1;
}
}
}
if ($type == "bot") {
$old_result = "";
$handle = popen($call . " 2>&1", "r");
$result = fread($handle, 2096);
echo($result);
while ((strpos($result, "end") !== false) != true) {
$result = fread($handle, 2096);
sleep(1);
if ($result != $old_result) {
echo($result);
$old_result = $result;
}
}
pclose($handle);
}
?>
</body>
</html>
Related
I have the following code which basically runs a bunch of curl request in a for loop
This is a background system job.. however when this code is running.. i can't access the website, website is just loading until this task/function is finished
public function endcount() {
$order_list = $this->order_model->get_rows([
'where' => [
"status IN ('Processing', 'In Progress') AND service_id = 1"
],
'order_by' => 'quantity ASC',
'limit' => '200'
]);
foreach ($order_list as $key => $value) {
$start_count = $value['start_count'];
//service id = 1 is for followers
if ($value['service_id'] == '1' || $value['service_id'] == '3' || $value['service_id'] == '5') {
$end_count = 0;
try {
$username = $value['target'];
$proxy = '139.99.54.49:10163';
$proxyauth = 'username:password';
$url = 'https://www.instagram.com/'. $username .'/?__a=1&__d=dis';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy); // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth); // Use if proxy have username and password
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json') );
$data = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
var_dump($error_msg);
}
$json_data = json_decode($data, true);
if ($json_data && array_key_exists('graphql', $json_data)) {
$end_count = $json_data['graphql']['user']['edge_followed_by']['count'];
} else {
var_dump($username . ' data ga bisa');
$end_count = 0;
}
curl_close($ch);
} catch(Exception $e) {
var_dump($e->getMessage());
$end_count = 0;
}
if ($end_count == -666) {
$end_count = $start_count + 5;
}
$total_followers = $start_count + $value['quantity'];
$remains = $total_followers - $end_count;
if ($remains <= 10) {
$status = 'Success';
} else {
$status = 'Partial';
}
var_dump('end count of ' . $value['target'] . ' ' . $end_count . ' WITH REMAINS: ' . $remains);
if ($status == 'Success') {
$update_order = [
'remains' => $remains,
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
];
$update_order = $this->order_model->update($update_order, ['id' => $value['id']]);
if ($update_order == true) {
print('ID '.$value['id'].' => ['.$status.'] - [FINAL COUNT : '.$end_count.'] - [REMAINS : '.$remains.'] - [TARGET COUNT : '.$total_followers.']<br>');
} else {
print('Error..');
}
}
//var_dump($value['target']);
} else if ($value['service_id'] == '2') {
//service id = 2 is for likers
}
}
}
is there any way i can optimize this code so it is not blocking access to the site while running ?
try adding sleep(5); funtion to your code so server isn't overloaded with requests..
your code should look something like this :
foreach ($order_list as $key => $value) {
sleep(5);
$start_count = $value['start_count'];
API code executes successfully without giving any errors however the voucher am trying to create doesn't get created in datto below is the response am getting ,the highlighted text is the voucher am trying to create what might be the cause of this because the input body am sending is as indicate in their documentation https://github.com/cloudtrax/docs/blob/master/api/vouchers.md#actions
this is the response and the request code any help will be highly appreciated
<?php
$key = 'xxxxxxxx';
$secret='xxxxxxx';
class Method
{
const GET = 0;
const POST = 1;
const PUT = 2;
const DELETE = 3;
public static function nameForEnumValue($value) {
switch($value) {
case 0: return "GET";
case 1: return "POST";
case 2: return "PUT";
case 3: return "DELETE";
}
}
};
function print_debug_info($method, $endpoint, $headers) {
print( "\n" );
print( "Method: " . Method::nameForEnumValue($method) . "\n");
print( "Endpoint: " . $endpoint . "\n" );
print_r($headers);
}
function build_headers($auth, $sign) {
$headers = array();
$headers[] = "Authorization: " . $auth;
$headers[] = "Signature: " . $sign;
$headers[] = "Content-Type: application/json";
$headers[] = "OpenMesh-API-Version: 1";
return $headers;
}
function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
// get a curl handle then go to town on it
$ch = curl_init($api_server . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($method == Method::DELETE)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
elseif ($method == Method::PUT) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
}
else if ($method == Method::POST) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
}
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch));
}
else
echo "RESULT: \n" . $result . "\n";
echo "RESULT: \n" . $json . "\n";
}
catch(Exception $e) {
trigger_error( sprintf('Curl failed with error #%d: "%s"',
$e->getCode(), $e->getMessage()), E_USER_ERROR);
}
}
function call_api_server($method, $endpoint, $data) {
global $key, $secret;
$time = time();
$nonce = rand();
if ($method == Method::POST)
assert( '$data != NULL /* #### POST requires $data #### */');
elseif ($method == Method::GET || $method == Method::DELETE)
assert( '$data == NULL /* ### GET and DELETE take no $data ### */');
$path = $endpoint;
// if present, concatenate encoded json to $endpoint for Signature:
if ($data != NULL) {
$json = json_encode($data);
$path .= $json;
}
$authorization = "key=" . $key . ",timestamp=" . $time . ",nonce=" . $nonce;
$signature = hash_hmac('sha256', $authorization . $path . $body, $secret);
$headers = build_headers($authorization, $signature);
print_debug_info($method, $endpoint, $headers);
invoke_curl($method, $endpoint, $headers, $json);
}
$uniqueKey=strtoupper(substr(sha1(microtime()), rand(0, 6), 6));
$uniqueKey = implode("-", str_split($uniqueKey, 6));
echo($uniqueKey);
$data =array('desired_vouchers',[
'code'=>$uniqueKey,
//'code'=>0103,
'duration'=> 24,
'max_users'=> 4,
'up_limit'=> 20,
'down_limit'=> 40,
'comment'=> "Courtesy of API Test",
'purge_days'=> 5
] );
call_api_server(Method::POST, "/voucher/network/xxxxx",$data);
//call_api_server(Method::GET, "/dna-api/v1/login",Null);
//call_api_server(Method::GET, "/dna-api/doc#get--dna-api-v1-routers-{mac}",Null);
//call_api_server(Method::GET, "/dna-api/v1/users/xxxx/overview",Null);
?>
I am just trying to include a file in CakePhp but nothing helps me. I have placed that file inside the vendor folder.
Here's the path of that file:
vendor/paytm/PaytmChecksum.php
I tried to import it in my controller like below:
require_once(ROOT . DS . 'vendor' . DS . 'paytm' . DS . 'PaytmChecksum.php');
But it didn't work. So, I tried another method by including below two lines at top of the controller.
use Cake\Filesystem\File;
use Cake\Filesystem\Folder;
Then did this in the controller action:
$dir = new Folder(ROOT . DS . 'vendor' . DS . 'paytm' . DS . 'PaytmChecksum.php');
But nothing is working for me. I tried to place the folder in my current directory and then tried by including the file with require_once but that also not worked.
Can anyone please help with the same?
I also Faced a problem in paytm checksum.
So i had created a files in Component.
......\src\Controller\Component\PaytmChecksumComponent.php
And the code is.
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
define('PAYTM_ENVIRONMENT', 'TEST'); // PROD
define('PAYTM_MERCHANT_KEY', '*********************'); //Change this constant's value with Merchant key received from Paytm.
define('PAYTM_MERCHANT_MID', '*************'); //Change this constant's value with MID (Merchant ID) received from Paytm.
define('PAYTM_MERCHANT_WEBSITE', 'WEBSTAGING'); //Change this constant's value with Website name received from Paytm.
define('PAYTM_REFUND_URL', '');
class PaytmChecksumComponent extends Component
{
public $PAYTM_STATUS_QUERY_NEW_URL = 'https://securegw-stage.paytm.in/merchant-status/getTxnStatus';
public $PAYTM_TXN_URL = 'https://securegw-stage.paytm.in/theia/processTransaction';
public function initialize(array $config): void
{
if (PAYTM_ENVIRONMENT == 'PROD') {
$this->PAYTM_STATUS_QUERY_NEW_URL = 'https://securegw.paytm.in/merchant-status/getTxnStatus';
$this->PAYTM_TXN_URL = 'https://securegw.paytm.in/theia/processTransaction';
}
define('PAYTM_STATUS_QUERY_URL', $this->PAYTM_STATUS_QUERY_NEW_URL);
define('PAYTM_STATUS_QUERY_NEW_URL', $this->PAYTM_STATUS_QUERY_NEW_URL);
define('PAYTM_TXN_URL', $this->PAYTM_TXN_URL);
}
function encrypt_e($input, $ky)
{
$key = html_entity_decode($ky);
$iv = "####&&&&####$$$$";
$data = openssl_encrypt($input, "AES-128-CBC", $key, 0, $iv);
return $data;
}
function decrypt_e($crypt, $ky)
{
$key = html_entity_decode($ky);
$iv = "####&&&&####$$$$";
$data = openssl_decrypt($crypt, "AES-128-CBC", $key, 0, $iv);
return $data;
}
function generateSalt_e($length)
{
$random = "";
srand((float) microtime() * 1000000);
$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
$data .= "0FGH45OP89";
for ($i = 0; $i < $length; $i++) {
$random .= substr($data, (rand() % (strlen($data))), 1);
}
return $random;
}
function checkString_e($value)
{
if ($value == 'null')
$value = '';
return $value;
}
function getChecksumFromArray($arrayList, $key, $sort = 1)
{
if ($sort != 0) {
ksort($arrayList);
}
$str = $this->getArray2Str($arrayList);
$salt = $this->generateSalt_e(4);
$finalString = $str . "|" . $salt;
$hash = hash("sha256", $finalString);
$hashString = $hash . $salt;
$checksum = $this->encrypt_e($hashString, $key);
return $checksum;
}
function getChecksumFromString($str, $key)
{
$salt = $this->generateSalt_e(4);
$finalString = $str . "|" . $salt;
$hash = hash("sha256", $finalString);
$hashString = $hash . $salt;
$checksum = $this->encrypt_e($hashString, $key);
return $checksum;
}
function verifychecksum_e($arrayList, $key, $checksumvalue)
{
$arrayList = $this->removeCheckSumParam($arrayList);
ksort($arrayList);
$str = $this->getArray2StrForVerify($arrayList);
$paytm_hash = $this->decrypt_e($checksumvalue, $key);
$salt = substr($paytm_hash, -4);
$finalString = $str . "|" . $salt;
$website_hash = hash("sha256", $finalString);
$website_hash .= $salt;
$validFlag = "FALSE";
if ($website_hash == $paytm_hash) {
$validFlag = "TRUE";
} else {
$validFlag = "FALSE";
}
return $validFlag;
}
function verifychecksum_eFromStr($str, $key, $checksumvalue)
{
$paytm_hash = $this->decrypt_e($checksumvalue, $key);
$salt = substr($paytm_hash, -4);
$finalString = $str . "|" . $salt;
$website_hash = hash("sha256", $finalString);
$website_hash .= $salt;
$validFlag = "FALSE";
if ($website_hash == $paytm_hash) {
$validFlag = "TRUE";
} else {
$validFlag = "FALSE";
}
return $validFlag;
}
function getArray2Str($arrayList)
{
$findme = 'REFUND';
$findmepipe = '|';
$paramStr = "";
$flag = 1;
foreach ($arrayList as $key => $value) {
$pos = strpos($value, $findme);
$pospipe = strpos($value, $findmepipe);
if ($pos !== false || $pospipe !== false) {
continue;
}
if ($flag) {
$paramStr .= $this->checkString_e($value);
$flag = 0;
} else {
$paramStr .= "|" . $this->checkString_e($value);
}
}
return $paramStr;
}
function getArray2StrForVerify($arrayList)
{
$paramStr = "";
$flag = 1;
foreach ($arrayList as $key => $value) {
if ($flag) {
$paramStr .= $this->checkString_e($value);
$flag = 0;
} else {
$paramStr .= "|" . $this->checkString_e($value);
}
}
return $paramStr;
}
function redirect2PG($paramList, $key)
{
$hashString = $this->getchecksumFromArray($paramList, $key);
$checksum = $this->encrypt_e($hashString, $key);
}
function removeCheckSumParam($arrayList)
{
if (isset($arrayList["CHECKSUMHASH"])) {
unset($arrayList["CHECKSUMHASH"]);
}
return $arrayList;
}
function getTxnStatus($requestParamList)
{
return $this->callAPI(PAYTM_STATUS_QUERY_URL, $requestParamList);
}
function getTxnStatusNew($requestParamList)
{
return $this->callNewAPI(PAYTM_STATUS_QUERY_NEW_URL, $requestParamList);
}
function initiateTxnRefund($requestParamList)
{
$CHECKSUM = $this->getRefundChecksumFromArray($requestParamList, PAYTM_MERCHANT_KEY, 0);
$requestParamList["CHECKSUM"] = $CHECKSUM;
return $this->callAPI(PAYTM_REFUND_URL, $requestParamList);
}
function callAPI($apiURL, $requestParamList)
{
$jsonResponse = "";
$responseParamList = array();
$JsonData = json_encode($requestParamList);
$postData = 'JsonData=' . urlencode($JsonData);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
));
$jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse, true);
return $responseParamList;
}
function callNewAPI($apiURL, $requestParamList)
{
$jsonResponse = "";
$responseParamList = array();
$JsonData = json_encode($requestParamList);
$postData = 'JsonData=' . urlencode($JsonData);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
));
$jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse, true);
return $responseParamList;
}
function getRefundChecksumFromArray($arrayList, $key, $sort = 1)
{
if ($sort != 0) {
ksort($arrayList);
}
$str = $this->getRefundArray2Str($arrayList);
$salt = $this->generateSalt_e(4);
$finalString = $str . "|" . $salt;
$hash = hash("sha256", $finalString);
$hashString = $hash . $salt;
$checksum = $this->encrypt_e($hashString, $key);
return $checksum;
}
function getRefundArray2Str($arrayList)
{
$findmepipe = '|';
$paramStr = "";
$flag = 1;
foreach ($arrayList as $key => $value) {
$pospipe = strpos($value, $findmepipe);
if ($pospipe !== false) {
continue;
}
if ($flag) {
$paramStr .= $this->checkString_e($value);
$flag = 0;
} else {
$paramStr .= "|" . $this->checkString_e($value);
}
}
return $paramStr;
}
function callRefundAPI($refundApiURL, $requestParamList)
{
$jsonResponse = "";
$responseParamList = array();
$JsonData = json_encode($requestParamList);
$postData = 'JsonData=' . urlencode($JsonData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $refundApiURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse, true);
return $responseParamList;
}
}
To load component in controller
public function initialize(): void
{
parent::initialize();
//....................................
$this->loadComponent('PaytmChecksum');
//........................
}
// .............
function payment(){
//...$paytmParams = array(
"MID" => "*****",
"WEBSITE" => "DEFAULT",
"INDUSTRY_TYPE_ID" => "1",
"CHANNEL_ID" => "WEB",
"ORDER_ID" => "*************",
"CUST_ID" => "*****",
"MOBILE_NO" => "*****",
"EMAIL" => "*******",
"TXN_AMOUNT" => (float)100,
/* on completion of transaction, we will send you the response on this URL */
"CALLBACK_URL" => "https://******",
);
$checksum = $this->PaytmChecksum->getChecksumFromArray($paytmParams, "_#C%&uL");
pr($checksum);
}
ok, i think i just fucked up everything because of my brain failure.
I followed Google's example of "phpsqlsearch_v3":
imported the sql file
change the query from showing miles to kilometers
testing by using this:
phpsqlsearch_genxml.php?lat=37.315903&lng=-121.977928&radius=40
everything works as charm...
going into website to get latlong, adding and changing some data in db
now, I'm changing the phpsqlsearch_genxml.php to....
phpsqlsearch_genxml.php?lat=59.627847&lng=17.838589&radius=40
...nothing... however, if i change radius to 8000 it will work but the distance for places around input will be like 5665.231121242624km but if i flip the input because I'm on the right side of the earth blink blink to
phpsqlsearch_genxml.php?lat=17.838589&lng=59.627847&radius=100
it will give me a more accurate result, however... the result should closer and around 1-2km...
suggestion what to do now?
function getAddress($lat, $lng) {
$use_curl = false;
if ($use_curl) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array (
"Content-type: application/binary"
));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
if (curl_errno($ch))
return -1;
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$str = substr($response, $header_size);
curl_close($ch);
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta", $meta);
}
} else {
$str = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta"=>$meta);
}
}
}
I use the code in php to connect to the api and display the results...
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require("OAuth.php");
$cc_key = "cc_key"; //cc_key
$cc_secret = "cc_secret"; // cc_secret key
$url = "https://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = htmlspecialchars($_GET["q"]);
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
//echo $url . "<br>"; test uri
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['title'].'</a></br>';
echo ''.$result['abstract'].'</br>';
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['dispurl'].'</a></br>';
}
?>
then write mini "pagination"
//$start = "&start=" . "0";
$start_val = $_GET['start'];
if ($start_val == "") $start_val = 0;
$start = "&start=" . $start_val;
// Some more code...
$count_val = 10;
$count = "&count=" . $count_val;
if ($query != "") {
if ($start_val != 0) {
echo 'previous';
echo '<span> | </span>';
}
echo 'next';
}
but "pagination" does not work =(
I can not understand why does not work
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Please HELP me
Thanks.