thumbnail creation error while uploading to mysql works

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
weeping
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 12:01 pm

thumbnail creation error while uploading to mysql works

Post by weeping »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


hello,

i first tried to upload images to mysql and in the same time to generate thumbnails in the same mysql query - which didnt worked so i want now to submit/upload an image to mysql and in the same time to generate its thumbnail inside a directory on the server BUT i have this problem that the image i 'browse' for need to be in the same directory with my .php scripts... i will post the code and the error i get :


the function used for creating thumbnails:

Code: Select all

function createthumb($name,$filename,$new_w,$new_h){
$system=explode('.',$name);
if (preg_match('/jpg|jpeg/',$system[1])){
$src_img=imagecreatefromjpeg($name);
}
if (preg_match('/png/',$system[1])){
$src_img=imagecreatefrompng($name);
}

$old_x=imageSX($src_img);
$old_y=imageSY($src_img);


$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;

if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}

else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

if (preg_match("/png/",$system[1])) {
imagepng($dst_img,$filename);
}
else {
imagejpeg($dst_img,$filename);
}

imagedestroy($dst_img);
imagedestroy($src_img);
}
************************************************
rest of code:
************************************************

Code: Select all

<?php

include 'init.php';

if(!isset($_POST['upload']))
{
include 'addform.php';
exit;
}

else
{

function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

$file_name = stripslashes($_FILES['image']['name']);
$extension = getExtension($file_name);
$extension = strtolower($extension);

if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$ext_error = 'Unknown extension!';
include 'add.php';
exit;
}

define ("MAX_SIZE","5000");
$sizekb=filesize($_FILES['image']['tmp_name']);

if ($sizekb > MAX_SIZE*5000)
{
$size_error = 'You have exceeded the size limit!';
include 'add.php';
exit;
}

// $file_name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$file_size = $_FILES['image']['size'];
$file_type = $_FILES['image']['type'];

$var = fopen($temp_name, 'r');
$content = fread($var, filesize($temp_name));
$content = addslashes($content);
fclose($var);

if(!get_magic_quotes_gpc())
{
$file_name = addslashes($file_name);
}

$user = 'test2';
$path="thumbs\\$user";
mkdir($path,0777,TRUE);

include 'fct.php';
$filename = "$path\\thumb_$file_name";
createthumb($file_name,$filename,120,150);

$query = "INSERT INTO upload (name, size, type, picture) ".
"VALUES ('$file_name', '$file_size', '$file_type', '$content')";
mysql_query($query) or die ('Could not insert into dB!');

$ok = 'Thumbnail created Successfully!';
$path_to_images = "thumbs/$user/";
$default_img = "";
include 'addform.php';
exit;

}

?>




*********************************************************
The errors:
*********************************************************


Warning: imagecreatefromjpeg(gkoufay04.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in E:\www\fct.php on line 6

Warning: imagesx(): supplied argument is not a valid Image resource in E:\www\fct.php on line 12

Warning: imagesy(): supplied argument is not a valid Image resource in E:\www\fct.php on line 13

Warning: Division by zero in E:\www\fct.php on line 26

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in E:\www\fct.php on line 29

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in E:\www\fct.php on line 30

Warning: imagejpeg(): supplied argument is not a valid Image resource in E:\www\fct.php on line 36

Warning: imagedestroy(): supplied argument is not a valid Image resource in E:\www\fct.php on line 39

Warning: imagedestroy(): supplied argument is not a valid Image resource in E:\www\fct.php on line 40


*********************************************

as i said i get these errors when trying to submit a image which is not in the same directory with my .php files. the image gets writen to blob field inside sql but the thumbnail doesnt generate (it generates when source image is toghether with php files...)


HELP PLEASE !!!

10x!


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Last edited by weeping on Tue Feb 27, 2007 3:55 am, edited 2 times in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

What compels you to store the image data in MySQL instead of the file system?

The following are notes that I wrote as I read your code, they may be a bit out of order when corresponding to your code.

Looking for the file's extension alone is asking for trouble. I could rename any file I like to .jpeg and your code would store it. getimagesize() is much more safe.

The file's size is stored in $_FILES['image']['size'], so filesize() isn't really needed.. although you can use it to verify the size (granted, PHP fills the value.) Your code appears to accept up to 25M files. Is this what you want?

file_get_contents() can substitute for fopen()+fread(filesize())

$file_name can potentially contain an entire path (as some browsers do mistakenly provide that information.) basename() will help fix that.

It's possible for forms to be submitted without the use of their submit button. Some browsers will not provide the button unless the user actually selected the button to submit.

It's best to use the built-in constant DIRECTORY_SEPARATOR instead of hard-coding "\" or "/" as PHP set's it to the platform's native separator for you.

addslashes() is not a very secure function. In fact, it can be tricked into allowing SQL injections. Since you are using MySQL, use mysql_real_escape_string() which does not have such a flaw.

---

The errors you are getting come from $file_name not actually existing yet. $temp_name is what you want instead.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

What does you your mkdir return?

Code: Select all

mkdir($path,0777,TRUE);
(#10850)
weeping
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 12:01 pm

Post by weeping »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


hello, sorry for not reading the rules i will try to comply with them

i changed a bit the code as you suggested (please accept me as beeeing not very advanced in php..only a few weeks of trying to understand it and using forums for help and php manual ..)

it works to : 
 - write the image into BLOB field inside mysql (no matter the path where the image is selected from ), 
 - AND creates the thumbnail inside a given directory($path) BUT only if the image submitted was inside the same directory where php files are 

all i want is to be able create that thumbnail  from whereever i load the images ..

i will put here the whole content of my files so you can try it yourself...it can be useful because part of it really works and i feel i am close to make it all work (with your help) :

sql table
[syntax="sql"]CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
picture MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);
init.php[/syntax]

Code: Select all

<?php

// MySQL Settings
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'pass';
$db_database = 'db';

// Connect to the database
$link = mysql_connect ($db_host, $db_user, $db_pass) or die ('Could not connect to the database.');
mysql_selectdb ($db_database) or die ('Could not select database.');


?>
addform.php

Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Upload FORM</title>
</head>

<body>

<br><br>
<form method="post" enctype="multipart/form-data" action="add.php">
<input name="image" type="file">
<input name="upload" type="submit" value=" Upload ">
</form>

<br><br>

<?php if (isset($ext_error)) { ?>Error: <?php echo $ext_error; ?><?php } ?>
<?php if (isset($size_error)) { ?>Error: <?php echo $size_error; ?><?php } ?>

<?php if (isset($ok))
{
echo $ok;
?>

<br>
<img src="<?php echo getRandomImage($path_to_images, $default_img) ?>" alt="">
<br><font size="2">(random) </font>

<?php
}
?>

</body>
</html>
add.php

Code: Select all

<?php

include 'init.php';

if(!isset($_POST['upload']))
{
include 'addform.php';
exit;
}

else
{
// The original name of the file on the client machine.
$file_name = $_FILES['image']['name'];

$info = pathinfo($file_name);
$ext = $info['extension'];
$extension = strtolower($ext);

if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "gif") && ($extension != "png"))
{
$ext_error = 'Unknown extension!';
include 'addform.php';
exit;
}
// max size 200 kB
define ("max_size","200");
// The size, in bytes, of the uploaded file.
$file_size = $_FILES['image']['size'];

if ($file_size > max_size*1000)
{
$size_error = 'You have exceeded the size limit!';
include 'addform.php';
exit;
}

// The temporary filename of the file in which the uploaded file was stored on the server.
$temp_name = $_FILES['image']['tmp_name'];

// The mime type of the file, if the browser provided this information. An example would be "image/gif".
// This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$file_type = $_FILES['image']['type'];

$var = fopen($temp_name, 'r');
$img = addslashes(fread($var, filesize($temp_name)));
fclose($var);

$user = 'testeee';
$path="thumbs\\$user";
if (!is_dir($path)) { mkdir($path,0777,TRUE); }

include 'fct.php';
$thumbname = "$path\\thumb_$file_name";
createthumb($_FILES['image']['name'],$thumbname,120,150);


if (!get_magic_quotes_gpc())
{
$file_name = addslashes($_FILES['image']['name']);
}

$query = "INSERT INTO upload (name, size, type, picture) ".
"VALUES ('$file_name', '$file_size', '$file_type', '$img')";
mysql_query($query) or die ('Could not insert into dB!');

$ok = 'Thumbnail created Successfully!';
$path_to_images = "thumbs/$user/";
$default_img = "";
include 'addform.php';
exit;

}

?>
fct.php

Code: Select all

<?php

function createthumb($name,$filename,$new_w,$new_h){
$system=explode('.',$name);
if (preg_match('/jpg|jpeg/',$system[1])){
$src_img=imagecreatefromjpeg($name);
}
if (preg_match('/png/',$system[1])){
$src_img=imagecreatefrompng($name);
}

$old_x=imageSX($src_img);
$old_y=imageSY($src_img);


$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;

if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}

else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

if (preg_match("/png/",$system[1])) {
imagepng($dst_img,$filename);
}
else {
imagejpeg($dst_img,$filename);
}

imagedestroy($dst_img);
imagedestroy($src_img);
}

function getRandomImage($path, $img) {
if ( $list = getImagesList($path) ) {
mt_srand( (double)microtime() * 1000000 );
$num = array_rand($list);
$img = $list[$num];
}
return $path . $img;
}

function getImagesList($path) {
$ctr = 0;
if ( $img_dir = @opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {
// can add checks for other image file types here
if ( preg_match("/(\.gif|\.jpg)$/", $img_file) ) {
$images[$ctr] = $img_file;
$ctr++;
}
}
closedir($img_dir);
return $images;
}
return false;
}

?>
please check yourselfs to see the errors...

Warning: imagecreatefromjpeg(pic4.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\wamp\www\fct.php on line 6

Warning: imagesx(): supplied argument is not a valid Image resource in C:\wamp\www\fct.php on line 12

Warning: imagesy(): supplied argument is not a valid Image resource in C:\wamp\www\fct.php on line 13

Warning: Division by zero in C:\wamp\www\fct.php on line 26

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\wamp\www\fct.php on line 29

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\wamp\www\fct.php on line 30

Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\wamp\www\fct.php on line 36

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\wamp\www\fct.php on line 39

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\wamp\www\fct.php on line 40


When selecting the image from other directory i get those errors !!!

mkdir makes the dir... it returns true for checking.. that's not my problem right now..

help!
10x :(


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I've already explained why you get the errors, it's still the same problem. Different variable name, but it's the same value.
feyd wrote:The errors you are getting come from $file_name not actually existing yet. $temp_name is what you want instead.
weeping
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 12:01 pm

NOK

Post by weeping »

you allready did and i knew it allready that it was that BUT what i still don't know it's how to make it work

this is what i get when calling: createthumb($temp_name,$filename,120,150);

Code: Select all

Notice: Undefined variable: src_img in E:\www\fct.php on line 153

Warning: imagesx(): supplied argument is not a valid Image resource in E:\www\fct.php on line 153

Notice: Undefined variable: src_img in E:\www\fct.php on line 154

Warning: imagesy(): supplied argument is not a valid Image resource in E:\www\fct.php on line 154

Warning: Division by zero in E:\www\fct.php on line 167

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in E:\www\fct.php on line 170

Notice: Undefined variable: src_img in E:\www\fct.php on line 171

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in E:\www\fct.php on line 171

Warning: imagejpeg(): supplied argument is not a valid Image resource in E:\www\fct.php on line 182

Warning: imagedestroy(): supplied argument is not a valid Image resource in E:\www\fct.php on line 185

Notice: Undefined variable: src_img in E:\www\fct.php on line 186

Warning: imagedestroy(): supplied argument is not a valid Image resource in E:\www\fct.php on line 186
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

The filename PHP provides doesn't have an extension that you will be able to use. getimagesize() will give you the information you want.
weeping
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 12:01 pm

Post by weeping »

10x feyd - you were right and it works v well now
i echo-ed all [FILE] variables and have seen that indeed i was giving the createtumb function the wrong path

eg:
echo " $_FILEs['image']['tmp_name']" --------> C:/wamp/tmp\php71.tmp

of course it didnt worked when i was using the extension for comparation inside if statements

this is how i compare now the file type inside the createtumb function :


$array = getimagesize($name);
$mime = $array ['mime'];

if ($mime == "image/jpeg"){
$src_img=imagecreatefromjpeg($name);
}

...
Post Reply