PHP - help

Miscellaneous Forums/General Discussion/PHP - help

Hey, I'm building a website for my friend - I'm having trouble trying to display a thumbnail gallery...

I want to make it so I can create a gallery from a folder full of images... And add more by just dumping more into the folder.


here's the script that generates the thumbnail...
<?php
# Constants
define(IMAGE_BASE, '/var/www/html/mbailey/images');
define(MAX_WIDTH, 80);
define(MAX_HEIGHT, 80);

# Get image location
$image_file = str_replace('..', '', $_SERVER['QUERY_STRING']);
$image_path = IMAGE_BASE . "/$image_file";

# Load image
$img = null;
$ext = strtolower(end(explode('.', $image_path)));
if ($ext == 'jpg' || $ext == 'jpeg') {
    $img = @imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
    $img = @imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
    $img = @imagecreatefrompng($image_path);
}

# If an image was successfully loaded, test the image for size
if ($img) {

    # Get image size and scale ratio
    $width = imagesx($img);
    $height = imagesy($img);
    $scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height);

    # If the image is larger than the max shrink it
    if ($scale &lt; 1) {
        $new_width = floor($scale*$width);
        $new_height = floor($scale*$height);

        # Create a new temporary image
        $tmp_img = imagecreatetruecolor($new_width, $new_height);

        # Copy and resize old image into new image
        imagecopyresized($tmp_img, $img, 0, 0, 0, 0,
                         $new_width, $new_height, $width, $height);
        imagedestroy($img);
        $img = $tmp_img;
    }
}

# Create error image if necessary
if (!$img) {
    $img = imagecreate(MAX_WIDTH, MAX_HEIGHT);
    imagecolorallocate($img,0,0,0);
    $c = imagecolorallocate($img,70,70,70);
    imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
    imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
}

# Display the image
header("Content-type: image/jpeg");
imagejpeg($img);
?>


here's the code I actually include to display my gallery:

<?php

$fCount = 0;



if ($handle = opendir('bignails')) {
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") {
	        if (substr($file, strlen($file)-3, 3)=="jpg" ) {
	            $fCount=$fCount+1;
				$fName[] = $file;
	        }            
        }
    }
}
closedir($handle);

?>

<br/>

<?php echo "Images in gallery: ",$fCount; ?>

<table cellspacing = "2">

	<?php for($i=0; $i<=$fCount-1; $i++){
	$Name=$fName[$i];
	?>
	<?php echo $Name; ?> 
	<td>
		<tr>
		<a href="bignails/<?php echo $Name; ?>">
		<img src="tn_gen/thumb.php?bignails/<?php echo $Name; ?>">
		</a>
		</tr>
	</td>
	<?php } ?>
	
</table>


My problem is the image is not being displayed...


-The link works
-The Image name(s) are correctly displayed by Echo
-The website works..
-My host has all the latesr versions of the GD library

Any ideas?

put an exit; after imagejpeg($img); and absolutely ensure your php file does not contain any \n characters (empty lines) that would corrupt the output.

Hey,

It's still not working - I did a test with the source below..

The image is located in "Mydomain.com/ext/bignails/ss4.jpg"

The script is located in "Mydomain.com/ext/tn_gen/thumb.php" its also where the show gallery script is - which is what I call in the website

I visited "www.mydomain.com/ext/tn_gen/thumb.php?ss4.jpg" and got a little red x... (you know the image that's produced in IE if it cant find the image)

here's the current source - I think it has something to do with where the image is located relative to the locating the script does.. They're obviously not matching up.

thumb.php
<?php
header("Content-Type: image/jpeg");
# Constants

define('MAX_WIDTH', 80);
define('MAX_HEIGHT', 80);


# Get image location
$image_file = str_replace('..', '', $_SERVER['QUERY_STRING']);
$image_path = "../bignails/$image_file";
echo "got location ",$image_path," file is ",$image_file;

# Load image
$img = @imagecreatefromjpeg($image_path);
echo "img created";

# If an image was successfully loaded, test the image for size
if ($img) {

    # Get image size and scale ratio
    $width = imagesx($img);
    $height = imagesy($img);
    $scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height);

    # If the image is larger than the max shrink it
    if ($scale > 1) {
        $new_width = floor($scale*$width);
        $new_height = floor($scale*$height);

        # Create a new temporary image
        $tmp_img = imagecreatetruecolor($new_width, $new_height);

        # Copy and resize old image into new image
        imagecopyresized($tmp_img, $img, 0, 0, 0, 0,
                         $new_width, $new_height, $width, $height);
        imagedestroy($img);
        $img = $tmp_img;
    }
}

# Create error image if necessary
if (!$img) {
    $img = imagecreate(MAX_WIDTH, MAX_HEIGHT);
    imagecolorallocate($img,0,0,0);
    $c = imagecolorallocate($img,70,70,70);
    imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
    imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
}

# Display the image
imagejpeg($img);
exit;
?>


showgallery.php
<?php

$fCount = 0;



if ($handle = opendir('bignails')) {
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") {
	        if (substr($file, strlen($file)-3, 3)=="jpg" ) {
	            $fCount=$fCount+1;
				$fName[] = $file;
	        }            
        }
    }
}
closedir($handle);

?>

<br/>

<?php echo "Images in gallery: ",$fCount; ?>

<table cellspacing = "2">

	<?php for($i=0; $i<=$fCount-1; $i++){
	$Name=$fName[$i];
	?>
	<?php echo $Name; ?> 
	<td>
		<tr>
		<a href="bignails/<?php echo $Name; ?>">
		<img src="tn_gen/thumb.php?<?php echo $Name; ?>">
		</a>
		</tr>
	</td>
	<?php } ?>
	
</table>


any ideas?

Here's a working version - When I got yours to work the resizing of images didn't appear to work either :/

showgallery.php
<?php

$fCount = 0;



if ($handle = opendir('bignails')) {
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") {
	        if (substr($file, strlen($file)-3, 3)=="jpg" ) {
	            $fCount=$fCount+1;
				$fName[] = $file;
	        }            
        }
    }
}
closedir($handle);

?>

<br/>

<?php echo "Images in gallery: ",$fCount; ?>

<table cellspacing = "2">

	<?php for($i=0; $i<=$fCount-1; $i++){
	$Name=$fName[$i];
	?>
	<?php echo $Name; ?> 
	<td>
		<tr>
		<a href="bignails/<?php echo $Name; ?>">
		<img src="tn_gen/thumb.php?<?php echo $Name; ?>">
		</a>
		</tr>
	</td>
	<?php } ?>
	
</table>


thumb.php
<?php
header("Content-Type: image/jpeg");

$image_file = str_replace('..', '', $_SERVER['QUERY_STRING']);
$image_path = "../bignails/$image_file";

function createthumb($src_image,$new_w,$new_h)
{
	$src_img=imagecreatefromjpeg($src_image);
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	if ($old_x > $old_y) 
	{
		$thumb_w=$new_w;
		$thumb_h=$old_y*($new_h/$old_x);
	}
	if ($old_x < $old_y) 
	{
		$thumb_w=$old_x*($new_w/$old_y);
		$thumb_h=$new_h;
	}
	if ($old_x == $old_y) 
	{
		$thumb_w=$new_w;
		$thumb_h=$new_h;
	}
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
	imagejpeg($dst_img); 
	imagedestroy($dst_img); 
	imagedestroy($src_img); 
}

# Display the image
createthumb($image_path,80,80);
?>


Address to the image-url and debug. There is no problem, so long this works.

@ Qube:
1. resize corrdinates should be integers
2. this code does not work with 32x1200 (icon strips for web etc.)

Oh no!, the nit picking police are about.

ok Qube's code seems to work, thanks!

I have another question --

How do I pass a URL argument from a script to an include script?

For example,

<?php
$myargument = $_GET['a'];
require_once('test/showgallery.php?b=$myargument')

?>


This gives me a file not found error... Is it possible to do this?

$myargument = $_GET['a'];
require_once('test/showgallery.php')


Then... in your include file use the same variable declared before ...

if ($myargument == blabla) {
  blablabla
}


ahh, thanks!

Anyone recommend a simple, free php shoutbox script? Preferably one that doesn't use a mysql database?

@Yahfree - I made one. Since you can't PM me you might want to post your email here for me to contact you (when I have the time).

watch out:
1. don't create all thumbnails everytime the gallery gets viewed. make a script like "CreateThumbs.php"
2. The "CreateThumgs.php" script should create thumbnails of every image and store it in a seperated folder.
3. watch out for the PHP memory limit. it can abort the php script runtime when it exceeds the limit.

Thanks for the warnings devils.

I've decided to try and write my own simple shoutbox - as ones on the internet are way over-complicated.

However, I'm having problems, I want the messages in a IFRAME that refreshes on submit... this is fine, but to do this, it screws up the database inserting script..

Additional info:
- The DB tables are all setup with this query:
CREATE TABLE shoutbox (
    id INT(10) not null AUTO_INCREMENT,
    name VARCHAR(20),
    message TEXT,
    date VARCHAR(15),
    ip VARCHAR(15),
    PRIMARY KEY(id)
);

- The database is NOT recieving information at all
- The script works with a non-IFRAME version



Here's the code - I've blanked out my DB info for obvious reasons.

shoutbox.php (the include file)
<?php

	// IMPORTANT -- DATABASE INFORMATION
	$dbhost = ""; 
	$dbname = "";
	$dbuser = ""; 
	$dbpass = ""; 
	//--------------------------------------------------------------------------------
	
	$name = $_POST['name'];
	$message = $_POST['message'];
	$ip = $_POST['ip'];
	$mlen = strlen($message);
	$maxlength = 150;
	$date = date("M jS Y");

	if ($_POST['submit'])  {
		if ($name == "") { 
			echo "<strong>Error: Please enter your nickname.</strong>"; 
		}
		else if ($message == "") { 
			echo "<strong>Error: No message sent.</strong>"; 
		}
		else if ($mlen > $maxlength) { 
			echo "<strong>Error: Message too long, 150char limit!</strong>"; 
		}
		else {
			$db = mysql_connect($dbhost,$dbuser,$dbpass); 
			mysql_select_db($dbname) or die(mysql_error());
			mysql_query("INSERT INTO shoutbox(name,message,date,ip) VALUES('$name','$message','$date','$ip')"); 
			mysql_close($db);
		}
	}

	
?>

<iFRAME name = "chatlog" src = "shoutbox/sbmessages.php"></iFRAME>

<br/>
<br/>
  <form target="chatlog" method="post" action="shoutbox/sbmessages.php">
    <strong>Nickname:</strong><br/>
    <input type="text" name="name" maxlength="20"><<br/>
    <strong>Message:</strong><br/>
    <textarea name="message"></textarea><br/>
    <input type="submit" name="submit" value="Shout It!">
    <input type="hidden" name="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>">
  </form>


sbmessages.php
<?php

	// IMPORTANT -- DATABASE INFORMATION
	$dbhost = ""; 
	$dbname = "";
	$dbuser = ""; 
	$dbpass = ""; 
	//--------------------------------------------------------------------------------
	
	$thedb = mysql_connect($dbhost,$dbuser,$dbpass);
	mysql_select_db($dbname) or die(mysql_error());
	$query = "SELECT * FROM shoutbox ORDER BY id LIMIT 20"; 
	$result = mysql_query($query);
	
	
	while($r = mysql_fetch_array($result)) {
		$name = $r['name'];
		$name = strip_tags($name);
		$message = $r['message'];
		$message = strip_tags($message);
		echo "<strong>>$name</strong>: $message<br/>";
	}
	mysql_close($thedb);
?>