Avatar's Showing up as 0kb on server

Post here is you are having problems with any of the tutorials.
Post Reply
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Avatar's Showing up as 0kb on server

Post by jaymeh »

Hi All,

I have recently completed the avatar tutorial which adds onto the user profiles. I am currently struggling as it uploads an image onto the server but then either throws up the error that the jpeg is not valid or uploads an image which is blank and 0kb in size. Could anyone please direct me to why this is?

Thanks
Jamie
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

Post your code with code tags
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

user.inc.php
<?php

//fetches all of the users from the table

function fetch_users()
{
	$query = 'SELECT user_id, user_username FROM users';

	$result = mysql_query('SELECT user_id AS `id`, user_username AS `username` FROM users');
	
	$users = array();
	
	while(($row = mysql_fetch_assoc($result)) !==false)
	{
		
		$users[] = $row;

	}
	
	return $users;
	
}
//fetches profile information for the given user
function fetch_user_info($uid)
{
	
	$uid=(int)$uid;
       
        $sql = "SELECT
                                 `user_username` AS `username`,
                                 `user_firstname` AS `firstname`,
                                 `user_lastname` AS `lastname`,
                                 `user_email` AS `email`,
                                 `user_location` AS `location`,
                                 `user_about` AS `about`,
                                 `user_gender` AS `gender`
                                 FROM `users`
                                 WHERE `user_id` = {$uid}";
                                 
        $result = mysql_query($sql);
       
        return mysql_fetch_assoc($result);
       
        $info['avatar'] = "core/user_avatars/{$info['id']}.jpg";
	
		return $info;
	
}

function fetch_user_id($username){
        $username = mysql_real_escape_string($username);
 
        $result = mysql_query("SELECT`user_id` FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");       
 
        return mysql_result($result,0);
}

//updates the current users profile info
function set_profile_info($email, $location,$about,$avatar)
{
	$email 		= mysql_escape_string(htmlentities($email));
	$about 		= mysql_escape_string(nl2br(htmlentities($about)));
	$location 	= mysql_escape_string($location);
	
	if (file_exists($avatar))
	{
		$src_size = getimagesize($avatar);
		
		if ($src_size['mime'] === 'image/jpeg')
		{
			$src_img = imagecreatefromjpeg($avatar);	
		}
		else if ($src_size['mime'] === 'image/png')
		{
			$src_img = imagecreatefrompng($avatar);
		}
		else if ($src_size['mime'] === 'image/gif')
		{
			$src_img = imagecreatefromgif($avatar);
		}
		else
		{
			$src_img = false;
		}
		
		if ($src_img !== false)
		{
			$thumb_width= 200;
			
				if($src_size[0] <= $thumb_width)
				{
					$thumb = $src_img;	
				}
				else
				{
					$new_size[0] = $thumb_width;
					$new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width;
					
					$thumb = imagecreatetruecolor($new_size[0], $new_size[1]);
					imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]);
				}
				
				imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg");
		}
	}
	
	$sql = "UPDATE `users` SET
				`user_email` = '{$email}',
				`user_about` = '{$about}',
				`user_location` = '{$location}'
				
			WHERE `user_id` = {$_SESSION['uid']}";
	
	mysql_query($sql);
	
}

//checks if the given username exists in the database
function user_exists($user)
{
	$user = mysql_real_escape_string($user);
	
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_username` = '{$user}'");
	
	return (mysql_result($total, 0) == '1') ? true : false;
}

//checks if the given username and password combination is valid
function valid_credentials($user, $pass) {
	$user = mysql_real_escape_string($user);
	$pass1 = sha1($pass);
	$query = "SELECT user_id FROM users WHERE user_username = '$user' AND user_password =  '$pass1'";
	$result = mysql_query($query);
	if(mysql_num_rows($result)>0) {
		$row = mysql_fetch_array($result);
		return $row['user_id'];
	}else{
		return 0;
	}
}

//adds a user to the datatabase
function add_user($user, $pass)
{
	$user = mysql_real_escape_string(htmlentities($user));
	$pass = sha1($pass);
	$joined = date("d-m-Y");
	
	mysql_query("INSERT INTO `users` (`user_username`, `user_password`, `user_joined`) VALUES ('{$user}', '{$pass}', '{$joined}')");
}

?>
editprofile.php
<?php

error_reporting(E_ALL);

include('core/init.inc.php');

if (isset($_POST['email'], $_POST['location'], $_POST['about']))
{
	$errors = array();
	
	if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false)
	
	{
		$errors[] = "The email address you entered is not valid";	
	}
	
	if(preg_match('#^[a-z0-9 ]+$#i',$_POST['location'])===0)
	{
			$errors[] = 'Your location must only contain A-Z 0-9 and spaces.';
	}
	if(empty($_FILES['avatar']['tmp_name'])=== false)
	{
		$file_ext = end(explode('.',$_FILES['avatar']['name']));
		
		if (in_array(strtolower($file_ext), array('jpg', 'jpeg', 'png', 'gif')) === false)
		{
			$errors[] = 'Your avatar must be an image.';	
		}
	}
	
	if(empty($errors))
	{
		set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']); 
	}
	
	$userinfo = array(
	'email'	=> htmlentities($_POST['email']),
	'location'	=> htmlentities($_POST['location']),
	'about'	=> htmlentities($_POST['about'])
	);

}	

else
{
	$userinfo = fetch_user_info($_SESSION['uid']);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit your Profile</title>
</head>

<body>
	<div>
		<?php
		
		if(isset($errors) == false)
		{
		
			echo 'Click update to edit your profile.';	
			
		}
		else if(empty($errors))
		{
		
			echo 'Your profile has been updated.';
			
		}
		else
		{
			echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';	
		}
		?>

	</div>

<form action="" method="post" enctype="multipart/form-data">
	<div>
		<label for="email">Email: </label>
		<input type="text" name="email" id="email" value="<?php echo $userinfo['email']; ?>" />
	</div>
    <div>
		<label for="location">Location: </label>
		<input type="text" name="location" id="location" value="<?php echo $userinfo['location']; ?>" />
	</div>
    <div>
		<label for="about">About Me: </label>
		<textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($userinfo['about']); ?></textarea>
	</div>
    <div>
    	<label for="avatar">Avatar: </label>
        <input type="file" name="avatar" id="avatar"/>
    </div>
    <div>
		<input type="submit" value="Update" />
	</div>
    </form>
</body>
</html>
I get the following error when I try

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/php7TaWMc' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 71
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

I'll take a look when I get home, but I can see some initial errors.. ill post again in 20 mins
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

Ok, thank you very much
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

I'll go through it function by function
function fetch_users()
{
        $query = 'SELECT user_id, user_username FROM users';
 
        $result = mysql_query('SELECT user_id AS `id`, user_username AS `username` FROM users');
       
        $users = array();
       
        while(($row = mysql_fetch_assoc($result)) !==false)
        {
               
                $users[] = $row;
 
        }
       
        return $users;
       
}
What is the point of the
$query = 'SELECT user_id, user_username FROM users';
line since you set it in the mysql_query() itself?

That line can be deleted.

The
$users = array();
shouldn't be needed, since when you do
$users[]
It will be set to an array automatically.

The
while(($row = mysql_fetch_assoc($result)) !==false)
doesnt need the quantifier (!== false, since thats the same as === true, which while() checks for automatically if nothing else is provided.


function fetch_user_info($uid)
{
       
        $uid=(int)$uid;
       
        $sql = "SELECT
                                `user_username` AS `username`,
                                `user_firstname` AS `firstname`,
                                `user_lastname` AS `lastname`,
                                `user_email` AS `email`,
                                `user_location` AS `location`,
                                `user_about` AS `about`,
                                `user_gender` AS `gender`
                                FROM `users`
                                WHERE `user_id` = {$uid}";
                                 
        $result = mysql_query($sql);
       
        return mysql_fetch_assoc($result);
       
        $info['avatar'] = "core/user_avatars/{$info['id']}.jpg";
       
                return $info;
       
}
I dont think this part gets ran:
 $info['avatar'] = "core/user_avatars/{$info['id']}.jpg";
       
                return $info;
because you have already returned something, which i think ends the function. But, i could be wrong.

If i am right, then simply make the user info get into the $info array (maybe a foreach loop will do that) and then add the avatar to it also.
$info['id']
I think you meant to have it as just
{$uid}
since you provided the uid.
function fetch_user_id($username){
        $username = mysql_real_escape_string($username);
 
        $result = mysql_query("SELECT`user_id` FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");      
 
        return mysql_result($result,0);
}
you pass the $username, so why are you referencing the $_SESSION one?

Surely the $_SESSION is what you pass into the function, and thats what gets used?

I think you need to change the
$_SESSION['username'];
to just
$username
since you also do SQL injection checks on that variable also, but not on the $_SESSION one.

This bit is in the set_profile_info function. The first bit looks fine to me, but this bit Im confused about.
if (file_exists($avatar))
        {
                $src_size = getimagesize($avatar);
               
                if ($src_size['mime'] === 'image/jpeg')
                {
                        $src_img = imagecreatefromjpeg($avatar);       
                }
                else if ($src_size['mime'] === 'image/png')
                {
                        $src_img = imagecreatefrompng($avatar);
                }
                else if ($src_size['mime'] === 'image/gif')
                {
                        $src_img = imagecreatefromgif($avatar);
                }
                else
                {
                        $src_img = false;
                }
               
                if ($src_img !== false)
                {
                        $thumb_width= 200;
                       
                                if($src_size[0] <= $thumb_width)
                                {
                                        $thumb = $src_img;     
                                }
                                else
                                {
                                        $new_size[0] = $thumb_width;
                                        $new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width;
                                       
                                        $thumb = imagecreatetruecolor($new_size[0], $new_size[1]);
                                        imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]);
                                }
                               
                                imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg");
                }
Why do you need to do all those checks? Why can't you just have it uploaded as it is, not use the image functions since they are really slow, and store the image type in the database, so you can reference the image easily anyway?

If you want help doing that, just ask. If there is a reason you did it this way, then that code looks fine to me. Just very inefficient / slow.

To make this function faster, dont use MySQL functions like count, as there is no need.
function user_exists($user)
{
        $user = mysql_real_escape_string($user);
       
        $total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_username` = '{$user}'");
       
        return (mysql_result($total, 0) == '1') ? true : false;
}
Change
 $total = mysql_query("SELECT '1' FROM `users` WHERE `user_username` = '{$user}'");
       
        return (mysql_result($total, 0) == '1') ? true : false;
In add_user function
$user = mysql_real_escape_string(htmlentities($user));
No where else in your code you do the htmlentities() check, which means that if htey did enter something like that, whenever you dont use it in a check, the values wont be the same.

You should put that check on all of them, or none of them, Not just one.

Next Page
error_reporting(E_ALL);
is slow and inefficient, and shouldnt be used in production. Once code is working, remove this line

I believe that:
if (isset($_POST['email'], $_POST['location'], $_POST['about']))
is more efficient if written using in_array() function. But im not 100% sure. The code you have there should work, but i think this is more efficient.
if(in_array(array('email','location','about'),$_POST))
Same as before:
$errors = array();
isnt needed



Okay, with regards to your error.

What you have there is the temporary image, you need to move it. Which I mentioned higher above, so I recommend that you use
move_uploaded_file() function.

Here is the code that I use, and it works. You'll have to adapt it to your code though.
<?php

	if(isset($_POST['submit'])){
		$target_path = "upload/";
		$target_path .= basename($_POST['file_name'].'.jpg');
		
		if(move_uploaded_file($_FILES['file_to_upload']['tmp_name'],$target_path)){
				echo "The file has been uploaded";
		} else {
			echo "There was an error";	
		}
	
	}

?>

<html>
	<head>
   	<title>Chapter 6 Lecture 3</title>
    </head>
    <body>
    	<form method="post" action="#" enctype="multipart/form-data">
        	<input type="text" name="file_name" placeholder="Rename file to:"/><br />
            <input type="file" name="file_to_upload"/><br />
            <input type="submit" name="submit" value="Upload" />
        </form>
    </body>
</html>


If you want that explaining atall, I have a video that does that online.

http://www.udemy.com/php-basics-for-beginners/ use promo code: BetterPHP_FREE_12 and its chapter 6 Lecture 3.

Hope that helps you :)

If i made any mistakes above anybody , just let me know :)
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

Thanks very much with your wise words of wisdom.

Does the move_uploaded_file() function allow you to resize an image?

Thanks
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

jaymeh wrote:Thanks very much with your wise words of wisdom.

Does the move_uploaded_file() function allow you to resize an image?

Thanks
No, it moves the original. But then you can resize it.

I didnt realise you wanted to resize it. I guess i didnt read it properly :P

but, i think you need to move it first, so that it is saved as an image and then resize it.
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

So once the image is uploaded how would I go about resizing it?
Last edited by jaymeh on Tue Jan 10, 2012 5:31 pm, edited 1 time in total.
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

the same way you did, that should work. Just reference the image that you save instead of the temp one
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

I tried the following, the image did not submit nor did it give me an error message.
function set_profile_info($email, $location,$about,$avatar)
{
        $email          = mysql_escape_string(htmlentities($email));
        $about          = mysql_escape_string(nl2br(htmlentities($about)));
        $location       = mysql_escape_string($location);
       
        if(isset($_POST['submit'])){
                $target_path = "core/user_avatars";
                $target_path .= basename($_POST['file_name'].'.jpg');
               
                if(move_uploaded_file($_FILES['avatar']['tmp_name'],$target_path)){
                                echo "The file has been uploaded";
                } else {
                        echo "There was an error";     
                }
       
        }
        
        $sql = "UPDATE `users` SET
                                `user_email` = '{$email}',
                                `user_about` = '{$about}',
                                `user_location` = '{$location}'
                               
                        WHERE `user_id` = {$_SESSION['uid']}";
       
        mysql_query($sql);
       
}
if(empty($errors))
	{
		set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']); 
	}
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

Your missing a / at the end of
$target_path = "core/user_avatars";
Should be
$target_path = "core/user_avatars/";
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

Thanks, its strange, its still not working :(
<?php

include('core/init.inc.php');

if(in_array(array('email','location','about'),$_POST))
{
	$errors = array();
	
	if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false)
	
	{
		$errors[] = "The email address you entered is not valid";	
	}
	
	if(preg_match('#^[a-z0-9 ]+$#i',$_POST['location'])===0)
	{
			$errors[] = 'Your location must only contain A-Z 0-9 and spaces.';
	}
	//if(empty($_FILES['avatar']['tmp_name'])=== false)
//	{
//		$file_ext = end(explode('.',$_FILES['avatar']['name']));
//		
//		if (in_array(strtolower($file_ext), array('jpg', 'jpeg', 'png', 'gif')) === false)
//		{
//			$errors[] = 'Your avatar must be an image.';	
//		}
//	}
	
	if(empty($errors))
	{
		echo "errors are empty";
		//set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']);
		 if(isset($_POST['submit'])){
                $target_path = "core/user_avatars/";
                $target_path .= basename($_POST['file_name'].'.jpg');
               
                if(move_uploaded_file($_FILES['avatar']['tmp_name'],$target_path)){
                        echo "The file has been uploaded";
                } else {
                        echo "There was an error";    
                }
       
        } 
	}
	
	
	
	$userinfo = array(
	'email'	=> htmlentities($_POST['email']),
	'location'	=> htmlentities($_POST['location']),
	'about'	=> htmlentities($_POST['about'])
	);

}	

else
{
	$userinfo = fetch_user_info($_SESSION['uid']);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit your Profile</title>
</head>

<body>
	<div>
		<?php
		
		if(isset($errors) == false)
		{
		
			echo 'Click update to edit your profile.';	
			
		}
		else if(empty($errors))
		{
		
			echo 'Your profile has been updated.';
			
		}
		else
		{
			echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';	
		}
		?>

	</div>

<form action="" method="post" enctype="multipart/form-data">
	<div>
		<label for="email">Email: </label>
		<input type="text" name="email" id="email" value="<?php echo $userinfo['email']; ?>" />
	</div>
    <div>
		<label for="location">Location: </label>
		<input type="text" name="location" id="location" value="<?php echo $userinfo['location']; ?>" />
	</div>
    <div>
		<label for="about">About Me: </label>
		<textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($userinfo['about']); ?></textarea>
	</div>
    <div>
    	<label for="avatar">Avatar: </label>
        <input type="file" name="avatar" id="avatar"/>
    </div>
    <div>
		<input type="submit" name="submit" value="Update" />
	</div>
    </form>
</body>
</html>
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

Does it say that there are no errors then fail?

If so, remove this if:

if(isset($_POST['submit'])){

and the corresponding }
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

$_POST['file_name'] should be $uid
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

It just says nothing. None of those echo statements work.

Very weird. Ill try that thanks

Made a little bit of progress, still no images but I get the following error

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/phpVtaWyp' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 72
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Avatar's Showing up as 0kb on server

Post by jacek »

bowersbros wrote:The
$users = array();
shouldn't be needed, since when you do
It is needed since the function always has to return an array, if there are no users, removing this line would make it return null which would eresult in an error.
bowersbros wrote: The
while(($row = mysql_fetch_assoc($result)) !==false)
doesnt need the quantifier (!== false, since thats the same as === true, which while() checks for automatically if nothing else is provided.
Actually it checks == true by default which is not the same as !== false.
bowersbros wrote:I dont think this part gets ran:
     $info['avatar'] = "core/user_avatars/{$info['id']}.jpg";
           
                    return $info;
because you have already returned something, which i think ends the function. But, i could be wrong.

If i am right, then simply make the user info get into the $info array (maybe a foreach loop will do that) and then add the avatar to it also.
Correct, but the fix is wrong, this should have been
        $info = mysql_fetch_assoc($result);
       
        $info['avatar'] = "core/user_avatars/{$info['id']}.jpg";
       
        return $info;
bowersbros wrote:To make this function faster, dont use MySQL functions like count, as there is no need.
    function user_exists($user)
    {
            $user = mysql_real_escape_string($user);
           
            $total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_username` = '{$user}'");
           
            return (mysql_result($total, 0) == '1') ? true : false;
    }
Change
     $total = mysql_query("SELECT '1' FROM `users` WHERE `user_username` = '{$user}'");
           
            return (mysql_result($total, 0) == '1') ? true : false;
That will jsut give an error if the user is not found since mysql_result() will not be able to fuind the first row. COUNT() is not that slow also the result is cached which means the next time that quesry runs it will just grab the result from memory.
bowersbros wrote:What you have there is the temporary image, you need to move it. Which I mentioned higher above, so I recommend that you use
move_uploaded_file() function.
And what we are doing is resizing that image and saving a smaller copy as the users avatar. So no, ther eis no need to use move_uplaoded_file at all.
bowersbros wrote:I believe that:
    if (isset($_POST['email'], $_POST['location'], $_POST['about']))
is more efficient if written using in_array() function. But im not 100% sure. The code you have there should work, but i think this is more efficient.
    if(in_array(array('email','location','about'),$_POST))
Nope, isset() should be faster since it just checks against null.
bowersbros wrote:Same as before:
    $errors = array();
isnt needed
No, it is, because we have a different outcome later on if the $errors variable is an empty array to if it is not set.



Go back to what you had to start with, and see if the file is being uplaoded properly by adding a
print_r($_FILES);
before the call to set_profile_info()
Image
bowersbros
Posts: 534
Joined: Thu May 05, 2011 8:19 pm

Re: Avatar's Showing up as 0kb on server

Post by bowersbros »

heh, oops ;)

But, it doesnt reference the image when its temporary, because its not saved as jpeg or png, just as a file isnt it?
Thats why its saved as tmp/RandomLettersHere3 isnt it?
I don't like to brag, but I wasn't circumcised. I was circumnavigated. ;)

Want to learn something new? Or maybe reinforce what you already know? Or just help out? Please subscribe to my videos: http://goo.gl/58pN9
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Avatar's Showing up as 0kb on server

Post by jacek »

bowersbros wrote:heh, oops ;)

But, it doesnt reference the image when its temporary, because its not saved as jpeg or png, just as a file isnt it?
Thats why its saved as tmp/RandomLettersHere3 isnt it?
The extension only has meaning to desktop apps really. All you need is the data.
Image
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Avatar's Showing up as 0kb on server

Post by jaymeh »

I have made some various changes to the system and I have outputted what is in the file array below.
Array ( [avatar] => Array ( [name] => Sonic.jpg [type] => image/jpeg [tmp_name] => /var/tmp/php.waq8n [error] => 0 [size] => 48477 ) )

But I still get this error message.
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/php.waq8n' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 71

Here is the function
function set_profile_info($email, $location,$about,$avatar)
{
        $email          = mysql_escape_string(htmlentities($email));
        $about          = mysql_escape_string(nl2br(htmlentities($about)));
        $location       = mysql_escape_string($location);
       
        if (file_exists($avatar))
        {
                $src_size = getimagesize($avatar);
               
                if ($src_size['mime'] === 'image/jpeg')
                {
                        $src_img = imagecreatefromjpeg($avatar);       
                }
                else if ($src_size['mime'] === 'image/png')
                {
                        $src_img = imagecreatefrompng($avatar);
                }
                else if ($src_size['mime'] === 'image/gif')
                {
                        $src_img = imagecreatefromgif($avatar);
                }
                else
                {
                        $src_img = false;
                }
               
                if ($src_img !== false)
                {
                        $thumb_width= 200;
                       
                                if($src_size[0] <= $thumb_width)
                                {
                                        $thumb = $src_img;     
                                }
                                else
                                {
                                        $new_size[0] = $thumb_width;
                                        $new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width;
                                       
                                        $thumb = imagecreatetruecolor($new_size[0], $new_size[1]);
                                        imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]);
                                }
                               
                                imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg");
                }
        }
       
        $sql = "UPDATE `users` SET
                                `user_email` = '{$email}',
                                `user_about` = '{$about}',
                                `user_location` = '{$location}'
                               
                        WHERE `user_id` = {$_SESSION['uid']}";
       
        mysql_query($sql);
       
}
Thanks again
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Avatar's Showing up as 0kb on server

Post by jacek »

Well it looks like it's uploading okay then.

I have never seen the function fail before but it could be a corrupted image. Could you try another image file and see if it does the same thing ?

I guess the only other thing to try would be to update your GD module.
Image
Post Reply