image click counter - php

Is there a way to count how many times an image how been clicked. And once the image is clicked have it displayed?
I am currently pulling random images from a database and want to show which is has been clicked the most.
<html> <body>
<div style="float:left"> <?php // Connect to the database mysql_connect ('localhost', 'root') ; mysql_select_db ('links');
// Number of images $num_displayed = 1 ;
// Select random images from the database $result = mysql_query ("SELECT * FROM links ORDER BY RAND() LIMIT $num_displayed");
// For all the rows that are selected while ($row = mysql_fetch_array($result))
// Display images { echo "<img src=\"".$row["image"]."\" border=0 alt=\"".$row["text"]."\">"; } ?> </div>
<div style="float:left; margin-left:100px"> <?php include("image2.php"); ?>
</div> </body> </html>
thanks.

Create a trigger in image table to count selects
CREATE TRIGGER `database_name`.`trigger_name` BEFORE SELECT INSERT ON
`database_name`.`images_table_name` FOR EACH ROW
BEGIN
UPDATE
`database_name`.`images_table_name`
SET
`database_name`.`images_table_name`.`counter` = `database_name`.`images_table_name`.`counter` + 1
WHERE
`database_name`.`images_table_name`.`id` = NEW.`id`;
END$$
Perform your querys ordering by counter field.
To register clicks, implements a click tracker quering an update on second field, like 'clicks'

You can do this using javascript:
In head tag:
<script type="text/javascript">
var count = 0;
function changevar(){
count = count + 1;
if (count == 3) {
alert('Done');
}
}
</script>
In body tag:
<img src="image.png" onClick="changevar()"/>

How about counting each time the image is displayed? This is an option if and only if there are no other images which can be to it in the way an image album viewer works.
Use php to render the image, and run a small script in there which increments the number of times this image has been clicked (or displayed). Alternatively you could create an entry for each time the image is displayed saving lots more possibly interesting information such as image, last_view, ip, count and or referrer (if it works;untested). Recording the IP would allow you to keep track of unique views with count showing you how many times they reviewed the image; this depends on how you implement it.
$name = trim($_GET['img']);
if (!isset($_GET['img'] || empty($name)) {
// Check url var wasn't omitted or typed incorrectly.
die("Image not specified.");
}
// This is just an example path. It would be a good idea to specify a path
// like this to ensure that people don't try and use it to display files
// that you wouldn't want them too.
//eg. images you don't want to keep records of.
$image = "/images/$name";
$date = time();
$ip = $_SERVER['REMOTE_ADDR'];
$ref = $_SERVER['HTTP_REFERER'];
if (!file_exists($image)) {
// Ensure that something exists at $image
die("Invalid image.");
}
$f = fopen($image, 'r');
if (!$f) {
// Make sure that the contents of the file can be opened.
die("Unable to open image.");
}
$info = #imagegetsize($image);
if (!$info) {
// This is to make sure that the $image contains a path
// to an image not just a regular file.
die("Invalid image type.");
}
Header("Content-type: {$info['mime']}");
echo fread($f, filesize($image));
fclose($f);
/****************
* Script for saving image 'click' information.
***************/
exit;
Display the image like this
<img src="/image.php?img=example.png" />
If you are having troubles and images are displaying correctly, open the path in your browser to see the errors.

Related

Click on an image stored in a MySQL database table and get additional row content for that image

I have created a members.php page that connects to a database table. The table has the following fields: id, username, profile image.
The following PHP code displays the profile image for each user in rows of 6 and allows each image to be clickable.
<?php
// The code below will display the current users who have created accounts with: **datemeafterdark.com**
$result=mysql_query("SELECT * FROM profile_aboutyou");
$row1 = mysql_fetch_assoc($result);
$id = $row1["id"];
$_SESSION['id'] = $id;
$profileimagepath = $row1["profileimagepath"];
$_SESSION['profileimagepath'] = $profileimagepath;
$count = 0;
while($dispImg=mysql_fetch_array($result))
{
if($count==6) //6 images per row
{
print "</tr>";
$count = 0;
}
if($count==0)
print "<tr>";
print "<td>";
?>
<center>
<img src="<?php echo $dispImg['profileimagepath'];?>" width="85px;" height="85px;">
</center>
<?php
$count++;
print "</td>";
}
if($count>0)
print "</tr>";
?>
This is all great, however, when I click on the image that loads it re-directs me to: viewmemberprofile.php which is what it is supposed to do. But it always displays the same image with the same id value (i.e.) 150 no matter which image I click. What I would like to have happened is. If I click on an image with id 155 etc... it will display content for that image data field not consistently the same image data regardless of which image I click.
Your help and guidance would be greatly appreciated. Thank you in advance.
One thing that I forgot to mention is that I do use sessions so... when I am re-directed to the viewmemberprofile.php page I use the following code to aide in getting the data that I need from the table.
<?php
$id = $_SESSION['id'];
echo($id);
?>
<?php
echo('<br>');
?>
<?php
$profileimagepath = $_SESSION['profileimagepath'];
?>
<img src="<?php echo($profileimagepath);?>" width="50px;" height="50px;">
I have yet to impliment the suggested solution.
You need to pass the ID of the row to viewmemberprofile.php, e.g.:
<a href="viewmemberprofile.php?id=<?= $dispImg['profileimagepath'] ?>">
And viewmemberprofile.php needs to select that row from the DB:
SELECT * FROM profile_aboutyou WHERE id = $_GET['id']
The above SQL statement is pseudo-code; you need to write actual code to accomplish what it is describing, preferably using parameterized queries.

Images not displaying from database and file

i Have set up a site that lets user upload images then those images get displayed back on the home screen. but i hit a wall just now so i got past to letting the user upload an image then that images gets saved to a folder and a database but how can i do it so the image gets displayed on the home screen.
<?php
// Connect to database
$errmsg = "";
if (! #mysql_connect("localhost","alfred1000351","*******")) {
$errmsg = "Cannot connect to database";
}
#mysql_select_db("drp_2cgih5o233");
$q = <<<CREATE
create table pix (
pid int primary key not null auto_increment,
title text,
imgdata longblob)
CREATE;
#mysql_query($q);
// Insert any new image into database
if ($_REQUEST[completed] == 1) {
// Need to add - check for large upload. Otherwise the code
// will just duplicate old file ;-)
// ALSO - note that latest.img must be public write and in a
// live appliaction should be in another (safe!) directory.
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
if (strlen($instr) < 149000) {
mysql_query ("insert into pix (title, imgdata) values (\"".
$_REQUEST[whatsit].
"\", \"".
$image.
"\")");
} else {
$errmsg = "Too large!";
}
}
// Find out about latest image
$gotten = #mysql_query("select * from pix order by pid desc limit 1");
if ($row = #mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
} else {
$errmsg = "There is no image in the database yet";
$title = "no database image available";
// Put up a picture of our training centre
$instr = fopen("../wellimg/ctco.jpg","rb");
$bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>
<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
</body>
</html>
Here is my toughts:
Do not suppress warnings what you get from DB. They are real, and needed. Remove all #-characters from the front of DB-calls. If you get any notices, warnings, errors do not suppress them, correct them.
If you are making new code, consider using PDO as DB API, not the old, deprecating PHP MySQL API. It's as easy as MySQL API to use.
You only want try to create table only once, remove it from code which is executed many times.
You should check if $_REQUEST parameters exists, and not compare them if they do not. Also you need to put the parameter names in quotes, otherwise PHP thinks you are using constants, which you are not. So line if ($_REQUEST[completed] == 1) { must be fixed to if(isset($_REQUEST['completed']) && $_REQUEST['completed'] == 1) {. Same appies to whatisit and gim -params.
The code if (strlen($instr) < 149000) { does not work as intented, you cannot get length of resource. You are probably looking for this functionality: if (strlen($_FILES['imagefile']['size']) < 149000) {.
Same (as in step 4) with $row s you need to put the literas in quotes, so fix those lines as: $title = htmlspecialchars($row['title']); $bytes = $row['imgdata'];
Othewise than that it should work. However, it contains DB-security hole, which can lead to compromize your website, so I recommend you NOT to put this to any real site. Just for your own/friends fun.

Displaying specific image and MySql information when clicked on

I am building an image uploading website. Images are uploaded to a directory on the server and data such as the filename is stored in a MySql table. I have created a 'gallery' page which displays all the uploaded images as thumbnails. When a user clicks on one of the images, it takes them to 'image.php' page, which will display the image full size and echo information such as the username of the person who uploaded the image etc.
I am unsure as to what would be the correct way of displaying the image. The images in my MySql table have unique ID's which I'm guessing will have to be manipulated in some way, but how do I would I get the ID of the photo that has been clicked on into the 'image.php' MySql query?
Hope this has been explained well enough. Thanks in advance.
gallery.php page... (exclusing database connections etc.)
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM photos");
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<section class="thumbnails group">
<?php Echo "<img src=http://.../thumbs/tn_".$info['filename'] .">"; }?>
</section>
image.php page...
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM photos WHERE 'id' = ??");
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<section class="main-image group">
<?php echo "<img src=http://.../images/".$info['filename'] .">"; }?>
</section>
You can simply pass the ID of the image through in the querystring
<img src="/path/to/thumbnail">
In your image.php page, you can retrieve the ID like this (assuming it's an integer):
$imageID = intval( $_GET["image"]);
You should then be able to retrieve the path to the image and display it.
# liquorvicar answer is correct one, there's no ambiguity in his answer! well,
try this;
<?php Echo "<img src=http://...thumbs/tn_".$info['filename'] .">"; }?>
on image.php page
$id=intval($_REQUEST['id'])
now you have id for that specific image show its related info.

php generate image?

How can i use php to get an image url from database (based on user id) and display it out as an image.
http://mysite.com/img.php?id=338576
The code below shows a php script goes to a database , check whether the specific user(using the id in the link above) exist then get the image url out of that user's row.
<?php
//connect to database
include ("connect.php");
//Get the values
$id = mysql_real_escape_string($_GET['id']);
//get the image url
$result = mysql_query("SELECT * FROM users WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$img_url = row['imgurl'];
mysql_close($connect);
}
else{
}
?>
The $Img_url is an actual image link www.asite.com/image.jpg
The problem is how can i use php to make an image from the image link($img_url)? By which http://mysite.com/img.php?id=338576 will turn into an image.
I hope someone could guide me
Thanks!
The easiest way:
header('Location: url/to/image');
You could also proxy the request, which uses your bandwidth:
echo(file_get_contents('url/to/image'));
This is pretty basic stuff. Am I understanding you correctly? I would just do this:
<?php
$img_html = '<img src="' . $img_url . '" />';
echo $img_html;
?>
Or check this answer:
How do I script a php file to display an image like <img src="/img.php?imageID=32" />?

Making album-viewer like facebook

I am working on making a album-viewer like facebook.
I have made the "setup", you can see the photo, what album its in and so, now I would like to make the "next" "previous" buttons work.
I have seen them using preloading while viewing a current, and i wish to accomplish something like that.
But first of all, how can I make the "next"? What are the procedure to make the "next" work.
With this I mean how should I code it, so it knows which picture is next? I would like to sort it from the date(order by date), so the next should be newer than the current date, and previous older than the current date.
My database looks like this:
album
id uID title
album_photos
id aID uID photo date
aID holds the id of the album(album ID), uID holds the id of the user(userID).
I also want to make use of javascript too. Make an ajax request, instead of refreshing whole page.
So my question is:
What is the procedure of making next/prev button, if I would like to make it work after date DESC, how does the javascript look like? An ajax request to file.php, that are grabbing the latest image from the database and then on success it replace the current photo and show it? What about the adressbar, in facebook the adressbar changes align with loading new photo.
Any well explained answer for procedure of making this, will accept the answer
This here will load images from the database using ajax (next/previous). Also includes guides and a preloader (hosted here http://www.preloaders.net/). Let me know if you have any questions.
Here you go. these are 3 files
index.php ...display page
ajax.php ...read database for images
show.php ...loads images
just remember to set host, user, password & databasename in ajax.php
copy & paste these:
1. index.php
<?php
include("ajax.php");
?>
<script type="text/javascript" src="JQUERY/jquery.js"></script>
<script>
var ID = "<?php echo $id; ?>";
var inc = ID + 1;
var dec = ID;
var totalpages = "<?php echo $totalpages + 1; ?>";
$(function(){
$('.loader').hide();
<!-- np = next & prev button functions -->
$('.np').click(function() {
if($(this).attr('id') == "next") {
$(this).attr('push', inc++);
if($(this).attr('push')<totalpages) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
dec = inc - 2;
$('#images').hide();
}
}
else if($(this).attr('id') == "prev") {
$(this).attr('push', dec--);
if($(this).attr('push')>-1) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
inc = dec + 2;
$('#images').hide();
}
}
});
});
<!-- this function is called after ajax send its request -->
function AjaxFunc(return_value) {
$('#images').html(return_value);
$('.loader').hide();
$('#images').show();
}
</script>
<div id="images">
<!-- loads default numbers of images. whats inside here will change once you click next or prev -->
<?php
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
</div>
<!-- next & previous buttons -->
<a class="np" id="prev" push="<?php echo $id; ?>" href="#">Prev</a>
<a class="np" id="next" push="<?php echo $id + 1; ?>" href="#">Next</a>
<!-- preloader. hidden on start. will show while images load -->
<img class="loader" src="http://www.preloaders.net/generator.php?image=75&speed=5&fore_color=000000&back_color=FFFFFF&size=64x64&transparency=0&reverse=0&orig_colors=0&uncacher=26.066433149389923"/>
2. ajax.php
<?php
//id is tjhe page number. it is 0 by default. while clicking next/prev, this will not change. set it like this: file?id=0
$id = $_GET['id'];
//connect to the databsae
$host="localhost";
$user = "username";
$password = "";
$database = "database_name";
$connect = mysql_connect($host, $user, $password) or die("MySQL Connection Failed");
mysql_select_db($database) or die ("Database Connection Fail");
//set your the limit of images to be displayed
$limit = 5;
//push images into array
$q = mysql_query("SELECT * FROM image_table");
$num = mysql_num_rows($q);
while($r = mysql_fetch_array($q)) {
$imagearray[] = "<img src='"
.$r['IMAGE_URL']
."'/>";
}
//will determine total number of pages based on the limit you set
$totalpages = ceil($num/$limit) - 1;
?>
3. show.php
<?php
include("ajax.php");
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
If you are sorting your photos by date DESC and you got the current photos date do the following:
To find the next photo: Order your photos by date DESC and select the first photo whos date is smaller than the date of the current photo. Fetch only the first one.
To find the prev photo: Order your photos by date ASC and select the first photo whos date is greater than the date of the current photo. Fetch only the first one.
Construct the SQL-Statements for this by yourself.

Categories