how make html cache from php script - php

i have this script on my site, and i need to cache it in HTML, and maybe set expire cache to 24hours. This is the script:
<?php
$dir='DDL/ANIME/';
$s = $_GET['s'];
$d = $_GET['d'];
$ref=$_SERVER['HTTP_REFERER'];
$file=$dir.$_GET["file"];
$file1=$_GET["file"];
$esiste = 0;
$desistenza= "error";
$domain0='www.example0.org';
$domain1='www.example1.org';
$domain2='www.example2.org';
$domain3='www.example3.org';
$domain4='www.example4.org';
$domain5='www.example5.org';
$domain6='www.example6.org';
$domain7='www.example7.org';
$domain8='www.example8.org';
$domain9='www.example19.org';
$domain10='www.example10.org';
$domain11='www.example11.org';
function checkFileOnDomain($file,$domain) {
$resourceUrl = "http://$domain/$file";
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.example0.org/');
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($statusCode == '200')
return true;
}
$domain_list=array("www.example1.org", "www.example2.org", "www.example3.org", "www.example4.org", "www.example5.org", "www.example6.org", "www.example7.org", "www.example8.org", "www.example9.org", "www.example10.org", "www.example11.org");
foreach ($domain_list as $domain) {
if (checkFileOnDomain($file,$domain)) { $esiste = 1; $desistenza=$domain;
} else {}
} unset($domain);
?>
<html>
<head>
<title>Download & Streaming </title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="playerhtml5.css">
<meta http-equiv="Content-Language" content="it" />
<link rel="stylesheet" type="text/css" href="0174/ds.css" />
<script type="text/javascript" src="0174/advertisement.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
</head>
<body oncontextmenu="return false;">
<center>
<? if($esiste == 1 ){ ?>
<? if(empty($s)){ ?>
<?php
$d = $desistenza;
switch ($d) {
case $domain0: $d = "af"; break;
case $domain1: $d = "1"; break;
case $domain2: $d = "2"; break;
case $domain3: $d = "3"; break;
case $domain4: $d = "4"; break;
case $domain5: $d = "5"; break;
case $domain6: $d = "6"; break;
case $domain7: $d = "7"; break;
case $domain8: $d = "8"; break;
case $domain9: $d = "9"; break;
case $domain10: $d = "10"; break;
case $domain11: $d = "11"; break;
default: $s = "NO";
}
?>
<div id="wtf" class="button">
<a href="http://<?php echo $desistenza ?>/<?php echo $file ?>" target="_blank" >Download</a>
Streaming Alternative
</div>
<div id="wtf" class="html5video lightsoff" style="width:100%;">
<div id="wtf" class="main-container">
<div class="hero-unit">
<video id='video-player' preload='metadata' controls>
<source src="http://<?php echo $desistenza ?>/<?php echo $file ?>" type="video/mp4">
</video>
</div>
</div>
</div>
<? } ?>
<? if($s == 3){ ?>
<div id="wtf" class="button">
Download</p></b>
</div>
<? } ?>
<? } ?>
<? if($esiste == 0 ){ ?>
<b><p style="font-size:30px"><font color="#FF6600">File not found <br></font></b></p>
<? } ?>
</center>
</body>
</html>
the script is working fine and all is good, but my site is on shared hosting, so sometimes it causes high load to cpu, so i come up with the solution to cache this pages

You can save the content of the pages on your local files system. On the next request for the page, you check the timestamp of the saved page in your local file system. In case it's older than 24 hour, curl the page, otherwise serve the save file.

Related

Google sign in redirect back to login page if email not in the database

i am kinda new to PHP and not sure if this has been answered before i cant really find anything. what im asking for help with is with a google sign in if the email address is not in the database i would like it to redirect the user back to the login page, i have attached the code for the login below if anyone can help it will be highly appreciated thank you.
//session_start();
//index.php
include('classDev.php');
//Include Configuration File
include('config.php');
$login_button = '';
if(isset($_GET["code"]))
{
$token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
if(!isset($token['error']))
{
$google_client->setAccessToken($token['access_token']);
$_SESSION['access_token'] = $token['access_token'];
$google_service = new Google_Service_Oauth2($google_client);
$gData = $google_service->userinfo->get();
if(!empty($gData['given_name']))
{
$_SESSION['user_first_name'] = $gData['given_name'];
}
if(!empty($gData['family_name']))
{
$_SESSION['user_last_name'] = $gData['family_name'];
}
//if (empty(($data->select_where("user",$where_condition)))) {
// header("location: index.php?status=failure");
//}
if(!empty($gData['email']))
{
$where_condition = array("email" => $gData['email']);
if (($data->select_where("user",$where_condition))) {
$_SESSION['user_email_address'] = $gData['email'];
}
}
if (empty($_SESSION['email'])) {
//echo "please enter an email address that is valid.";
//header('location: index.php?status=failure');
}
if(!empty($gData['gender']))
{
$_SESSION['user_gender'] = $gData['gender'];
}
if(!empty($gData['picture']))
{
$_SESSION['user_image'] = $gData['picture'];
}
}
}
if(!isset($_SESSION['access_token']))
{
$login_button = 'Login With Google';
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Login using Google Account</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">PHP Login using Google Account</h2>
<br />
<div class="panel panel-default">
<?php
if($login_button == '')
{
echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
echo '<h3><b>Name :</b> '.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
echo '<h3><a href="logout.php">Logout</h3></div>';
//header('location: home.php');
include('home.php');
}
else
{
echo '<div align="center">'.$login_button . '</div>';
}
?>
</div>
</div>
</body>
</html>```

Is there a way to automatically use another image as a temporary placeholder for missing images sitewide?

I am working on building a site, but right now it has several images that I don't have actual images for yet. As this site has thousands of images or places where images should be, I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Update: Since I am still a bit confused as to where to even place this function, I am going to add the code for one of the pages that I need this for then maybe someone can help me figure out how to place it.
Here is the code for one of the pages:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do { ?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
Since this is as simple as a foreach loop, and not tons of images scattered across your webpage, you can use something like:
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
Full code:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do {
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="<?php echo $image; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Such a function might be written as:
function im($imgName) {
$pathToImgs = "images/";
if (file_exists( $pathToImgs . $imgName )) {
echo $pathToImgs . $imgName;
}
else {
echo $pathToImgs . "placeholder.jpg";
}
}
Then in your html:
<img src="<?php im("product1.jpg"); ?>">
<img src="<?php im("product2.jpg"); ?>">
<img src="<?php im("product3.jpg"); ?>">
As a start.
***Edit 1:
Given your code where it says:
<img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
You might modify it with a conditional that inserts the placeholder image in the event that the target image simply doesn't exist, yet.
<img class="thumb" src="<?php
if (file_exists("img/" . $row_master['img'])) {
echo "img/" . $row_master['img'];
}
else {
echo 'img/placeholder.jpg';
}
?>">
You could reuse this functionality by turning the conditional into a php function, so described as a starter above.
Using jQuery, you can accomplish something easy enough using a global $('img') handler when errors occur. Simply swap them out with your placeholder image afterwards.
$('img').on('error', function() {
const oldSrc = encodeURIComponent($(this).attr('src'));
$(this).attr('src', `https://via.placeholder.com/300/000000/FFFFFF/?text=${oldSrc}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="imagethatdoesntexist.jpg"><br />
<img src="anotherimage.jpg">
Here I use placeholder.com (A convenient site for placeholder images such as this), and inject the old image source into the query string, which the site will render in the image itself.

HTML doesn't load after PHP opening tag

Right now I'm coding this really simple user page but getting one problem that's bugging me and can't find out why it's happening.
When ever I would put <?php HTML will just stop loading from there.
<?php
session_start();
if (!isset($_SESSION["user"])) {
$logged_in = "no";
} else {
$username = $_SESSION["user"];
$logged_in = "yes";
}
include ('global.php');
?>
<head>
<title><?php echo $sitename; ?></title>
<link rel="stylesheet" type="text/css" href="css.css">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="header">
<div class="header_content">
<div class="middle_logo">
<p><?php echo $sitename; ?></p>
</div>
</div>
</div>
<div class="under_header">
<?php
$id = htmlentites($_GET["id"]);
$get_user_data = mysqli_query ($dconnect, "SELECT * FROM user_data WHERE id='$id'");
if (mysqli_num_rows($get_user_data) < 2) {
header ("Location: index.php");
} else {
while ($row = mysqli_fetch_array($get_user_data)) {
echo $row["username"];
}
}
?>
<h1><?php echo $users_name; ?></h1>
</div>
When I look at the source code it ends at <div class="under_header">
The answer has already been found in the comment :
The line :
$id = htmlentites($_GET["id"]);
Contain an error and should be :
$id = htmlentities($_GET["id"]);
Thanks to #RiggsFolly and #JustOnUnderMillions.
You can now accept an answer and close the question.

A redirecting site (dereferrer) like anonym.to in PHP - Check URL parameter - Security?

I wand to build a simple dereferrer site like anonym.to
When you visit http://www.mydereferrer.tld/?http://www.sitename.tld you should be redirected to http://www.sitename.tld by a meta-refesh tag.
Here's what I have:
<?
if(($pos = strpos($_SERVER['REQUEST_URI'], '?')) !== false) {
$url = trim(substr($_SERVER['REQUEST_URI'], $pos + 1));
}
if (strlen($url) > 50) {
$url_short = substr($url, 0, 48) . "..";
} else {
$url_short = $url;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?
if(!empty($url)) {
?>
<meta http-equiv="refresh" content="1; URL=<? echo $url ?>" />
<?
}
?>
<title>.. Redirecting</title>
</head>
<body>
<div id="container">
<?
if (isset($url)) {
?>
<h1>.. Redirecting</h1>
<p><? echo $url_short; ?></p>
<?
} else {
?>
<h1>.. No valid URL given</h1>
<?
}
?>
</div>
</body>
</html>
this works quite fine. But what security checks should I do?
What CBroe is referring to is that you just include $url and $url_short without any character escaping. Because of that you are susceptible to XSS. As a quick example assume $url is
www.google.com" /><body onload=alert('test1')><br style="
then
<meta http-equiv="refresh" content="1; URL=<? echo $url ?>" />
gets evaluated to
<meta http-equiv="refresh" content="1; URL=www.google.com" /><body onload=alert('test1')><br style="" />
OWASP has an excellent guide on how you embed untrusted data into your page.

Instagram API pagination

I am using the below code which works well at loading all the images that match the #spproject tag. What i'd like to do is load 9 photos at a time and then either load more with ajax or just link to previous/next pages. Problem is i dont quite understand how to do it using the API, can you help?
CODE:
<?PHP
function get_instagram($next=null,$width=160,$height=160){
if($next == null ) {
$url = 'https://api.instagram.com/v1/tags/spproject/media/recent?access_token=[TOKEN]&count=10';
}
else {
$url .= '&max_tag_id=' . $next;
}
//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
//unlink($cache); // Clear the cache file if needed
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
$result = '<ul id="instagramPhotos">'.PHP_EOL;
if (is_array($jsonData->data))
{
foreach ($jsonData->data as $key=>$value)
{
$result .= '<li><div class="album">
<figure class="frame">
<i><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" name="'.$value->user->username.'"></i>
</figure>
<span class="count">#SPproject</span>
<figcaption class="name">'.$value->user->username.'</figcaption>
</div></li>'.PHP_EOL;
}
}
$result .= '</ul>'.PHP_EOL;
if(isset($jsonData->pagination->next_max_tag_id)) {
$result .= '<div>Next</div>';
}
return $result;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>#SPproject - A worldwide instagram idea</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="normalize.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var totalPhotos = $('#instagramPhotos > li').size();
$('#result').text('Total tagged images: '+totalPhotos);
});
</script>
</head>
<body>
<div id="container">
<?=get_instagram(#$_GET['next']);?>
<div id="result"></div>
</div>
</body>
</html>
website: http://www.spproject.info/
The JSON object which Instagram is returning contains a pagination variable and in turn, a "next_url" variable. next_url is the API URL you need to call to get the next page of results.
Here is a good tutorial on pagination with Instagram.
Also, a tip for the future - don't post your API access codes on the internet...
The (revised) code below should be a good starting point for you.
<?PHP
function get_instagram($next=null,$width=160,$height=160){
$url = 'https://api.instagram.com/v1/tags/spproject/media/recent?access_token=[token]&count=9';
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
//unlink($cache); // Clear the cache file if needed
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
$result = '<ul id="instagramPhotos">'.PHP_EOL;
foreach ($jsonData->data as $key=>$value) {
$result .= '<li><div class="album">
<figure class="frame">
<i><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" name="'.$value->user->username.'"></i>
</figure>
<span class="count">#SPproject</span>
<figcaption class="name">'.$value->user->username.'</figcaption>
</div></li>'.PHP_EOL;;
//$result .= '<li><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" name="'.$value->user->username.'" /></li>'.PHP_EOL;
}
$result .= '</ul>'.PHP_EOL;
if(isset($jsonData->pagination->next_max_tag_id)) {
$result .= '<div>Next</div>';
}
return $result;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>#SPproject - A worldwide instagram idea</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="normalize.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var totalPhotos = $('#instagramPhotos > li').size();
$('#result').text('Total tagged images: '+totalPhotos);
});
</script>
</head>
<body>
<div id="container">
<?=get_instagram(#$_GET['next']);?>
<div id="result"></div>
</div>
</body>
</html>

Categories