Cache AND display images php - javascript

I am using a php script to display images stored as blobs in my database.
I used to display them with the following script.
<?php
if(!empty($_GET['user_id'])){//script to display an image from the database you basicly just get the id from the picture in matter and fucking acess it
include_once "DBH.php";
//Get image data from database
$id = mysqli_real_escape_string($conn, $_GET['user_id']);
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $id");
if($result->num_rows > 0){
$imgData = $result->fetch_assoc();
header("Content-type: image");
echo $imgData['image'];
}else{
echo 'Image not found...';
}
}
?>
In the context where
<img src = 'displayProfilePicture.php?user_id=n'>
The div containing the divs are updated frequently and to update the users image seems like alot of unnecessary processing. I want to cache the profilepictures in the webpage so that i dont have to query them from the database every time. I started reading alot about how you could cache the images but could not find any content on how to display the cached images.
This is a problem for me as the images flicker for a bit every time the img is updated with the php script. In an optimal world i see that the img load one time and then after that it does not have to load.
The context wich i use the display img script is in a chat that is updated with a timer-interval within an ajax-request
$("#chatlogs").load("logs.php");
logs.php
if(isset($_SESSION['chatRoomId'])){
while ($extract = mysqli_fetch_array($result1))
{
$from = $extract['from'];
//make an object to echo.
if($from == $id){
echo "<div class='chatContainer self'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$selfId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}else{
echo "<div class='chatContainer friend'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$guestId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}
}
}

I think this is what you looking for:
<?php
if(empty($_GET['user_id']) || !preg_match( '/^[0-9]+$/' , $_GET['user_id'])){
header( '400 Bad Request' );
exit(1);
}
include_once "DBH.php";
$user_id = intval( $_GET['user_id'] );
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $user_id");
if($result->num_rows == 0){
// Not Found
header('404 Not Found');
exit(1);
}
$imgData = $result->fetch_assoc();
header("Content-type: image");
$cache_for = 3600; // One hour in seconds
$cache_until = gmdate("D, d M Y H:i:s", time() + $cache_for) . " GMT";
header("Expires: $cache_until");
header("Pragma: cache");
header("Cache-Control: max-age=$cache_for");
echo $imgData['image'];
exit(0);
Comments
First I checked if the user_id is supplied in the request, if so then check if it was a valid number if it doesn't then respond with a 400 error.
And also I have removed a SQLi in your code src='displayProfilePicture.php?user_id=-1 or 1=1.
And I have set the caching headers, so the browser will cache the image for an hour.

Related

How to updating specific data from DB at specific periode

What is the way to keep update the info about if user has got new notifications?
When page is opened it includes content of pageTop.php. There it checks database, if there are some unchecked notification. And loads note_NO or note_YES in base of query.
How is the approach to have new info at certain time period ?
Next page works on page load or refresh. But I don't want to reload header.php each time.
header.php:
<?php include_once("pageTop.php");?>
<div id="pageMidle"></div>
<div id="pageFoot"></div>
pageTop:
$sql = "SELECT id FROM note WHERE user='$l_user' AND did_read ='0' ";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$nrows = mysqli_num_rows($query);
if ($numrows == 0) {
$envelope = '<img src="images/note_NO.jpg" width="30" height="30" alt="Notes">';
} else {
$envelope = '<img src="/images/note_YES.gif" width="30" height="30" alt="Notes">';
}
html:
<div id="envolopeDIV">
<?php echo $envelope; ?>
</div>
You can use a session to keep track of time between requests in the backend. If your specified time period has passed, include the snippet for querying the database.
session_start();
const TIME_PERIOD = 123456;
$currentTimestamp = time();
$previousTimestamp = $_SESSION['previous_timestamp'] ?? 0;
if ($previousTimestamp + TIME_PERIOD > $currentTimestamp) {
// check notifications
}
$_SESSION['previous_timestamp'] = $currentTimestamp;
//...

Header not working in php

I have a program that brings an image from the database and displays it inside an image div in my website. The below code was working successfully on my local wamp server but when I moved it to an online server it did not work anymore.
<?php
session_start();
include 'dbConnector.php';
$uID = $_SESSION['loggedUserID'];
$sql = "SELECT photo FROM hostmeuser WHERE userID = '$uID'";
$result = $conn->query($sql);
if(!$row = mysqli_fetch_assoc($result))
{
$imgData = "Assets/man.jpg";
}
else
{
$imgData = $row['photo'];
}
header("content-type: image/jpg");
echo $imgData;
?>
I have noticed that all (header) functions are not working on the new server and I have no control over this server so I replaced every:
header("Location: example.php")
with:
?>
<script type="text/javascript">
window.location.replace("example.php");
</script>
<?php
it is working fine now on most cases but not this one!
header("content-type: image/jpg");
Can you suggest any solution for this? or at least do you know how to represent this command in javascript?

Sql Php Ajax - Check if change in database

I currently have a ajax script to run a notiload.php file which runs every 5 seconds to check if theres a change in the database, if theres a change it then outputs "1 New" for a message. However as I will be introducing a notification sound in that file. It will chime every 5 secconds when the file is loaded. Of course this will piss people off. So I need the script to check if theres a change in the database. I have a time and date stamp of every message, with the message being viewed as 2 and not as 1. So if theres a change in the database I will need it to call that file or play a sound.
here is my ajax script inside the main page
<script type="text/javascript">
$(document).ready(function(){
refreshTable<?= $FriendName->id ?>();
});
function refreshTable<?= $FriendName->id ?>(){
$('#NotiLoad<?=$FriendName->id?>').load('elements/notiload.php?id=<?=$FriendName->id?>', function(){
setTimeout(refreshTable<?= $FriendName->id ?>, 5000);
});
}
</script>
<div id="NotiLoad<?= $FriendName->id ?>" style="display: inline-block;"></div>
And here is the php of notiload.php
<?php
session_start();
// redirect to index page if not superuser
$con = mysqli_connect('localhost','root','','');
if (!$con) {
die('Could not connect to Socialnetwk DB: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
?>
<?php
$uid = $_GET['id'];
$mid = $_SESSION['user']['id'];
?>
<?php $usrload = $con->query("SELECT * FROM message WHERE sender = $uid AND recipient = $mid AND seen = '2' OR sender = $mid AND recipient = $uid AND seen = '2'"); ?>
<?php while($FriendName = $usrload->fetch_object()): ?>
<h6 style="display:inline-block;font-size: 10px;color:#37BC9B">1 New</h6>
<?php endwhile;?>

How to create an image slideshow from images in a mysql database

I have a mysqli database and form which allows me to store an id, name and photo. The path of the photo is set to an "images" folder on the server. I have a query which can
SELECT * FROM images WHERE name = $pagetitle.
This works absolutely fine, outside of the javascript slideshow. When i put a php command in the javascript where it is looking for which images to display, the js only shows 1 image, and not ALL images.
Any help would be appreciated, thanks.
The section of the code in question is below...
index.php
<!-- Image Slide Show Start -->
<div style="display: flex; justify-content: center;">
<img align="middle" src="" name="slide" border=0 width=300 height=375>
<script>
<?php
require('dbconnect.php');
$data = mysql_query("SELECT * FROM images WHERE name= '$pagetitle'");
$image = mysql_fetch_array( $data );
?>
//configure the paths of the images, plus corresponding target links
slideshowimages("<?php echo "/images/".$image['photo'] . ""?>")
//configure the speed of the slideshow, in miliseconds
var slideshowspeed=2000
var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.slide.src=slideimages[whichimage].src
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",slideshowspeed)
}
slideit()
</script> </div><br><br>
<!-- Image Slide Show End -->
your update query have syntax errors, use , between fields, also you must contain strings in 2 ' :
$query = "UPDATE page_content SET PageTitle='$pageTitle',
PageContent='$PageContent', PageContent2='$PageContent2' WHERE PageId='$PageId'";
You have missed , between fields and '' around variables in your query.
$sql = "UPDATE page_content SET PageTitle='$pageTitle',
PageContent='$PageContent', PageContent2='$PageContent2'
WHERE PageId='$PageId'";
// check query executed successfully or get error
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
OR
$result = mysqli_query($sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR);
Hope it will help you :)
Try this:
$sql = "SELECT * FROM images WHERE name= '$pagetitle'";
$result = $conn->query($sql);
$directory = '';
while( $image = $result->fetch_assoc() )
$directory .= ($directory != '' ? "," : '') . ('"/images/'.$image["photo"] . '"');
// Check if it was successfull
if($directory != '') {
// if there are images for this page, run the javascript
?><script>
//configure the paths of the images, plus corresponding target links
slideshowimages(<?php print $directory ?>)

how to load more images from a folder using php jquery ajax

i have multiple folders and all folders contain some images upto 20 images.
in my html page i want to show first 5 images and show click to view more 15
and when the user click that link it will show next 15 images
but till now i can only fetch all the images at a time
here is my code
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
foreach($images as $image)
{
?>
<a href="<?php echo $image ?>" class="imageHover">
<img src="<?php echo $image ?>" class="img-responsive" />
</a>
<?php
}
?>
I am sorry for not being supportive or all but I think you should ask or research about "pagination". What you are asking is a definition of pagination.
Actually you are asking , "How do I implement pagination ?"
http://codular.com/implementing-pagination
http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928
and here is some code you can try to implement simple pagination
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
Simple PHP Pagination script
If I understood you correctly, you want your first page to display 5 images. Then, after clicking on a link, you want the same page to show the remaining images (from 5 up until the number of images in the folder – maybe 20 in your case).
I've been a bit verbose just so that it's clear. I've also left you echoing file paths as your code specifies, but presumably you're going to want to turn these into URLs. I'll leave that to you.
Try something like this:
<?php
$dirname = "img/outlets/".$service_type."/". $outlet_name ."/snaps/";
$images = glob($dirname."*.jpg");
$initial_images = 5; // However many you want to display on the inital load
// Get the starting image and the end image array keys
if($_GET['show_all_images']){ // Check the the browser sent a query parameter
// We've been asked to display more
// Get the array index of the first image. Remember that arrays start at 0, so subtract 1
$first_image_index = $initial_images - 1;
// Get the array index of the last image
$last_image_index = count($images);
}
else{
// We're on the inital load
$first_image_index = 0;
$last_image_index = $initial_images - 1;
}
// Iterate the glob using for. We want to specify an array key, so it's easier here to use for rather than foreach (which is the right solution most of the time)
for ($i=$first_image_index; $i < $last_image_index; $i++):?>
<a href="<?php echo $images[$i] ?>" class="imageHover">
<img src="<?php echo $images[$i] ?>" class="img-responsive" />
</a>
<?php endfor;?>
<?php if($_GET['show_all_images']): // Display a 'show less' link?>
Show less
<?php else: ?>
Show more
<?php endif; ?>
A simple way is to name images to end with indexed. Example being img_1.
You can then use ajax to fetch the last 15 images when user clicks on view more.
But this approach is very basic and is not scalable. As other answers suggest you can mix pagination with indexed image name approach

Categories

Resources