Instagram API pagination in PHP - php

I am trying to create a small instagram app in PHP only (no database) and without getting an access_token (just my client_id). So far so good, (i.e. input user_id returns photos from last 30 days, with likes-count and created_time, in a table), until I get to pagination. As expected, I want to hit a 'more' button which loads next json file and adds additional photos to the existing table, but it falls apart there... Here is what I've got, working, except for the pagination attempt.
NOTE: this is an internal app, so the sensitivity of my client_id is not an issue, if it is exposed
<?php
if (!empty($_GET['user_id'])){
$user_id = ($_GET['user_id']);
$instagram_url = 'https://api.instagram.com/v1/users/' . $user_id . '/media/recent/?client_id=MY_CLIENT_ID';
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json, true);
}
?>
...
<?php
if(!empty($instagram_array)){
$instagram_array['pagination'] as $page { // Attempt at pagination
echo '<p>' .$page['next_url'].'</p>'; // Attempt at pagination
} // Attempt at pagination
foreach($instagram_array['data'] as $image){
if ($image['created_time'] > strtotime('-30 days')) {
echo '<tr>';
echo '<td>' . date('M d, Y', $image['created_time']) . '</td>';
echo '<td>'.$image['likes']['count'].'</td>';
echo '<td><img src="'.$image['images']['standard_resolution']['url'].'" alt=""/ style="max-height:40px"></td>';
echo '</tr>';
}
}
}
?>
</body>
</html>
Note: this is cobbled together from a few other sources - I am a total noob, so please forgive me if I need a little hand-holding...:)

You may specify min_timestamp to return medias which taken later than this timestamp
https://api.instagram.com/v1/users/{user_id}/media/recent/?access_token={access_token}&min_timestamp={min_timestamp}
$instagram_array['pagination']['next_url'] should be removed, it may include your access token which is a sensible data, that must be always invisible.
list_ig.php
<?
$user_id = "...";
$access_token = "...";
//30 day ago
$min_timestamp = strtotime("-30 day",time());
//pagination feature
$next_max_id = $_GET['next_max_id'];
$instagram_url = "https://api.instagram.com/v1/users/" . $user_id . "/media/recent/?access_token=" .$access_token. "&min_timestamp=" . $min_timestamp;
if($next_max_id != "")
$instagram_url .= "&max_id=" . $next_max_id;
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json ,true);
?>
<? if( $instagram_array['pagination']['next_max_id'] != "" ): ?>
More
<? endif;?>
.... print instagram data....
Instagram AJAX Demo
http://jsfiddle.net/ajhtLgzc/

Related

How do I create a prev/next function for a one page display site?

I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}

get a variable number from sql

I'm a beginner in php. I'm trying get a variable number from sql ,
I have this part of code:
function renderNotification()
{
if ($user_id = $this->getDi()->auth->getUserId()) {
$cnt = $this->getDi()->db->selectCell("SELECT COUNT(ticket_id) FROM ?_helpdesk_ticket WHERE status IN (?a) AND user_id=?",
array(HelpdeskTicket::STATUS_AWAITING_USER_RESPONSE), $user_id);
if ($cnt)
return '<div class="am-info">' . ___('You have %s%d ticket(s)%s that require your attention',
sprintf('', REL_ROOT_URL . '/helpdesk/index/p/index/index?&_user_filter_s[]=awaiting_user_response'), $cnt, '') .
'</div>';
}
}
i want get number of ticket only in other place in my program
This is my try:
<?php echo "%s%d" ; ?>
or
<?php echo $cnt ; ?>
but not work
i'm using Zend , sf , pear , all what i need output %s%d ticket(s)%s from above code in other place or call it
i have found correct way it's below
<?php
$cnt = $di->db->selectCell("SELECT COUNT(ticket_id)
FROM ?_helpdesk_ticket
WHERE status IN (?a)
AND user_id=?",
array(HelpdeskTicket::STATUS_AWAITING_USER_RESPONSE),
$di->user->pk());
echo $cnt;
?>

Showing specific information of current user logged in, in PHP

I'm using this 2 plugins
http://www.wpexplorer.com/wordpress-user-contact-fields/
and
WooCommerce
The 1st parameter, in this case the number "1" refers to the id of the user, how con I change it to be dynamic? So, depending on the user I get its own specific information
<h2>Personal</h2>
<?php
echo '<ul>';
echo '<li>Direccion: ' .get_user_meta(1,'address',true) . '</li>';
echo '<li>Compañia: ' .get_user_meta(1,'company',true) . '</li>';
echo '<li>Birth dAte: ' .get_user_meta(1,'birth',true) . '</li>';
echo '<li>Gender: ' .get_user_meta(1,'gender',true) . '</li>';
echo '<li>phone: ' .get_user_meta(1,'phone',true) . '</li>';
echo '</ul>';
?>
thanks
Don't try to make a function do something it wasn't intended to do. Write your own. Especially for something this simple.
function getUserStuff($id, $item){
$item = mysql_real_escape_string($item);
$id = mysql_real_escape_string($id);
$q = mysql_query("SELECT `".$item."` FROM `users` WHERE `id` = '".$id."'");
$z = mysql_fetch_assoc($q);
return (mysql_num_rows($q) > 0) ? $z[$item] : false;
}
This is just an example. I used a deprecated function for simplicity but you should use a different API.

Unable to retrieve results from site

Everything's working fine but I was unable to retrieve the total number of results from the site (faroo)..
<?php
if (isset($_GET['q']))
{
$q = $_GET['q'];
$p = $_GET['p'];
$page = file_get_contents('http://www.faroo.com/api?q=' . $q
. '&start=' . $p . '&l=en&key='.$myownkey.'&src=web&f=json');
// echo $page->{'count'}; //this too not working
$dat_array = json_decode($page, true);
echo $dat_array->{'count'}; //not woking.
}
?>
where am I going wrong?
json_decode($page, true);
The second parameter as "true" turns the data into an associative array rather than an object. To access the data this should work:
echo $dat_array['count'];

PHP Twitter search api with tweet back button

I'm using working on building a WordPress plugin, that uses the Twitter api - but I'm very new to working with Twitter.
I currently have a keyword search form and results working
<?php
// get the keyword from url
$srchterm = $_GET['search_box'];
// encode it for the safe search
$srchterm = urlencode($srchterm);
// search the keyword using Twitter API
$srch_twitts = "http://search.twitter.com/search.atom?q=".$srchterm."";
// use curl to execute the Twitter URL
$twits = curl_init();
curl_setopt($twits, CURLOPT_URL, $srch_twitts);
curl_setopt($twits, CURLOPT_RETURNTRANSFER, TRUE);
$twi = curl_exec($twits);
// here we have the searched result in an array
$search_res = new SimpleXMLElement($twi);
//print_r($search_res);
?>
<?php
/* display the data */
$i = 0;
// displays the search keyword
echo "<p style='padding-left:10px; color:brown'>Your search term is: " . stripslashes($_GET['q']) . "</p>";
// tweets in an array. split it by foreach
// we need only 10 result so, use if condition
foreach ($search_res->entry as $result) if ($i++ < 10)
{
echo "<div id='tweets'>";
echo "<p>$i</p> ";
echo "<div class='avatar'><img src='". $result->link[1]->attributes()->href. "' /> </div>";
echo "<div class='twitcont'>";
echo "<div class='name'>". $result->author->name . "</div>";
echo "<div class='content'>" . $result->content ;
// convert the updated date of tweet to seconds
$twittedSeconds = time() - strtotime($result->updated);
$names = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$seconds = array( 1, 60, 3600, 86400, 604800, 2630880, 31570560);
// find the time difference between present time and tweet time
if($twittedSeconds > 0)
{
for($j = count($seconds) - 1; $j >= 0 ; $j--)
{
$interval = $seconds[$j];
if($twittedSeconds >= $interval)
{
$getTime = round($twittedSeconds / $interval);
if ($getTime > 1)
{
$names[$j] .= s;
}
$time = $getTime. ' ' . $names[$j] . ' ago';
break;
}
}
//echo the time difference
echo "<div class='time'> " . $time . "</div>";
}
echo "</div>";
echo "</div></div>";
}
?>
My question:
How can I integrate a tweet button for each result - this would allow the admin to (after searching twitter for keyword matches) tweet back on conversations.
Please see this example: http://screencast.com/t/2xBkTyUHT
Find the tweet id then attach a hyper link of this format
https://twitter.com/intent/tweet?in_reply_to={tweet id}
So the link might look like this.
$tweet_id = substr($entry->id, strrpos($entry->id, ':')+1);
echo "Reply";
More information can be found here. Twitter Web Intents
Note: You put echo "<div id='tweets'>"; in a loop. Means DOM will have multiple elements with same id. Correct it either using class or put it outside the loop.

Categories