Tinypass dynamic data - php

I am using Tinypass.com for a paywall and would like to show data from a database table inside the tags.
I want to replace below where: 'ECHO DATA FORM DB TO GO HERE'
So far I have:
<?php
/* Include TinyPass - make sure to use the correct path */
include_once "lib/TinyPass.php";
// configure Tinypass
TinyPass::$SANDBOX = true;
# Chanage these values with your TinyPass applicatin's settings
TinyPass::$AID = "76JigADEH5";
TinyPass::$PRIVATE_KEY = "aj43agFz9ZGxq8yPlZN4PHn01Xiy0bnezWmpEirC";
/*
If you want to integrate this system with logged in user then RID should be [ObjectName-UserID]
*/
$rid = "Content-1"; #unique_resource_id
$store = new TPAccessTokenStore();
$store->loadTokensFromCookie($_COOKIE);
$token = $store->getAccessToken($rid);
# If anonymous user has rights to see content
if($token->isAccessGranted()) {
//Access granted! Display requested resource to the user
echo '<div class="vendor"><iframe src="http://player.vimeo.com/video/25708134?title=0&byline=0&portrait=0" width="500" height="281" frameborder="0"></iframe></div>'; } else {
echo '<div style="background-color:#D3768D; width:100%; height:281px;"></div><div style="padding:15px;" >
ECHO DATA FORM DB TO GO HERE
<br> ';
$resource = new TPResource("$rid", "Paid Content");
//Create 3 price options
$po1 = new TPPriceOption("5.00", "24 hours");
$po2 = new TPPriceOption("10.00", "72 hours");
$po3 = new TPPriceOption("20.00", "30 days");
$offer = new TPOffer($resource, $po1);
$offer->addPriceOption($po2);
$offer->addPriceOption($po3);
$ticketoptions = array();
$ticketoptions["btn.size"] = "2";
$purchaseRequest = new TPPurchaseRequest($offer, $ticketoptions);
$buttonHTML = $purchaseRequest->generateTag();
//output button HTML in the place where Tinypass button is supposed to be rendered
echo $buttonHTML;
}
?>
Normally I would use:
<?php echo $row_tutorial['text_after']; ?>
But obviously that would not work with in another tag. Any ideas

So what you want is a concatenated string:
echo '<div style="background-color:#D3768D; width:100%; height:281px;"></div><div style="padding:15px;" >' . $row_tutorial['text_after']. '<br> ';

Related

PHP Database search display

To give you an understanding of what I'm working on. I'm working on a project where on my school campus you can navigate around. For example a room can be called J2626 or J2617 etc... The thing is that when a user Is using my website I only want it to type in the exact name of the room to be able to display anything. Right now it doesn't work like I want it to.
For example: if you only type in J in the search field, it will display all rooms that start with J.
Here is my code right now:
<?php
$fileName = dirname(dirname(__FILE__)) . "../../db/bth_nav.sqlite";
if (isset($_GET['page'])) {
$argument = $_GET['page'];
$argument = "%" . $argument . "%";
$db = new PDO("sqlite:$fileName");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt = $db->prepare('SELECT * FROM bth_nav WHERE name LIKE (:nameOwner) OR owner LIKE (:nameOwner);');
$stmt->execute(array($argument));
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($res)) {
header("Location: " . "http://" . $_SERVER['index.php']);
}
?>
<div class = "formObjectSearch">
<?php foreach ($res as $val) { ?>
<div class = "infoTab">
<h2><?= $val['name']; ?></h2>
<p>Guidance: <?= $val['info']; ?></p>
<p>Whos sitting here?: <?= $val['owner']; ?>
</div>
<img class = "buildingImage" src = "img/<?= $val['image']; ?>"
<?php
}
}
?>
</div>
I've tried making diffrent if statements but with no success. So what I need help with is that I only want the user to be able to search for a correct room name and not be able to only search for J and display everything.
Update
Here is my index.php:
I used this link, because Code sample didn't want to work: index.php code
Here is my building.php:
Samer here: building.php code
And the the new search.php with help:
Same here: search.php code
I get these errors right now:
Notice: Undefined index: index.php in /path/incl/files/search.php on line 19
Warning: Cannot modify header information - headers already sent by (output started at /path/incl/header.php:7) in /path/incl/files/search.php on line 19
My header.php code:
Same here: header.php code
My config.php code:
Same here: config.php code
My footer.php code:
Same here: footer.php code
If i understanded you correctly and if you want to search for all rooms with starting letter J, you need to change your arguments.
Explanation:
'%J%' - searches for selected field, where is J letter.
'%J' - searches for selected field, where J is the last letter.
'J%' - searches for selected field, where J is the first letter.
Try to change your argument like that:
$argument = $argument . "%";
UPDATE
Fixing your if statement:
if (empty($res) OR $res == null) {
header('Location: http://'.$_SERVER['index.php']);
}
else {
echo '<div class = "formObjectSearch">';
foreach ($res as $val) {
echo '<div class = "infoTab">';
echo '<h2>'.$val["name"].'</h2>';
echo '<p>Guidance:'.$val["info"].'</p>';
echo '<p>Whos sitting here?:'.$val["owner"].'</p>';
echo '</div>';
echo '<img class="buildingImage" src="img/'.$val['image'].'" />';
}
echo '</div>';
}
OR
You can try to replace empty, with:
if ($res->rowCount() > 0) {
// if founded
} else {
// header('Location: http://'.$_SERVER['index.php']);
}

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;
}

Instagram API pagination in 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/

Echoing a <div> and obtaining the id of it

Currently, when displaying all posts made by users I do the following:
while($info=mysql_fetch_array($data)) {
echo "<div id = 'posts'>";
echo $info['subject'];
echo $info['post-item'];
echo "</div>";
}
But, however, I now need to treat each element fetched as an actual post rather than just an outputted div for obtaining the post_id of each post to be able to actually enable a user to interact with different posts e.g. to 'like' a post.
I had tried hyperlinking the like href to ?id=$thispost which worked for liking however had problems such as a user altering the url, or even if I would like to also add the commenting functionality, I would need a different method!
As for different tasks, you would pass different querystrings:
like this
comment
share this
In page.php, you would then...
if (isset($_GET['do'] && isset($_GET['id'])) {
$do = $_GET['do'];
$id = $_GET['id'];
} else exit("blabla");
switch ($do) {
case 'like':
// do sth
break;
case 'comment':
// do sth
break;
// etc.
} // switch
Of course, passing the values by URL open the gate to manipulation.
So either store $do and $id in $_SESSION or in $_POST.
Example for $_POST:
$h = "";
while ($info = mysql_fetch_array($data)) {
$h .= '<div id = "posts">';
$h .= '<form method="post" action="page.php">';
$h .= "{$info['subject']}<br />{$info['post-item']}";
$h .= "<input type=\"hidden\" name=\"id\” value=\”{$info['id']}\” />';
$h .= '<input type="submit" name="do" value="like" />';
$h .= '</form></div>';
}
echo $h;
Comments:
1. don't use mysql_*, but mysqli_* or PDO -> makes your code future-proof and more secure
2. this code creates a form around every post, with a hidden field containing the id (from db) of that post...
3. and a button that will send the id invisible for the user to page.php.
4. in page.php, you read $_POST, as in my above exaple with $_GET:
if (isset($_POST['id'])) {
$do = $_POST['do'];
$id = $_POST['id'];
} else exit("blabla");
// etc.

Concrete5 User attributes

I figured out how to du this seperatly
Display the user attribute:
<?php
//Create a User object (of the current User)
$u = new User();
//Creat a UserInfo object with the user ID
$ui = UserInfo::getByID($u->getUserID());
//Get the Value of your user Attribute
$value = $ui->getAttribute('name');
//Print it out
echo $value;
?>
Display page owner:
<?php
$ownerID = $cobj->getCollectionUserID();
$uia = UserInfo::getByID($ownerID);
$ownerName = $uia->getUserName();
echo $ownerName
?>
But i cannot figure out how to put them together so it displays the attribute('name'); of the page owner
Can you guys please help
Thanks
After moving a little bit more around with the codes.
i figured out that i just needed to move the
$cobj->getCollectionUserID();
into
$ui = UserInfo::getByID($u->getUserID());
So the finished code:
<?php
//Creat a UserInfo object with the Owner
$ui = UserInfo::getByID($cobj->getCollectionUserID() );
//Get the Value of your user Attribute
$value = $ui->getAttribute('name');
//Print it out
echo $value;
?>

Categories