Random image creating script trouble - php

I have created a script which takes a random IMAGE ID from the database, converts it to a valid file name and then I use it to generate random images from a link.
This is how such a link looks like (works - try it):
http://imgit.org/roll.php?image=3J9N0Y4k8g4l4G7
When you reload that link, you'll notice the image changes. If I add this image to <img src="THAT LINK" /> it works, however, it doesn't work on message board like phpBB or vBulletin when I put that link inside [img][/img] BBCode tags.
I suppose there is a problem with my script, because there are various services out there that do exactly the same thing (link on forums) and it works.
Here is my roll.php script:
<?php
$imgit_root_path = '.';
include("{$imgit_root_path}/common.php");
if ($config['disable_roll'])
{
redirect('index.php');
}
$roll_key = request_var('image', '');
$roll_key = substr($roll_key, 0, 15);
if (!$roll_key)
{
redirect('index.php?action=404');
}
if (!$image->roll_key_exists($roll_key))
{
redirect('index.php?action=404');
}
$images = $image->roll_info($roll_key);
$images = explode('|', $images);
$count = sizeof($images);
$index = mt_rand(0, $count - 1);
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$image_url = generate_site_url() . IMAGES_PATH . $image->get_name($images[$index]);
$image_inf = pathinfo($image_url);
header('Content-type: ' . $extList[$image_inf['extension']]);
readfile($image_url);
?>

I believe the problem may be that phpBB will disallow links which aren't confirmed as images. That is, don't have a known image extension, such as .jpg;
https://www.phpbb.com/community/viewtopic.php?f=46&t=1285255
For security reasons, images whose extensions cannot be confirmed
(such as in the first example) aren't allowed by BBCode. Instead of an
image, it's fully possible for someone to embed a JavaScript script,
or even worse, onto a page which could be a security risk to anyone
visiting the page, or possibly even the server.
This is most likely the same in vBulletin.
Seems you can override it in the forum settings maybe?
Alternatively, if you can change you script, so that you can append a ".jpg" extension to the end, then that may also work!

I think what happens is browser caches image. Try adding header('Cache-Control: max-age=0'); before readfile($image_url);

Related

Display Random Image from WP Directory

I have used a function
/*
Random File Function
Written By: Qassim Hassan
Website: wp-time.com
Twitter: #QQQHZ
*/
function Qassim_Random_File($folder_path = null){
if( !empty($folder_path) ){ // if the folder path is not empty
$files_array = scandir($folder_path);
$count = count($files_array);
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = $folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
else{
return "The folder is empty!";
}
}
else{
return "Please enter folder path!";
}
}
?>
to pull a random image from a specific wordpress directory. I can successfully call up a random image file however it does not display, just displays the image filename and a broken image icon.
The code I am using from the tutorial to display the image is <?php echo Qassim_Random_File("my-folder-name"); // display random image! ?>
I am brand new to php as of this week, and a fairly novice coder in general (know some basics) so I really am stumped. I've fooled with other possible solutions from stack overflow already but this tutorial is the only thing I've been able to get close to working. Many thanks if anyone can spot the problem!
This is showing up in the HTML inspector:
<div class="elementor-widget-container">
<h5>call</h5>
<a href="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" target="_blank" title="image_2.jpg">
<img src="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" alt="image_2.jpg">
</a>
</div>
You just need to replace this line:
$file_link = $folder_path . "/" . $random_file;
...with this one:
$file_link = get_site_url(null, $folder_path . "/" . $random_file);
What was the problem?
scandir is returning the physical file path, not the url to the file - we can confirm this is we look at one of the values it returns for $random_file, e.g. wp-content/uploads/H-PH-MA-Greyscale
This is a relative URL, but we need an absolute URL so that it will work no matter where it is called. We also need to include the site URL so that the path to wp-content is correct. (Note: site URL and home URL can be different - the site URL is the one that always point to the location of the WP files).
Another problem is the trailing slash (or lack of one) on the site URL. get_site_url and get_home_url do not add the trailing slash to the URL, so you need to add it yourself if it isn't included in the file path.
So how do we solve this?
Using the get_site_url function added the correct path to the WP files, and it also lets us pass it the file path with our without a preceding slash as a parameter, and it will add the slash on the path only if it is needed.
The code looks simple, if the folder exist and it has more then 2 file (it considers the "." and ".." and files when you use scandir) then you should be able to see something. What's the generated HTML code for that function call?
Be aware that the code you are using builds the file url using the phisical path, that isn't going to work. You should fix this part:
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = get_home_url().$folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
Notice the get_home_url() to build the real URL which is needed for your <img tag src

Displaying Lots of Images Using One PHP File

I hope someone will help me with this. Namely, I need a PHP code which will display images in a HTML/PHP page based on their id. For example: the file ShowPicture.php, and the code in it something like this:
PictureID = "MyPicture1"
MyPicture1_Source = "/Pictures/Picture1.jpg";
PictureID = "MyPicture2"
MyPicture2_Source = "/Pictures/Picture2.png";
PictureID = "MyPicture3"
MyPicture3_Source = "/Pictures/Picture3.gif";
PictureID = "MyPicture4"
MyPicture4_Source = "/Pictures/Picture4.bmp";
Example of usage on the pages:
HTML/PHP PAGE 1: <IMG src="ShowPicture.php?id=MyPicture4">
HTML/PHP PAGE 4: <IMG src="ShowPicture.php?id=MyPicture2">
HTML/PHP PAGE 2: <IMG src="ShowPicture.php?id=MyPicture3">
HTML/PHP PAGE 3: <IMG src="ShowPicture.php?id=MyPicture1">
I don't currently use any code since I didn't find good enough which will suit this particular need of mine.
The file should be something like Facebook's rsrc.php file, which fetches all the graphics for the site whilst hiding the real source path.
EDIT: I do not need Sessions nor Cookies, I want the pictures to be displayed permanently on pages through PHP, even after the user refreshes/reloads the pages.
EDIT 2: No (My)SQL. The PHP file itself and alone must be sort of a database for storing and displaying images.
I wanted you to put efford in it yourself. Stack Overflow is ment to help you when you have issues with your code. It's not ment for people that just want some programmer to do all the work for them. Anyway, I've taken a few minutes to do it for you now, so here it is:
<?php
$id = $_GET["id"];
switch($id){
case "MyPicture1":
$file = "img/img1.jpg";
break;
case "MyPicture2":
$file = "img/img2.jpg";
break;
case "MyPicture3":
$file = "img/img3.jpg";
break;
case "MyPicture4":
$file = "img/img4.jpg";
break;
default:
echo "Invalid ID given!";
exit;
}
if(file_exists($file)){
$size = getimagesize($file);
$fp = fopen($file, 'rb');
if($size and $fp){
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
header('Content-Type: '.$size['mime']);
header('Content-Length: '.filesize($file));
fpassthru($fp);
}
exit;
} else {
echo "File not found!";
}
?>
You can modify it any further yourself.

Overwrite text in a specific div in a file (PHP HTML)

I am creating a slideshow editor. I have been able to parse a file and present it to the user in a form. Now I need to figure out how to write the saved information to the file. I want the user to be able to edit the information before and after the slideshow, so there is no specific set of information to be able to overwrite the whole file.
If there is a way to get all of the text before the div and copy it to the variable, add the new information, then get the rest of the information after the div and add that to the variable and then write all that information to the file, then that would work. Otherwise, here is what I have put together.
/* Set Variables */
$x = $_POST['x'];
$file = $_POST['file'];
$path = '../../yardworks/content_pages/' . $file;
$z=0;
while ($z<$x){
$title[$z] = $_POST['image-title'.$z];
$description[$z] = $_POST['image-desc'.$z];
$z++;
}
for ($y=0; $y<$x; $y++){
$contents .= '<li>
<a class="thumb" href="images/garages/'.$file[$y].'">
<img src="images/garages/'.$file[$y].'" alt="'.$title[$y].'" height="100px" width="130px" class="slideshow-img" />
</a>
<div class="caption">
<div class="image-title">'.$file[$y].'</div>
<div class="image-desc">'.$description[$y].'</div>
</div>
</li>';
}
/* Create string of contents */
$mydoc = new DOMDocument('1.0', 'UTF-8');
$mydoc->loadHTMLFile($path);
$mydoc->getElementById("replace")->nodeValue = $contents;
$mydoc->saveHTMLFile($path);
$file = file_get_contents($path);
$file = str_replace("<", "<", $file);
$file = str_replace(">", ">", $file);
file_put_contents($path, $file);
?>
Nothing throws out an error, but the file also remains unchanged. Is there anything I can change or fix to make it write to the file? This is all I have been able to find regarding this specific problem.
I would like to stick to one language, but if I find a way to write to the file using javascript, do the php variables pass on to the javascript section or do I have to stick with one language?
**Edit
Everything is working. ONE problem: is there a way to keep the special characters without converting them? I need the < and > to stay as they are and not convert to a string
I have decided to save the file as it is and use a separate code set to replace the string. I have edited my question above.

PHP GD avatars go blank when certain images are put in it

I'm making an avatar site. One of my users is having an issue... their avatar is going blank. Their avatar:
http://www.world2build.com/API/Avatar.aspx?ID=1586
The items on their avatar work fine without this item, but when they put this body on, which is the very first layer, it goes blank:
http://node1.world2build.com/Body/13245107086553.png
However, if I move the Body to the top layer, it displays... but I have to keep the body at bottom layer to make sure it displays like a normal avatar. Why would this make the PNG go blank with it as the bottom layer? I don't see the problem.
Code (with $vars being an array with the links to the files):
function merge_image($base, $img){
$width = imagesx($img);
$height = imagesy($img);
imagecopy($base,$img,0,0,0,0,$width,$height);
}
$base = imagecreatefrompng($vars[0]);
for($i=1; $i<count($vars); $i++){
merge_image($base, imagecreatefrompng($vars[$i]));
//echo $vars[$i]."<BR>";
}
header("Content-Type: image/png");
imagesavealpha($base, true);
imagepng($base);
NOTICE: $base, on line 7, is the body image (the one causing the problem.)
A working avatar is: http://www.world2build.com/API/Avatar.aspx?ID=1602 (it uses a different body than the one provided above)
I fixed this by replacing the code with this, and turning $base into a blank image.
$base = imagecreatefrompng("../Images/BlankTransparentImage.png");
for($i=0; $i<count($vars); $i++){
merge_image($base, imagecreatefrompng($vars[$i]));
//echo $vars[$i]."<BR>";
}
(Notice I changed $i=1 to $i=0 in the for loop to include the body.)

Code for displaying thumbnail images

I have a simple PHP script that enables users to upload images on a server. I am after some help in displaying these images as thumbnails in an HTMl page and then letting the user click on these thumbnails and then the original picture is displayed in a new page.
Can I use straight HTML for this? Or do I need some combination of javascript or PHP variant?
I know that there are many questions about this on stackoverflow, and I have tried them, but nothing is what I am after.
I would prefferably like the thumbnails be created on the 'fly' rather than me personally having to create each thumbnal when a user uploads an image.
So basically what language should I use to do this? And also can I have some source code if possible?
thanks
Creating thumbnails every time they are requested is a very bad idea - it takes a lot of processing power, which would be easily saved by keeping them around the first time you create them. I would suggest putting the thumbnail creation in the php script that processes the file upload, so that you save the image and its thumbnail to disk at the same time. You can also keep the thumbnail in memory, or wait until the first time it's requested to create it, but either way you cannot re-generate it every time it is requested.
It is possible to use html to change an image's size, by simply setting the width and/or height properties:
<img src='foo.jpg' alt='foo' width='500' height='300'/>
However, this is a bad idea if you aren't certain that the user will later want to view the full-sized image. The reason is that a thumbnail has a smaller filesize than the full image: if the client only wants to view the thumbnail, then you don't want to waste bandwidth (= your money and the client's time) sending them the full image.
As for your interface, you don't need javascript to accomplish that, just html. However, you will need a server-side script to create the thumbnails that your html page links to.
There are plenty of php thumbnail scripts out there.
Either you use a rewriter to still show the original path, but server a php thumbnail version. Or you have to have the url change to something like:
<img src="thumb.php?file=path/to/picture.jpg&size=128" />
Mighty Stuff
phpThumb
Are just such two. Best configured to utilize the cached folder. I use a modified version of the first script at work.
Here's a PHP script you can build appon only works with jpg images.
It will scan through a directory, normalize the image to a decent dimension and also make a thumb on the fly, then on next refresh it wont need to reprocess the image as its already present in the thumbs dir. Hope it helps...
Script placement
Root>
thisscript.php
/images/
someimage.jpg
someimage2.jpg
thisscript.php
<?php
// config section
$path = "./images/";
$thpath = $path."thumbs/";
// end configration
// Open the directory
$do = dir($path);
// now check if the thumb dir is available if not, create it!!
if (!is_dir($thpath)){
mkdir($thpath);
}
$output = '<div>';
while (($file = $do->read()) !== false){
if (is_dir($path.$file)){
continue;
}else{
$info = pathinfo($path.$file);
$fileext = $info['extension'];
if (strtolower($fileext) == 'jpg'){
if (!is_file($thpath.$file)){
//Normalize Super lrg Image to 750x550
thumb_it($path, $file, $path,750,550,99);
//Make Thumb 200x125
thumb_it($path, $file, $thpath,200,125,99);
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}else{
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}
}
}
}
$output .='</div>';
echo $output;
//Functions
function thumb_it($dirn, $file, $thumbdir,$rwidth,$rheight,$quality){
set_time_limit(0);
$filename = $dirn.$file;
$thfilename = $thumbdir.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $file);
// get the filename and the thumbernail directory
if (is_file($filename)){
// create the thumbernail from the original picture
$im = #ImageCreateFromJPEG($filename);
if($im==false){return false;}
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
if (($width < $rwidth) && ($height < $rheight)){
$n_height = $height;
$n_width = $width;
}else{
// saveing the aspect ratio
$aspect_x = $width / $rwidth;
$aspect_y = $height / $rheight;
if ($aspect_x > $aspect_y){
$n_width = $rwidth;
$n_height = $height / $aspect_x;
}else{
$n_height = $rheight;
$n_width = $width / $aspect_y;
}
}
$newimage = imagecreatetruecolor($n_width, $n_height);
// resizing the picture
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
// writing to file the thumbnail
if(file_exists($thfilename)){chmod($thfilename, 0777);}
Imagejpeg($newimage, $thfilename, $quality);
imagedestroy($newimage);
imagedestroy($im);
}
}
?>

Categories