PHP create embed image from database position - php

I searched Google and Stackoverflow but could not find the answer. Probably it is because I am searching for the wrong question. Without the right question, it’s hard to get the right answers. So I hope someone can help me.
I have created a top 20 list where people can rank their favourite website (I know it is not that original, but I do it to learn php)
Websites can be added to a database and are sorted based on votes. Each website has its own unique ID in the database, name and position.
What I cannot figure out is how to do the following.
Next to the list displayed show a get code button. This button will create a code for an image file that can be display on any website. For example:
<img src="http://www.example.com/counter.php?id=47"/>
or even better
<img src="http://www.example.com/47.gif"/>
To do this I need to make a php code, that can take the id and turn it into a nice image file and there I am stuck. I have seen twitter, feedburner, Technorati and over 100 other websites do this, but I cannot find out how.
I found this code that fakes feedburner, but I cannot figure out how to turn it into what I need.
<?php
//Send a generated image to the browser
create_image();
exit();
function create_image(){
//Create the image resource
$image = imagecreatefromgif('image.gif');
//Create text color
$brown = ImageColorAllocate($image, 0, 0, 0);
//Check for the get parameters
if (isset($_GET['count']) && is_numeric($_GET['count']))
$rank = $_GET['count'];
else
$rank = 20;
// Some Alignment Calculations
$bbox = imagettfbbox(8.5, 1,'verdana.ttf', $rank);
$xcorr = 0 + $bbox[2]; $xcorr = 31 - $xcorr;
//Add the number in brown color to the image
imagettftext($image,8.5,0,$xcorr,16,$brown,'verdana.ttf',$rank);
//Tell the browser what kind of file is come in
header("Content-Type: image/gif");
imagegif($image);
//Free up resources
ImageDestroy($image);}?>
Based on
www.mygeekpal.com/how-to-fake-your-feedburner-subscribers/
Using the above code and naming it counter.php I can fetch the position from the database and create
<img src='http://www.example.com/counter.php?count=".$array ['position']."' />
This takes the positon of a website from the database ($array has already been made to fetch) and creates an image with the position nr.
Works fine, but once the postion changes based on user ratings, the image will not show the correct data.
I hope someone can help. Thank you.
Summery
Basically what I am try to make is something that will show the most recent data, based on the ranking of the website. Just like showing the number of twitter followers, for example http://twittercounter.com/counter/?username=labnol or feedburner followers on http://feeds.feedburner.com/~fc/labnol
Both are images that show a number based on information in a database. But I want to create my own image, based on the rank of the website in the database.

Looking at your code it should update everytime the page is reloaded. Clear your browser cache.
If this fails i would check from where it is getting the Get['count'] data which im assuming is the Rank number of the site.
Can you check that the Get['Count'] data is updating as it should ?
Im not sure using an ARRAY in the URL is a good idea, why not use Sessions ?
This link might be of interest.
Sorry i have not been of more help.

This is what I have so far (I cannot edit this question from this computer, due to different cookies).
This is based on the help from
How to fetch data from database and display it in PHP?
thanks to
https://stackoverflow.com/users/353790/robertpitt
This seems to work
<?php
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM domains WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
}
$img_number = imagecreate(110,24);
$image = imagecreatefromgif('image.gif');
$backcolor = imagecolorallocate($img_number,254,46,212);
$textcolor = imagecolorallocate($image, 0, 0, 0);
imagefill($image,0,0,$backcolor);
$number = $user['position'];
Imagestring($image,9,26,4,$number,$textcolor);
header("Content-Type: image/gif");
imagegif($image);
ImageDestroy($image);
?>

Related

Why does avatar disappear upon revisiting page?

When a user submits a picture, the file is moved to a generated folder (for security purposes) with its file pathway recorded on the database. The picture displays correctly when the user stays on the page, but when the user exits from the page and revisits it, the picture they had previously uploaded fails to display (nothing displays at all). I seem to be unable to evoke the image from its location through its session variable and would like insight on this, thanks.
What I've tried:
echoing the avatar session variable -> image doesn't display at all
echoing the location of the image -> image displays when the user does not leave page after submitting. When the user leaves and
revisits the page, the image does not display. In its place, a
outline of where the image is suppose to register shows.
A lot of small tweaks (for instance, setting avatar session variable to location, and so on).
Here is my code:
$fln = $_FILES['avatar']['name'];
if(isset($fln) && tmp_name !== "") {
$tmp_name = $_FILES['avatar']['tmp_name'];
$fls = $_FILES['avatar']['size'];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//size checker
if($fls > 6500000) {
echo "Image must be less than 6.5 MB...";
}
else {
mkdir("user_data/user_avatars/$rdn/");
$location = "user_data/user_avatars/$rdn/$fln";
move_uploaded_file( $tmp_name, $location);
$imageCD = "UPDATE users SET avatar=? WHERE email=? LIMIT 1";
$imageST = $con->prepare($imageCD);
$imageST->bind_param('ss', $location, $_SESSION["email_login"]);
$imageST->execute();
$_SESSION["avatar"] = $location;
}
}
else {
$location = "/img/default_pic.jpg";
}
Here is where the image is suppose to display:
<img src="<?php echo $_SESSION["avatar"]; ?>" class="profilePic" id="profilePic" />
The session variable will only be active as long as the user doesn't close the browser.
So if you're trying to echo $_SESSION["avatar"] it will work when the user just uploaded the avatar and surfs around on your page. When they leave and come back later, the session has been cleared. Furthermore, the session is only between the current user and the webserver and the avatar will only be displayed for the user itself, and not anyone else on your site!
It will therefore not be the ideal solution to load the image from session!
Every time a user visits your page you need to load their information from your database (including the avatar path) and display it directly from there.

How to check an IF statement every 5sec in PHP?

I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/

Random SQL record while excluding specific records

I have a CodeIgniter PHP application that shows two movie covers. Beside them is a "random movie" button that uses AJAX to replace the two movies with a new set of movies. You can continue to click this, over and over, and see it continue to replace the images of the movie covers. The first two covers to show are set as the defaults, and they should never show after the user has clicked the random movie button. The problem is this: When clicking the random movie button, it will some times take many clicks to finally show a new cover. That is, the same cover will be returned multiple times in a row. The two different covers being fetched are being called from slightly different URLs, so they will rarely both break at the same time. This lets me know that it is refreshing, but that the function is returning the same movie multiple times. If I access the url that is being called via AJAX directly, I never see this take place since I have used the Session class to store the last movie's and exclude it from the SQL query (i.e. WHERE id NOT IN ($default_movie, $last_movie)). Any idea why accessing the url directly would work fine, but when calling via AJAX, I'm seeing this behavior?
I know this may not have been as clear as possible, so let me know if I can clarify something that doesn't make sense. I'll add code if that helps as well. Thanks friends!
Query to get random movie:
SELECT * FROM (`movies`) WHERE `id` NOT IN (2, 10) ORDER BY RAND() LIMIT 1
Model method:
public function getRandom($count = 1, $featured = FALSE, $series = FALSE, $exclude = 0, $last = 0) {
$this->db->order_by('id', 'random');
$this->db->limit(1);
$conditions = array();
if ($exclude > 0) {
$conditions['id !='] = $exclude;
}
if ($last > 0) {
if (!empty($conditions['id !='])) {
$conditionsNotIn = "id NOT IN (" . $conditions['id !=']. ", $last)";
unset($conditions['id !=']);
$this->db->where($conditionsNotIn);
} else {
$conditions['id !='] = $last;
}
}
if ($featured) {
$conditions['featured'] = 1;
}
if ($series) {
$conditions['current_series'] = 1;
}
$movie = $this->db->get_where('movies', $conditions);
$movie = $movie->row();
if (!is_null($movie)) {
return $movie;
} else {
return FALSE;
}
}
Any idea why accessing the url directly would work fine, but when
calling via AJAX, I'm seeing this behavior?
I have an idea yes.
Browser caching.. PITA!
Try turning off caching explicitly:
$.ajaxSetup({cache: false});
Put that before your ajax request, assuming you're using jQuery.
If you're not you need to append some random variable to the url, this keep the browser from caching the requests.

CakePHP Form Spam

I have built a contact form using CakePHP following the tutorial at http://snook.ca/archives/cakephp/contact_form_cakephp
But would like to add a spam protector where the user is presented with a 5 letter character word such as BB42A that is random and the user has to type in before they can submit the form.
I have done some Googling but haven't found anything suitable online.
Any suggestions? Thanks
The one at the bottom of here is quite good: http://mattbrett.com/portfolio/hire/
I would suggest using an existing CAPTCHA library or service rather than rolling your own. No sense re-inventing the wheel.
One of the best is reCAPTCHA. Here's a good tutorial on implementing reCAPTCHA in Cake.
you can use actice/passive captchas with simple math questions like 2+3
http://www.dereuromark.de/2010/08/09/how-to-implement-captchas-properly/
how secure it needs to be is your decision. for most sites this is more than enough.
Actually - one of easiest ways I found to beat spambots was to have a hidden field in every contact form; and usually spambots would fill it whereas humans, as they can't see it, wouldn't be able to.
Try adding to your view:
//call it something along the lines of 'name' or 'email', and the
//real form field 'x1' or 'x2' etc
$this-Form->input('aformfield', array('class' => 'aformfield');
Make sure you hide it in your css:
.aformfield{display:none;}
In the controller before you send the email, check to see if the hidden field is filled:
if(!empty($this->data['Model']['aformfield'])){
$this->Session->setFlash('You shouldn\'t be able to fill out a hidden field');
$this->redirect($this->referrer());
}
It's not bullet proof and I'm sure spambots will ifnd a way around it but it's a good place to start if you don't want to do captcha's.
What you need is called captcha.
Google search for cakePHP + captcha should come up with some cakePHP plugins. I don't develop in cakePHP, so I can't tell more.
You can, of course, make your own captcha and then integrate it in your website.
To keep it short:
Generate a random string;
create an image with this string
(imagecreate function on php.net);
save the string as session
variable;
compare what user submitted with what's saved in session.
Code:
<?php
session_start();
function rand_str($length = 6,
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
{
$chars_length = (strlen($chars) - 1);
$string = $chars{rand(0, $chars_length)};
// Generate random string
for ($i = 1; $i < $length; $i = strlen($string))
{
// Grab a random character from list
$r = $chars{rand(0, $chars_length)};
// Make sure the same two characters don't appear next to each other
if ($r != $string{$i - 1}) $string .= $r;
}
return $string;
}
header("Content-Type: image/png");
$im = #imagecreate(100, 40) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0); // black
$text_color = imagecolorallocate($im, 255, 255,255); // white
$random_string = rand_str();
$_SESSION['captcha'] = $random_string;
imagestring($im, 5, 5, 5, $random_string, $text_color);
imagepng($im);
imagedestroy($im);
?>

auto hyper-link

I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.

Categories