We help IT Professionals succeed at work.

Galleria jquery + php

Toube
Toube asked
on
458 Views
Last Modified: 2013-01-15
Hi,

I using the jquery Galleria to view my photos.
Problem that I'm having is that I need to implement a script that calls on a .php file and the php file then updates the database when a user has viewed the picture.

I've attached a example file that is working with Highslide jquery photoalbum. I'm guessing the kind of a script is needed with Galleria?

Help is needed.

Regards,

Toby
example.txt
Comment
Watch Question

Author

Commented:
anyone?

Commented:
Hi,

Maybe it is an option to get every image through php, so your image source will be something like this:

/php/showimage.php?image=my_image.jpg

Now you can use php to process a view and present the image.

php code (not tested)

<?php
// The above must be the VERY FIRST LINE OF THE FILE!

// Check whether the user is correctly logged in, etc.
// at this point - that depends on YOUR reasons for
// doing this, of course

// Figure out which image to send them
$image = $_GET['image'];
// MAKE SURE IT IS SAFE! Allow only letters,
// numbers, and underscores in the filename,
// don't let them sneak around with ../ and
// download other files on the system!
if (!preg_match("\^\w+$\", $image)) {
  header("Content-type: image/gif");
  readfile("/path/to/access_denied.gif");
  exit(0); 
}

// log a view here
  
// OK, they're cool, send them the image.
// /path/to/my/images should be OUTSIDE
// your web space, somewhere else in the
// file system, because the whole point is to
// keep people from downloading what they
// don't have permission to download!
header("Content-type: image/jpeg");
readfile("/path/to/my/images/$image");
exit(0);
?>

Open in new window


Greetz,
walter

Author

Commented:
Hi Walter,

I'm not sure I'm following you here. Atm I'm using php to fetch all the images form my database using a while loop:

echo ('<div id="galleria">'); 
$index = 0;
$j = 0;
$img = $startvalue + $img;
	
echo ('<div id="galleria">'); 
while($index < $imagesinthispage){
	
$imageid_ = mysql_result($resultsqlquery, $index, photoid);
$thumbnail_ =  mysql_result($resultsqlquery, $index, thumbnailname);
$phototext_ =  mysql_result($resultsqlquery, $index, phototext);
$text_ = html_entity_decode($phototext_);
$text_original = html_entity_decode($phototext_);
$text_ = substr($text_,0,20);
$count_ = strlen($phototext_);
$date = mysql_result($result, $index, addtime);
$updatedtime = mysql_result($resultsqlquery, $index, date);
$eventid = mysql_result($resultsqlquery, $index, photoevent_);
$folder_ = mysql_result($resultsqlquery, $index, folder);
$filename_ = mysql_result($resultsqlquery, $index, filename);
$number = preg_replace('/[^0-9]/', '', $filename_);

if ($number > 1000)
{
	$number = $number1[strlen($number)-1];
}

echo "<div style=\"float: left; border: 1px solid #dadada; padding: 3px; margin: 5px;\">";
echo "<a href=\"albumi/$folder_/$filename_\"><img src=\"albumi/$folder_/$thumbnail_\" style=\"border: none; padding: 5px;\" title=\"$text_original\"/></a></div>".PHP_EOL;

$number = $number - 1;
$index++;
$img++;
updatelastreadphoto($eventid,$pid,$count_views,$count_picture);		
}
echo ('</div>'); // end <div id="galleria">
echo "<script language=\"javascript\" type=\"text/javascript\">
Galleria.run('#galleria')
Galleria.configure({
    imageCrop:false
})";
echo "</script>"; 
echo "</div>";

Open in new window

Commented:
Hi,

I am sorry, I misunderstood. Thought you needed a click counter. Hmm lets see. Maybe is is possible to use one of the Galleria events to log an image view.

There is an event called 'image' that tracks the image that is currently displayed. When this even is triggered, you could make an ajax call to a PHP script that logs the amount of views of the image. The imagename can be passed as a parameter.

http://galleria.io/docs/api/events/#list-of-galleria-events

greetz,
walter

Author

Commented:
Hi,

yes that what I want to do.. but problem is that I'm not sure how to use it combined with ajax?

Regards,

Toby

Commented:
Hi toby,

Can you profide an online example of your gallery (with the php rendered gallery)? Than I can use the html source and try to implement this for you.

greetz,
walter

Author

Commented:
yes:

intra.tobiasfransman.net
user: guest
pass: guest321

from there you find the albums under albumi. ex.
http://intra.tobiasfransman.net/albumi/index.php?id=2013&show=48

Commented:
Hi toby,

I have been playing with the script that initializes Galleria, and I got it working. The Galleria Initialize script binds a function to the 'image' event. This events loads a php file in a div with the id "galleria_processview_message" (also place this div in your page, but you can hide it). The script shows some output to let you know that the imageview is processed.

Galleria.ready(function() {

		this.bind("image", function(e) {
			var imageLocation = e.imageTarget.src;
			var imagelocationArray = imageLocation.split("/");
			var imageName = $(imagelocationArray).last()[0];

			// process image view
			$("#galleria_processview_message").load("processview.php?img="+imageName, function(response, status, xhr) {
				if (status == "error") {
					$("#galleria_processview_message").html("<strong>ERROR: </strong> script error! ("+xhr.status + " " + xhr.statusText+")");
				}else if(status == "success"){
					// let php show the message
				}
			});
		});
		
	});

Open in new window


And the php script that processes the view is:

<?php

// you should validat the imput
$imagefile = $_GET['img'];

// process image click here


// show message for demo purposes
echo 'SUCCESS image '.$imagefile.' processed!';

?>

Open in new window


I have tested this, and this works for me. Hope this works for you.

greetz,
walter

Author

Commented:
Hi,

thanks and points coming your way, so how do implement this my own page meaning using the above code?

Thanks.

Toby
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Commented:
I was looking at your sourcecode, but do not wrap the #galleria div inside the #galleria_processview_message div. This should be an empty div just below yout #galleria div

Author

Commented:
Thanks again.
It will now show me SUCCESS image processed! but not the actual image variable $imagefile looks like its empty. And using this script the Galleria album stops working and only the image (filename) is opened without the galleria functioning around it.

Let me still clarify: I need to use Galleria showing images. When the user clicks on a thumbnail (before going galleria starts) Galleria should open the clicked thumbnail instead of now always opening the first image of the album.

Secondly when scrolling through the Galleria images and clicking next button in galleria, it should call upon a updateviewcount.php that would update the clicked images statistics  to my database. in normal php only use it like this under every image:

updatelastreadphoto($eventid,$pid,$count_views,$count_picture);       // calls the on a funtion that updates images statistics to the database :)

I can open a new case and give the points for this one If you like?

EDIT:

Got it a bit further..now the Galleria also works but i don't get the success message when viewing images..

Regards,

Toby

Author

Commented:
This is the part where the information should be sent to the database:
$("#galleria_processview_message").load("processview.php?img="+imageName, function(response, status, xhr

I tried it this way but still no image info getting updated to the database:
$("#galleria_processview_message").load("updateviewcount.php?id=$year&show=$eventid&img="+imageName, function(response, status, xhr)

the updateviewcount.php is a simple php file:
updateviewcount:

 include('db_connect.php');
  $yearid = $_GET['id'];
  $eventid = $_GET['show'];
  $imageid = $_GET['img'];
  $count = $_GET['count'];
  $test= 'eventid='.$eventid.'imageid='.$imageid.'count='.$count;

  if($count == 1)
 {
   $getid = "select id from photos where photoevent_='$eventid'
             order by filename limit 1 offset $imageid";
   $result = mysql_query($getid);
   $dbimageid = mysql_result($result,0,id);

    $sql = "UPDATE photos set count_views = (count_views + 1 ), updatetime = updatetime WHERE id = '$dbimageid'";
    mysql_query($sql);
    $loggeduserid_ = $_SESSION['users_id'];
	$microseconds_ = ((double) microtime()) * 1000000;

    // check if user has already row for current header
    $lastreadchecksql = "SELECT 1 FROM photos_read WHERE user_r ='$loggeduserid_' AND eventid_ = '$eventid' AND photoid_ = '$dbimageid'";
    $lastreadcheck = mysql_query($lastreadchecksql);
    $num = mysql_num_rows($lastreadcheck);
    //echo('num='.$num);

    // if not found, add new row
    if($num == 0)
    {
        $insertlastreadsql = "INSERT INTO photos_read(eventid_,photoid_,user_r,lastreadmicrosec) VALUES
            ('$eventid','$dbimageid', '$loggeduserid_','$microseconds_')";
        $insertlastread = mysql_query($insertlastreadsql);
    }
    // else update old row
    else
    {
        $updatelastreadsql = "UPDATE photos_read SET lastread = now(), lastreadmicrosec = '$microseconds_' WHERE eventid_='$eventid' AND photoid_='$dbimageid' AND user_r='$loggeduserid_'";
        $updatelastread = mysql_query($updatelastreadsql);

    }
}

Open in new window

Commented:
Hi,

Make sure that your variables in jquery are existing variables:

$year, $eventid need to be defined in jquery, if not it will send empty variables.

greetz,
walter

Author

Commented:
Hi,

ok could try that. How do I call them in jquery? Sorry.. php is more my thing not jquey and javascripting :)

Commented:
Hi,

In the load command:

$("#galleria_processview_message").load("updateviewcount.php?id=$year&show=$eventid&img="+imageName, function(response, status, xhr)

Open in new window


You use these variables. If you need to set them using php you have to use something like this (in the jquery script):

<?

// use php to define javascript variables
echo 'var year = '.$year;
echo 'var eventid = '.$eventid;

?>

$("#galleria_processview_message").load("updateviewcount.php?id="+year="&show="+eventid+"&img="+imageName, function(response, status, xhr)

Open in new window

Author

Commented:
Ok,

using the script lik this but still no updates being made to the database when viewing the images:

echo ('<div id="galleria">');  

	$index = 0;
	$j = 0;
	$img = $startvalue + $img;
	
	 while($index < $imagesinthispage){	
	 $imageid_ = mysql_result($resultsqlquery, $index, photoid);
	 $thumbnail_ =  mysql_result($resultsqlquery, $index, thumbnailname);
	 $phototext_ =  mysql_result($resultsqlquery, $index, phototext);
	 $text_ = html_entity_decode($phototext_);
	 $text_original = html_entity_decode($phototext_);
     $text_ = substr($text_,0,20);
     $count_ = strlen($phototext_);
     $date = mysql_result($result, $index, addtime);
     $updatedtime = mysql_result($resultsqlquery, $index, date);
     $eventid = mysql_result($resultsqlquery, $index, photoevent_);
     $folder_ = mysql_result($resultsqlquery, $index, folder);
     $filename_ = mysql_result($resultsqlquery, $index, filename); 
	$number = preg_replace('/[^0-9]/', '', $filename_);
		if ($number > 1000)
		{
			$number = $number1[strlen($number)-1];
		}
		echo "<div style=\"float: left; border: 1px solid #dadada; padding: 3px; margin: 5px;\">";
		echo "<a href=\"albumi/$folder_/$filename_\"><img src=\"albumi/$folder_/$thumbnail_\" style=\"border: none; padding: 5px;\" title=\"$text_original\"/></a></div>".PHP_EOL;

		$number = $number - 1;
		$index++;
		$img++;
		
updatelastreadphoto($eventid,$pid,$count_views,$count_picture);		
}
echo ('</div>'); // end <div id="galleria">
echo ('<div id="galleria_processview_message"></div>');

?>


<script language="javascript" type="text/javascript">

	Galleria.run('#galleria');

	Galleria.configure({
		imageCrop:false
	});

</script>
<script language="javascript" type="text/javascript">	
	
	Galleria.ready(function() {

<?php

// use php to define javascript variables
echo 'var year = '.$year;
echo 'var eventid = '.$eventid;

?>
	
		this.bind("image", function(e) {
			var imageLocation = e.imageTarget.src;
			var imagelocationArray = imageLocation.split("/");
			var imageName = $(imagelocationArray).last()[0];

			// process image view
			$("#galleria_processview_message").load("updateviewcount.php?id="+year="&show="+eventid+"&img="+imageName, function(response, status, xhr){
				if (status == "error") {
					$("#galleria_processview_message").html("<strong>ERROR: </strong> script error! ("+xhr.status + " " + xhr.statusText+")");
				}else if(status == "success"){
					// let php show the message
				}
			});
		});
		
	});
		
</script>

Open in new window

Commented:
Can you echo the transported variables in the target div?

Author

Commented:
What variables do you mean by transported?

Commented:
Hi,

I just took a look at the javascript source, I have made a little mistake. Setting the javascript variables with php should be like this (forgot the quotes):

<?

// use php to define javascript variables
echo 'var year = "'.$year.'"';
echo 'var eventid = "'.$eventid.'"';

?>

Open in new window


Sorry about that.

greetz,
walter

Author

Commented:
Still no go sry. Here's what the source gives out:

<script language="javascript" type="text/javascript">	
	
	Galleria.ready(function() {

var year = "2012"
var eventid = "48"
var imageid = "3686" // imageid from db
	
		this.bind("image", function(e) {
			var imageLocation = e.imageTarget.src;
			var imagelocationArray = imageLocation.split("/");
			var imageName = $(imagelocationArray).last()[0];

			// process image view
			$("#galleria_processview_message").load("updateviewcount.php?id="+year"&show="+eventid+"&img="+imageName, function(response, status, xhr){
				if (status == "error") {
					$("#galleria_processview_message").html("<strong>ERROR: </strong> script error! ("+xhr.status + " " + xhr.statusText+")");
				}else if(status == "success"){
					// let php show the message
				}
			});
		});
		
	});
		
</script>

Open in new window

Commented:
Needs a + after '+year'

Author

Commented:
Thanks.

$("#galleria_processview_message").load("updateviewcount.php?id="+year+"&show="+eventid+"&img="+imageName, function(response, status, xhr){

still no go..hmph..

Author

Commented:
This is a hard one.. but not unsolvable :)

Commented:
Can you see if PHP receives the get variables?

Author

Commented:
Hi,

I think the problem could be in my updateviewcount.php file: because now the update fails to update the because it can not get the imageid from the database:

These are echoed out of the updateviewcount.php file:

eventid=53
imageid=002.jpg
count=1

select id from photos where photoevent_='53' order by filename limit 1 offset 002.jpg

UPDATE photos set count_views = (count_views + 1 ), updatetime = updatetime WHERE id = ''

So it cannot find the photoid using the 002.jpg value.. what if we could try to get that same imagenumber without the .jpg only the 002 part?

<?php
 include('/home/tobiasfr/include/db_connect.php');

  $yearid = $_GET['id'];
  $eventid = $_GET['show'];
  $imageid = $_GET['img'];
  $count = $_GET['count'];
  $test= 'eventid='.$eventid.'<br/>imageid='.$imageid.'<br/>count='.$count.'';
echo $test;
  if($count == 1)
 {
   $getid = "select id from photos where photoevent_='$eventid' order by filename limit 1 offset $imageid";
   echo $getid;
   $result = mysql_query($getid);
   $dbimageid = mysql_result($result,0,id);

    echo $sql = "UPDATE photos set count_views = (count_views + 1 ), updatetime = updatetime WHERE id = '$dbimageid'";
    mysql_query($sql);
    $loggeduserid_ = $_SESSION['users_id'];
	$microseconds_ = ((double) microtime()) * 1000000;

    // check if user has already row for current header
    $lastreadchecksql = "SELECT 1 FROM photos_read WHERE user_r ='$loggeduserid_' AND eventid_ = '$eventid' AND photoid_ = '$dbimageid'";
    $lastreadcheck = mysql_query($lastreadchecksql);
    $num = mysql_num_rows($lastreadcheck);
    //echo('num='.$num);

    // if not found, add new row
    if($num == 0)
    {
        $insertlastreadsql = "INSERT INTO photos_read(eventid_,photoid_,user_r,lastreadmicrosec) VALUES ('$eventid','$dbimageid', '$loggeduserid_','$microseconds_')";
        $insertlastread = mysql_query($insertlastreadsql);
    }
    // else update old row
    else
    {
        $updatelastreadsql = "UPDATE photos_read SET lastread = now(), lastreadmicrosec = '$microseconds_' WHERE eventid_='$eventid' AND photoid_='$dbimageid' AND user_r='$loggeduserid_'";
        $updatelastread = mysql_query($updatelastreadsql);

    }
}


?>

Open in new window

Author

Commented:
Yes.. I removed .jpg from updateviewcount.php and it started working :)

Now I still have one more little dilemma.. how can I make galleria open the selected clicked thumbnail when clicked on and not the first image like it does now..? Shall I open a new case.. or shall i use this:
https://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_27988722.html

Author

Commented:
Got it working also :)
Thanks for your support, much appreciated.
Regards,
Toby

Commented:
Hi toby,

sorry I could'nt react on your posts the last view days, I was offline for a view days. Great that you have found the solution.

greetz
walter

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.