PHP pagination of 400+ pictures - php

a have a website with more than 400 pictures in a directory. I'd like to list them by 12 on every page. How can i do that? Here is my actual code:
<!doctype html>
<html lang="hu">
<head>
<title>Amatőr</title>
<meta charset="utf-8"/>
</head>
<body>
<h2>Vannak jó képeid? Töltsd fel őket és kikerülhetnek az oldalra!</h2>
<article>
<header>
Amatőr Lányok
</header>
<div id="kepek">
<?php
$imgdir = '../img/blog/img/amator/'; //Pick your folder
$allowed_types = array('png','jpg','jpeg','gif'); //Allowed types of files
$dimg = opendir($imgdir);//Open directory
while($imgfile = readdir($dimg))
{
if( in_array(strtolower(substr($imgfile,-3)),$allowed_types) OR
in_array(strtolower(substr($imgfile,-4)),$allowed_types) )
/*If the file is an image add it to the array*/
{$a_img[] = $imgfile;}
}
$totimg = count($a_img); //The total count of all the images
//Echo out the images and their paths incased in an li.
for($x=0; $x < $totimg; $x++){ echo "<a onclick='Lightbox.start(this, false, false, false, false); return false;' rel='lightbox[amator]' href='" . $imgdir . $a_img[$x] . "'><img class='kep_listaz' width='200px' height='160px' src='" . $imgdir . $a_img[$x] . "' /></a>";}
?>
</div>
</article>
</body>
</html>
Thanks!

So this is really more of a maths questions.
You will need to get the total count of the images, then divide that by the max number of images per page (make sure to ceil() it).
You have now a max number of pages needed to view all of these images. What you need to do now is figure whether you want page=1/page=2 etc or as a start and end. Both are relatively easy, however, with the page you'd need to do
$page = (int)$_GET['page'];
$start = $page * $max_items_per_page;
$end = $start + $max_items_per_page;
This way it's probably saver. Also add extra code to make sure you're not out of bounds with the page requested.
Now it's a matter of getting an array of the files (I suggest you use glob()) and use array_slice() that from start to end.
Finally just have a previous/next page, or list all (or some) of the pages. Getting next and previous is as simple as adding/removing 1 to $page, i.e. $next = $page + 1; and $prev = $page-1;. Again, for both of these, double check that you're not out of bounds. Probably best not to show next/previous if they are out of bounds.

There are two ways to paginate this kind of data: on the front-end where you send it all and JavaSctipt only shows the user a portion at a time, or on the back-end where the page is only rendered with a portion at a time and you reload the whole page to get more.
The fastest way to get it working is using the back-end method:
Before your for loop add $page = isset($_GET['page']) ? $_GET['page']-1 : 0;
Change the loop's argument to $x=$page*12; $x < $totimg && $x < ($page+1)*12; $x++
Then you can manipulate pages by adding ?page=3 to the url
You'll also want to add some error handling incase an invalid page number is submitted.

Related

System hit counter SaaS - Via TXT - Imagecopymerge

I am doing an hit counter (view) system, and now I need to find a way to merge all number images into one to be possible to embed in another pages, could someone help me out?
Here is the code I have:
$number = trim(file_get_contents('visitas.txt'));
$file = 'visitas.txt';
$views = file_get_contents ($file);
$fdata = intval($views)+1;
file_put_contents($file, $fdata);
$array = str_split($number);
if(!empty($array)){
foreach($array as $single){
echo '<img style="height:20px" src="'.$single.'.png">';
}
}else{
echo '<img src="0.png">';
}
$image = imagecreatefromstring(file_get_contents('sample.jpg'));
At the moment everything is working, each refresh is counting and sum the number writed by image, but I need to embed this counter in another pages, something like:
<img src='https://countersite.com.br/img-counter-385503.jpg'>
Here is a image of the counter working:
UPDATED
I need help to merge the image already created with the numbers (0.png, 1.png...) into one image (counter1.png).

How to grab specifc data from another website with PHP's fgetcsv and fopen

I'd like to be able to grab data such as list of articles from yahoo finance. At the moment I have a local hosted webpage that searched yahoo finance for stock symbols (E.g Nok), It then returns the opening price, current price, and how far up or down the price has gone.
What I'd like to do is actually grab related links that yahoo has on the page - These links have articles related to the share price...E.g https://au.finance.yahoo.com/q?s=nok&ql=1 Scroll down to headlines, I'd like to grab those links.
At the moment I'm working off a book (PHP Advanced for the world wide web, I know it's old but I found it laying around yesterday and it's quite interesting :) ) In the book it says 'It's important when accessing web pages to know exactly where the data is' - I would think by now there would be a way around this...Maybe the ability to search for links that have a particular keyword in it or something like that!
I'm wondering if theres a special trick I can use to grab particular bits of data on a webpage?? Like crawlers, they are able to grab links that are related to something.
It would be great to know how to do this, then i'd be able to apply it to other subjects in the future.
Ill add my code that I have at the moment. This is purely for practise as I'm learning PHP in my course :)
##getquote.php
<!DOCTYPE html PUBLIC "-//W3// DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Get Stock Quotes</title>
<link href='css/style.css' type="text/css" rel="stylesheet">
</head>
<h1>Stock Reader</h1>
<body>
<?php
//Read[1] = current price
//read[5] = opening price
//read[4] = down or up whatever percent from opening according to current price
//Step one
//Begin the PHP section my checking if the form has been submitted
if(isset($_POST['submit'])){
//Step two
//Check if a stock symbol was entered.
if(isset($_POST['symbol'])){
//Define the url to be opened
$url = 'http://quote.yahoo.com/d/quotes.csv?s=' . $_POST['symbol'] . '&f=sl1d1t1c1ohgv&e=.csv';
//Open the url, if can't SHUTDOWN script and write msg
$fp = fopen($url, 'r') or die('Cannot Access YAHOO!.');
//This will get the first 30 characters from the file located in $fp
$read = fgetcsv ($fp, 30);
//Close the file processsing.
fclose($fp);
include("php/displayDetails.php");
}
else{
echo "<div style='color:red'>Please enter a SYMBOL before submitting the form</div>";
}
}
?>
<form action='getquote.php' method='post'>
<p>Symbol: </p><input type='text' name='symbol'>
<br />
<input type="submit" value='Fetch Quote' name="submit">
</form>
<br />
<br />
##displayDetails.php
<div class='display-contents'>
<?php
echo "<div>Todays date: " . $read[2] . "</div>";
//Current price
echo "<div>The current value for " . $_POST["symbol"] . " is <strong>$ " . $read[1] . "</strong></div>";
//Opening Price
echo "<div>The opening value for " . $_POST["symbol"] . " is <strong>$ " . $read[5] . "</strong></div>";
if($read[1] < $read[5])
{
//Down or Up depending on opening.
echo "<div>" .strtoupper($_POST['symbol']) ."<span style='color:red'> <em>IS DOWN</em> </span><strong>$" . $read[4] . "</strong></div>";
}
else{
echo "<div>" . strtoupper($_POST['symbol']) ."<span style='color:green'> <em>IS UP</em> </span><strong>$" . $read[4] . "</strong></div>";
}
added code to displayDetails.php
function getLinks(){
$siteContent = file_get_contents($url);
$div = explode('class="yfi_headlines">',$siteContent);
// every thing inside is a content you want
$innerContent = explode('<div class="ft">',$div)[0]; //now you have inner content of your div;
$list = explode("<ul>",$innerConent)[1];
$list = explode("</ul>",$list)[0];
echo $list;
}
?>
</div>
I just the same code in - I didn't really know what I should do with it?!
Idk for fgetcsv but with file_get_contents you can grab whole content of a page into a string variable.
Then you can search for links in string (do not use regex for html content search: Link regex)
I briefly looked at yahoo's source code so you can do:
-yfi_headlines is a div class witch wrappes desired links
$siteContent = file_get_contents($url);
$div = explode('class="yfi_headlines">',$siteContent)[1]; // every thing inside is a content you want
-last class inside searched div is: ft
$innerContent = explode('<div class="ft">',$div)[0]; //now you have inner content of your div;
repeat for getting <ul> inner content
$list = explode("<ul>",$innerConent)[1];
$list = explode("</ul>",$list)[0];
now you have a list of links in format: <li>text</li>
There are more efficient ways to parse web page like using DOMDocument:
Example
For getting content of a page you can also look at this answer
https://stackoverflow.com/a/15706743/2656311
[ADITIONALY] IF it is a large website: at the beggining of a function do: ini_set("memory_limit","1024M"); so you can store more data to your memory!

Relating PHP to source files

Sorry if the title is a bit vague, couldn't think of a better way to phrase it, anyway.
I'm attempting to make a page system for a website. Where you predictably start on page one, and then click page two and a different set of images appear. Each page has 12 images which are all thumbnail images. You click on the thumbnail image and lightbox brings up the high res shot.
My current problem is that I cannot link the PHP script to the images correctly. To me it looks correct but it doesn't work, so clearly not.
Info:
Thumbnails are name "thumb1.jpg" from 1-24, full images are name "img1.jpg" from 1-24
<?php
$imgs = array(12, 12, );
if(!empty($_GET["page"]))
{
$currPage = $_GET["page"];
}
else
{
$currPage = 1;
}
for($i = 1; $i<$imgs[$currPage-1]+1;$i++)
{
echo "<a href='albums/norfolk weekender 2012/img'.$imgs[$currPage][$i].'.jpg' rel='lightbox[group]'><img src='albums/norfolk weekender 2012/thumb'.$imgs[$currPage][$i].'.jpg'/></a>";
}
?>
.
Anyway, I'm unsure why it doesn't work, and any help will be much appreciated.
Ta.
John.
'.$imgs[$currPage][$i].'
It looks like you should be using " instead of ' to wrap round this embedded variable both times you reference it in the code, since your echo is distinguished by ".
Either way, looking at this it doesn't seem this array structure you've got going on is working.
"albums/norfolk weekender 2012/img".$imgs[$currPage][$i].".jpg"
Have you not considered something like this (care, it's rough); with $pageNo representing $_GET["page"]
for ( $i = ($pageNo - 1) * 12 + 1; $i <= ($pageNo * 12); $i++ )
{
echo "<a href='albums/norfolk weekender 2012/img".$i.".jpg' rel='lightbox[group]'><img src='albums/norfolk weekender 2012/thumb".$i.".jpg'/></a>";
}
If presentation (i.e. checking to see if an image exists before displaying it) is a major concern, you could use file_exists( filename ). By creating an Array like this...
$imgs = array(12, 12, );
...you are simply creating an array containing two elements of 12 (and possibly a blank element, I'm not entirely sure.) I think where you went wrong is you attempted to declare the size in the "constructor" of Array; in PHP this is not the case.

A fast way (or alternate way) to dynamically load 40000 links in an image map?

I'm bringing back a GD Image which is generated from user information in a database, now on the page where this image is viewed. I have the following area map for the image generated by the same sort of query to create a link to that users profile. However, there are a possible 40000 users in the database... anyway, what I have IS working, but as you can imagine it takes a long while for it to load.
<map id="pixel" name="pixel">
<?
$map_x_1 = 0;
$map_y_1 = 0;
$map_x_2 = 5;
$map_y_2 = 5;
$block_num = 1;
while ($map_y_2 <= 1000) {
while ($map_x_2 <= 1000) {
$actual_x_cood = $map_x_1+1;
$actual_y_cood = $map_y_1+1;
$grid_search = mysql_query("SELECT *
FROM project
WHERE project_x_cood = '$actual_x_cood' AND project_y_cood = '$actual_y_cood'") or die(mysql_error());
$block_exists = mysql_num_rows($grid_search);
if ($block_exists == 1) {
echo("<area shape=\"rect\" coords=\"$map_x_1, $map_y_1, $map_x_2, $map_y_2\" href=\"/block/$block_num/\" alt=\"\" title=\"$block_num\" />\n");
} else {
echo("<area shape=\"rect\" coords=\"$map_x_1, $map_y_1, $map_x_2, $map_y_2\" href=\"/block/$block_num/\" alt=\"\" title=\"$block_num\" />\n");
}
$map_x_1 = $map_x_1 + 5;
$map_x_2 = $map_x_2 + 5;
$block_num = $block_num+1;
}
$map_y_1 = $map_y_1 + 5;
$map_y_2 = $map_y_2 + 5;
$map_x_1 = 0;
$map_x_2 = 5;
}
?>
</map>
I was thinking about just throwing in a quick jquery load screen over the top in a div and then hiding it once the page has fully loaded so it looks nicer. But I'm not really too happy with the idea of it since I would just like to load it faster.
So is there a quicker way to do it, maybe PHP? JS? Thanks!
You should consider using an input:image element. It will retreive the x-y coords as built-in functionality, and can be used in JavaScript or as part of the submission of a form.
After receiving the x-y coords, you can use a quad-tree or other algorithm for quick spacial-searching in your dataset.
you should capture the coordinates in the image map (easy with jquery) and pass it to the server which then calculates the user clicked.
i did something similar with a rate bar that hat hat 100 values (1-100%). but it was done in prototype so the code wont help you much.
small hint: i had to substract the left position of the container from the absolute click position.
in php and forms its not so flexible but far easier. you can just specify an input type image. the coordinates will be passed as post variables.
something like
will suffice

Scraping non-absolute URL

I am trying to scrape www.weather.bm. I want all 10 radar images, but I can only get one (the image updates regularly) and it's not a absolute image url. I was hoping I could use the image as a image slideshow like the link but dont know how. Also, how can I remove images/Radarlegend.png? I just need the radar images.
Here is my code:
include('simple_html_dom.php');
$html = file_get_html('http://www.weather.bm/radarMobile.asp');
foreach($html->find('img') as $element)
echo $element->src . '<br>'
My output is:
<div id="main">
images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1556.jpg<br>images/Radarlegend.png<br></div>
</div>
There is a list of all ten images is in the JavaScript (formatting changes mine):
radarFileNames = new Array(
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1446.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1456.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1506.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1516.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1526.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1536.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1546.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1556.jpg',
'images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-2011-01-04-1606.jpg');
A simple search through for the line containing radarFileNames = new Array will return this line. Then you can extract the URLs with two preg_split()s: first on \(|\), then split the second token on ', '. Finally, prefix http://www.weather.bm/ to the URLs.
$localOffset = "+2 Hours"; //change this to your local offset from the image times you need. for me (CST) it's 2 hours.....
$start= strtotime("-90 Minutes " . $localOffset); // go back 90 minutes (The limit of the available images)
$start=($start-($start % (600))+(60*6)); //go to the next earlier 6 minute mark (all images appear to be at the 6 minute mark))appear to be at the 6 minute mark))
for($x=1;$x<=9;$x++){
$DateTime = date("Y-m-d-Hi", $start); // set the image time we want.
$fName = ("http://www.weather.bm/images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-$DateTime.jpg"); // set the filename
echo" $min <img src='$fName' alt='$fName'/><br/>"; // echo (or add to a stack or variable...) your image node
$start+=(600);//add 10 minutes
}

Categories