<?php
require 'db.php';
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
//catstagram start
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'nypgraduation2014';
$client_id = "e4c623cb050444eeb7072e1a577da5b3";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
while (isset($url) && $url != '')
{
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
foreach($results['data'] as $item)
{
$image_link = $item['images']['standard_resolution']['url'];
//$path_parts = pathinfo($image_link);
// save the file name in variable
//$image = ($path_parts['basename']);
//copy($image_link,"photos/" .$image);
mysql_query("INSERT INTO fypj131127cdb.instagramphoto(url) values('$image_link')");
// copy the file to you folder
}
$url = $result['pagination']['next_url'];
$image = "SELECT * FROM fypj131127cdb.instagramphoto ORDER BY ImageID ASC;";
$img_result=mysql_query($image);
$imageIndex = 0;
?>
Hi guys, I have trouble displaying all the instagram images with the hashtag #nypgraduation2014 using pagination. By using this codes, I don't know why I cannot display all the photos. As I am new to php and api, therefore I hope you guys can help me. Thanks!
Related
I understand how classes are useful, but don't know what's the proper way to create ones that have prepared statements. I've started making a class and I want a method called isOnline that returns if the url is online.
// This is the code I'm trying to make a class.
global $db;
$stmt = $db->prepare("SELECT url FROM urls WHERE rel=? ORDER BY url");
$stmt->bind_param("i", $_SESSION['admin_id']);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php
while($row = $result->fetch_array())
{
$url = $row['url'];
$site = strtolower($url);
// check if is online
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
if(!$statushttp == 0){
}else{
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'http://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
}
echo "$url with $statushttp <br>";
// email person here.
}
$stmt->free_result();
Not sure what you are doing to determine if a site is online or not but as far as creating a class to handle this. You should use something like this. If you can explain what you are doing to determine if a site is up or not I can update the class.
class SomeClassNameHere{
//this is the constructor of the class. This is ran when you create it
public SomeClassNameHere(){
}
//this is a public function that you can call
public function isOnline(){
//this is the first step to breaking up this into smaller peaces
//I moved your section of code that gets the urls from the database
//into a function that returns the rows from the database below.
$rows = getUrls();
while($row = $result->fetch_array()){
$site = strtolower($row['url']);
}
// check if is online
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
if(!$statushttp == 0){
}else{
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'http://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
}
//I wouldn't echo out the results here,
//I would have this function return a true or false and do the display
//somewhere else
//like this
if(statushttp == whateverIsTrue){ //remember to edit this
return true;
}else{
return false;
}
}
//this has the possibility to return more than one row. You will need to
//change your function to handle this.
public function getUrls(){
$stmt = $db->prepare("SELECT url FROM urls WHERE rel=? ORDER BY url");
$stmt->bind_param("i", $_SESSION['admin_id']);
$stmt->execute();
return $stmt->get_result();
}
}
To call this class you would want to do something like this.
//this is creating an instance of the class
$foo= new SomeClassNameHere();
//this will call the isOnline function of that class and return true or false
$siteOnline = $foo->isOnline();
if($siteOnline){
echo "Yeah!";
}else{
echo "Sad:-(";
}
So problem is I am using inline keyboard in my bot. And when I am trying to push this keyboard it gives me 3-5 callbacks. I don't know where is my mistake.
EDIT
I don't know why but it causes this error when i working with mysqli->fetch_assoc();
There is not full code just peace where I use inline keyboard
if ($callback_data!=Null){
checkJSON(3124,$order_id);
$message_id = $update['callback_query']['message']['message_id'];
$callback_data = json_decode($callback_data,true);
checkJSON(3125,$callback_data["order_id"]);
$order_id = $callback_data["order_id"];
checkJSON(3126,$order_id);
$rs = $mysqli->query("SELECT manager_id FROM orders WHERE id=".$order_id);
$row = $rs->fetch_assoc();
$manager = $row['manager_id'];
if ($manager!=Null){
$rs = $mysqli->query("SELECT telegram_id FROM managers WHERE id=".$manager);
$row = $rs->fetch_assoc();
$manager_telegram_id = $row['telegram_id'];
if ($chatID==$manager_telegram_id){
$callback_data = json_decode($callback_data);
$order_id = $callback_data["order_id"];
$status = $callback_data["status"];
checkJSON(1231234,$callback_data);
if($status == '3'){
editMessage($chatID,$message_id,"Заказ N".$order_id." подтвержден");
}
else{
editMessage($chatID,$message_id,"Заказ N".$order_id." отклонен");
}
$mysqli->query("UPDATE orders SET status=".$status." WHERE id=".$order_id);
}
sendMessage($chatID,$update['callback_query']['message']['message_id']);
editMessage($chatID,$message_id,
"Данный заказ уже в оброботке");
}
else{
$get_manager_query = $mysqli->query("SELECT id FROM managers WHERE telegram_id=".$chatID);
$row = $get_manager_query->fetch_assoc();
$manager = $row['id'];
$data1 = json_encode(array("order_id"=>$order_id,"status"=>3));
$data2 = json_encode(array("order_id"=>$order_id,"status"=>4));
$inline_button1 = array("text"=>"Принять","callback_data"=>$data1);
$inline_button2 = array("text"=>"Отказать","callback_data"=>$data2);
$inline_keyboard = [[$inline_button1,$inline_button2]];
$keyboard=json_encode(array("inline_keyboard"=>$inline_keyboard));
editMessage($chatID,$message_id,
"Вы приняли данный заказ",$keyboard);
$rs = $mysqli->query("UPDATE orders SET status=1, manager_id=".$manager." WHERE id=".$order_id);
}
}
function sendMessage($chatID,$text){
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($text);
file_get_contents($sendto);
}
function editMessage($chatId, $messageId, $message,$replyMarkup=Null) {
$url = API_URL."editMessageText?chat_id=".$chatId."&message_id=".$messageId.
"&text=".urlencode($message)."&reply_markup=".$replyMarkup;
file_get_contents($url);
}
It's Not your mistake!
Telegram Server is send callbacks for every changes in inline query.
You can setting that to off in BotFatherwith /setinlinefeedback command.
For more information visit this
Set your data by some separator After, get that data by $update['callback_query']['data'] and split by seted separator.
$botToken = "(your token)";
$website = "https://(site_url)/bot" . $botToken;
$order_id = '44423'; //my additional data
$keyboard = ["inline_keyboard" => [
[
[
"text" => "Доставлено",
"callback_data" => "delivered_".$order_id, // set few data by '_' separator Like ("delivered_443423_phone12345667_...)
],
[
"text" => "Затримуюсь",
"callback_data" => "delaying_".$order_id,
]
],
]
];
$params = [
'chat_id' => $chat_id,
'text' => $msg,
'parse_mode' => 'html',
'reply_markup' => json_encode($keyboard),
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
Update processing. For get update you need set webhook on file where bot is placed. https://api.telegram.org/bot(your token)/setWebhook?url=https://example.com/bot_directory/bot.php Site must have SSL (https).
$update = json_decode(file_get_contents('php://input'), TRUE);
$botToken = "(your token)";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$msg = $update['message']['text'];
$user_id = $update['message']['from']['id'];
if (isset($update['callback_query'])) {
$update_multiple = explode('_', $update['callback_query']['data']); //split data
if ($update_multiple[0] == 'delivered') {
$data1 = $update_multiple[1]; // get some data
// ......
}
}
I wan't my bot to receive images if user asks for it.
But I really not sure how to make it possible.
I've created special page on my web site, where I get images by request.
But, my bot isn't working.
I've created flickr account, created special page, the connected my bot's code with flickr page code.
So, the question is, how to make my bot search pictures in flickr and then provide them to user?
Here is code for bot page:
include 'flickr.php';
$row = "My access token";
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$row;
$ch = curl_init($url);
if($message == "image'.$set.'")
{
$load_images = $hasil;
$image = file_get_contents($load_images);
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"attachment":{
"type":"image",
"payload":{
"url":"'.$image.'"
}
}
}
}';
};
$json_enc = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_enc);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
And here is my flickr code.
I think that the mistake is somewhere here, but I can't see it.
require_once 'webhook.php';
class flickr
{
var $api;
function __construct($api) {
$this->api = $api;
}
function flickr_photos_search($search,$count_image,$size)
{
$params = array(
'api_key' => $this->api,
'method' => 'flickr.photos.search',
'text' => $search,
'format' => 'rest',
'per_page' => $count_image,
'page' => 1,);
$xml = $this->create_url($params);
if(#$rsp = simplexml_load_file($xml))
{
if (count($rsp)<>0)
{
foreach($rsp->photos->children() as $photo)
{
if ($photo->getName()=='photo')
{
$farm=$photo->attributes()->farm;
$server=$photo->attributes()->server;
$id=$photo->attributes()->id;
$secret=$photo->attributes()->secret;
if ($size=='Med')
{
$sz="";
}
else
{
$sz = "_".$size;
}
$gbr[]='<img src="https://farm'.$farm.'.staticflickr.com/'.$server.'/'.$id.'_'.$secret.$sz.'.jpg'.'" /> ';
}
}
}
else
{
die("No images found!");
}
}else
{
die("wrong parameter");
}
return $gbr;
}
function create_url($params)
{
$encoded_params = array();
foreach ($params as $k => $v){
$encoded_params[] = urlencode($k).'='.urlencode($v);
}
$url = "https://api.flickr.com/services/rest/?".implode('&', $encoded_params);
return $url;
}
}
if(isset($_REQUEST[$set]))
{
$search=$_REQUEST[$set];
$result= 30;
$size = 'm';
$flickr = new flickr('My flickr secret code');
$gbr = $flickr->flickr_photos_search($search,$result,$size);
foreach($gbr as $hasil)
{
echo $hasil.' ';
}
}
There is a problem:
$load_images = $hasil;
$image = file_get_contents($load_images);
"payload":{
"url":"'.$image.'"
}
From documentation - Payload image is just URL of that image
You can use my API (https://github.com/Fritak/messenger-platform) for that, really easy to use:
// Send an image (file).
$bot->sendImage($userToSendMessage, 'http://placehold.it/150x150');
I used the following code to include bing API in my web page. How can I add paging to this web search ?
Currently it shows only 1st 50 results and does not show the page links to other results. Also, how do I limit the results in one page to 20 ?
<?php
if (isset($_POST['submit']))
{
$acctKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$rootUri = 'https://api.datamarket.azure.com/Bing/Search';
$query = $_POST['searchText'];
$serviceOp ='Web';
$market ='en-us';
$query = urlencode("'$query'");
$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query";
$auth = base64_encode("$acctKey:$acctKey");
$data = array(
'http' => array(
'request_fulluri' => true,
'ignore_errors' => true,
'header' => "Authorization: Basic $auth"
)
);
$context = stream_context_create($data);
$response = file_get_contents($requestUri, 0, $context);
$response=json_decode($response);
echo "<pre>";
echo("<ol>");
foreach($response->d->results as $value)
{
$Ur = $value->Url;
echo '<li class="resultlistitem"><a href="{$Ur}"> '.$Ur. '
</a><br><p>';
echo($value->Description .'</li> </p>');
}
echo("</ol>");
echo "</pre>";
}
?>
I'm quite new to PHP and am creating a web scraper for a project. From this website, https://www.bloglovin.com/en/blogs/1/2/all, I am scraping the blog title, blog url, image url and concatenating a follow through link for later use. As you can see on the page, there are several fields with information for each blogger.
Here is my PHP code so far;
<?php
// Function to make GET request using cURL
function curlGet($url) {
$ch = curl_init(); // Initialising cURL session
// Setting cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$results = curl_exec($ch); // Executing cURL session
curl_close($ch); // Closing cURL session
return $results; // Return the results
}
$blogStats = array();
function returnXPathObject($item) {
$xmlPageDom = new DomDocument();
#$xmlPageDom->loadHTML($item);
$xmlPageXPath = new DOMXPath($xmlPageDom);
return $xmlPageXPath;
}
$blPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/all');
$blPageXpath = returnXPathObject($blPage);
$title = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[1]');
if ($title->length > 0) {
$blogStats['title'] = $title->item(0)->nodeValue;
}
$url = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[2]');
if ($url->length > 0) {
$blogStats['url'] = $url->item(0)->nodeValue;
}
$img = $blPageXpath->query('//*[#id="content"]//div/a/div/#href');
if ($img->length > 0) {
$blogStats['img'] = $img->item(0)->nodeValue;
}
$followLink = $blPageXpath->query('//*[#id="content"]/div[1]/div/a/#href');
if ($followLink->length > 0) {
$blogStats['followLink'] = 'http://www.bloglovin.com' . $followLink->item($i)->nodeValue;
}
print_r($blogStats);
/*$data = $blogStats;
header('Content-Type: application/json');
echo json_encode($data);*/
?>
Currently, this only returns:
Array ( [title] => Fashion Toast [url] => fashiontoast.com [followLink] => http://www.bloglovin.com/blog/4735/fashion-toast )
My question is, what is the best way to loop through each of the results? I've been looking through Stack Overflow and am struggling to find an answer to my question, and my heads going a bit loopy! If anyone could advise me or put me in the right direction, that would be fantastic.
Thank you.
Update:
I'm very sure this is wrong, i'm receiving errors!
<?php
// Function to make GET request using cURL
function curlGet($url) {
$ch = curl_init(); // Initialising cURL session
// Setting cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$results = curl_exec($ch); // Executing cURL session
curl_close($ch); // Closing cURL session
return $results; // Return the results
}
$blogStats = array();
function returnXPathObject($item) {
$xmlPageDom = new DomDocument();
#$xmlPageDom->loadHTML($item);
$xmlPageXPath = new DOMXPath($xmlPageDom);
return $xmlPageXPath;
}
$blogPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/all');
$blogPageXpath = returnXPathObject($blogPage);
$blogger = $blogPageXpath->query('//*[#id="content"]/div/#data-blog-id');
if ($blogger->length > 0) {
$blogStats[] = $blogger->item(0)->nodeValue;
}
foreach($blogger as $id) {
$blPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/all');
$blPageXpath = returnXPathObject($blPage);
$title = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[1]');
if ($title->length > 0) {
$blogStats[$id]['title'] = $title->item(0)->nodeValue;
}
$url = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[2]');
if ($url->length > 0) {
$blogStats[$id]['url'] = $url->item(0)->nodeValue;
}
$img = $blPageXpath->query('//*[#id="content"]//div/a/div/#href');
if ($img->length > 0) {
$blogStats[$id]['img'] = $img->item(0)->nodeValue;
}
$followLink = $blPageXpath->query('//*[#id="content"]/div[1]/div/a/#href');
if ($followLink->length > 0) {
$blogStats[$id]['followLink'] = 'http://www.bloglovin.com' . $followLink->item($i)->nodeValue;
}
}
print_r($blogStats);
/*$data = $blogStats;
header('Content-Type: application/json');
echo json_encode($data);*/ ?>
maybe you want to actually add a dimension to your array. I guess bloggers have a unique id, or somesuch identifier.
moreover, your code seems to execute only once? it might need to be in something like a foreach
I can't do that part for you, but you need an array containing each blogger, or a way to do a while, or for! you have to understand how to iterate over your different bloggers by yourself :)
here an exemple of array of bloggers
[14]['bloggerOne']
[15]['bloggerTwo']
[16]['bloggerThree']
foreach ($blogger as $id => $name)
{
$blPage = curlGet('https://www.bloglovin.com/en/blogs/1/2/' . $name);
// here you have something to do so that $blPage is actually different with each iteration, like changing the url
$blPageXpath = returnXPathObject($blPage);
$title = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[1]');
if ($title->length > 0) {
$blogStats[$id]['title'] = $title->item(0)->nodeValue;
}
$url = $blPageXpath->query('//*[#id="content"]//div/a/h2/span[2]');
if ($url->length > 0) {
$blogStats[$id]['url'] = $url->item(0)->nodeValue;
}
$img = $blPageXpath->query('//*[#id="content"]//div/a/div/#href');
if ($img->length > 0) {
$blogStats[$id]['img'] = $img->item(0)->nodeValue;
}
$followLink = $blPageXpath->query('//*[#id="content"]/div[1]/div/a/#href');
if ($followLink->length > 0) {
$blogStats[$id]['followLink'] = 'http://www.bloglovin.com' . $followLink->item($i)->nodeValue;
}
}
so after the foreach, you array could look like:
['12345']['title'] = whatever
['url'] = url
['img'] = foo
['followLink'] = bar
['4141']['title'] = other
['url'] = urlss
['img'] = foo
['followLink'] = bar
['7415']['title'] = still
['url'] = url4
['img'] = foo
['followLink'] = bar