user profile - image echo issue.

Post here is you are having problems with any of the tutorials.
Post Reply
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

user profile - image echo issue.

Post by matthewparker »

hi there,

i completed and successfully integrated both the register/login tutorial with the user profile(with pagination) system, along with the user avatar image.

what i have been trying to do(unsuccessfully) is echo the users avatar above their name on the user-list, so you have username+image, username+image and so forth.

i know this probably sounds like a stupid question but can someone at least point me in the right direction in terms of what part of my code i should be looking at to get this working(im not asking for the answer, so don't worry :P)

Obviously simply putting <?php echo $user_info['avatar']; ?> in the user_list.php won't work as it will just show the default avatar and not for each specific user id/username - if that makes sense?

im hoping this is fairly understandable but please me know if you require any code.

thanks.
Last edited by matthewparker on Mon May 14, 2012 9:17 pm, edited 1 time in total.
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: user profile - image echo issue.

Post by Temor »

How are you storing the avatars?
Are you naming the files in a specific way or are you perhaps storing the location of the picture in a database?

What I usually do is insert the name and location of the avatar along with the users ID in a database.
UserID - Location
1 - /images/avatars/1.jpg
I then fetch the location of the image.
SELECT `Location` FROM `avatars` WHERE `UserID` = `1`
and there you go.
<img src=<?php echo $row['location']; ?> /> 

You would obviously fetch the location of the avatar at the same time as the other things, such as username etc. No point in doing the same thing twice.
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

hi temor,

i wasn't storing them in the database before, i had simply followed the Avatar / Profile Image Upload tutorial.

I will test this out report back if i have any issues/and also if it works - which obviously it should do ;)

thanks again,
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: user profile - image echo issue.

Post by Temor »

Alright. I'll be here if you need help :)
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

hi,

so ive been looking at this(and getting stuck quite easily) so i thought i would show you my source code.

at present all image uploads are being stored correctly in the "user_avatars" folder, and are being shown when each individuals profile is clicked - that's all working fine.

what i need to be able to do is store the images into the database, so that all images can be echoed out in the same way that the usernames are - like in the user_list part of the profile tutorial.

if you could give me a hint as to what parts of it i should be looking at, that would be a big help:

user.inc.php: - just the relevant functions

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


function set_profile_info($email,$location,$about,$avatar){
	$email 			= mysql_real_escape_string(htmlentities($email));
	$location 		= mysql_real_escape_string($location);
	$about 			= mysql_real_escape_string(nl2br(htmlentities($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");
				}
			}
	
	$sql = "UPDATE `myusers` SET
				`user_email` = '{$email}',
				`user_location` = '{$location}',
				`user_about` = '{$about}'
			WHERE `user_id` = {$_SESSION['uid']}";
				
	mysql_query($sql);
	
}

edit_profile.php - information upload
<?php
include('core/init.inc.php');

$user_info = fetch_user_info($_SESSION['uid']);

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']);
		
		}

	
$user_info = array(
	'email' 	=> htmlentities($_POST['email']),
	'location' 	=> htmlentities($_POST['location']),
	'about' 	=> htmlentities($_POST['about']),

);

}else{

$user_info = 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>site -site</title>
<meta name="Keywords" content="some keywords" />
<meta name="Description" content="content." />


<style type="text/css">
body {
	background-color: #000;
}
</style>
<link href="../CSS/layout.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a)&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a.indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a;}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers.document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
</script>

</head>

<body onload="MM_preloadImages('../Images/homepagepram_01_02_05.jpg','../Images/siteicon_01roll.jpg','../Images/siteicon_02roll.jpg','../Images/siteicon_03roll.jpg','../Images/siteicon_04roll.jpg','../Images/siteicon_05roll.jpg')">
<div id="wrapper">
<div id="logo"><img src="../Images/logo2.jpg" width="1024" height="210" border="0" usemap="#Map" />
  <map name="Map" id="Map"><area shape="rect" coords="852,159,891,202" href="https://twitter.com/#!/xxxxx" />
    <area shape="rect" coords="807,161,849,199" href="http://www.facebook.com/#!/pages/xxxxx/xxxxx" />
  </map>
</div>



<div id="navigation">
 <a href="../index.htm" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('About Us','','../Images/newbtn_01_roll.jpg',1)"><img src="../Images/newbtn_01.jpg" name="About Us" width="119" height="45" border="0" id="About Us" /></a><a href="../performerspage.htm" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Performers','','../Images/newbtn_02_roll.jpg',1)"><img src="../Images/newbtn_02.jpg" name="Performers" width="115" height="45" border="0" id="Performers" /></a><a href="../ContactPageCast.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Employers','','../Images/newbtn_03_roll.jpg',1)"><img src="../Images/newbtn_03.jpg" name="Employers" width="111" height="45" border="0" id="Employers" /></a><a href="protected.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('My Pram','','../Images/newbtn_04_roll.jpg',1)"><img src="../Images/newbtn_04.jpg" name="My Pram" width="107" height="45" border="0" id="My Pram" /></a><a href="user_list.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Contact Us','','../Images/newbtn_05_roll.jpg',1)"><img src="../Images/newbtn_05.jpg" name="Contact Us" width="117" height="45" border="0" id="Contact Us" /></a>
  


 </div>
  
  




<div id="BodyArea">

<div id="leftbar"></div>

<div id="left">
    <p>
    		<h2><?php
			if (isset($errors) === false){
				echo 'Update your profile';
			}else if (empty($errors)){
				echo 'your profiles been updated.';
			}else{
				echo '<ul><li>', implode('</li></li>', $errors), '</li></ul>';
				
			}
	
	
			?></h2>
           
    </p>

<p></p>


    <form action ="" method ="post" enctype="multipart/form-data">
    <table>
    	<tr>
        	<td>
        	<label for="email">Email:</label>
            </td>
            <td>
            <input type="text" name="email" id="email" value="<?php echo $user_info['email']; ?>" />
            </td>
         </tr>
         
      	<tr>
        	<td>
        	<label for="location">Location:</label>
            </td>
            <td>
            <input type="text" name="location" id="location" value="<?php echo $user_info['location']; ?>" />
            </td>
         </tr>
         
        	<td>
        	<label for="about">About Me:</label>
            </td>
            <td>
            <textarea name="about" id="about" rows="14" cols="40"><?php echo strip_tags($user_info['about']); ?></textarea>
            </td>
         </tr>
         
         <tr>
         	<td>
         	<label for="avatar">Profile Picture:</label>
            </td>
            <td>
         	<input type="file" name="avatar" id="avatar" />
            </td>
         </tr>
         
         <tr>
            <td>
         	<input type="submit" value="Update" />
            </td>
         </tr>
        </table>
    </form>
</div>


i know i need to look at my functions, but i can quite figure out how to format the images with their ID, its literally just that. calling/echoing im fine with.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: user profile - image echo issue.

Post by jacek »

matthewparker wrote:what i need to be able to do is store the images into the database, so that all images can be echoed out in the same way that the usernames are - like in the user_list part of the profile tutorial.

if you could give me a hint as to what parts of it i should be looking at, that would be a big help:
That will never work well. The main reason being that you can't just output raw image data as part of the page and expect the browser to know what to do with it. Plus the images are files, so it makes sense to store them as files.

Saying that, it looks like you can get what you want anyway, since the get_user_info() function returns the avatar location
echo '<img src="', $info['avatar'], '" alt="avatar" />';
:D
Image
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

thanks for your help jacek.

I think ive understood you correctly. :)

I'll attempt again and report back with my code if i have an issues!
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

hi jacek,

Ive called the fetch_user_info function, echoed out the avatar like you said, andi really don't seem to be having any luck with this.

all the users avatars are stored as the name of their user's id i.e. ' 1.jpg' in the user_avatars folder.

there is a default avatar for users who don't upload an image, i simply want to display the list of images(each image for each user whether it be their own personal image or the default one due to no upload)

here is the code again with the echo as you said.

user.inc.php
function fetch_user_info($uid){
	$uid = (int)$uid;
	
	$sql = "SELECT
				`user_id` AS `id`,
				`user_name` AS `username`,
				`user_firstname` AS `firstname`,
				`user_lastname` AS `lastname`,
				`user_email` AS `email`,
				`user_about` AS `about`,
				`user_location` AS `location`,
				`user_gender` AS `gender`
			FROM `myusers`
			WHERE `user_id` = {$uid}";
			
				
		$result = mysql_query($sql);
		
		$info = mysql_fetch_assoc($result);
		
		$info['avatar'] = (file_exists("{$GLOBALS['path']}/user_avatars/{$info['id']}.jpg")) ? "core/user_avatars/{$info['id']}.jpg" : "core/user_avatars/default.jpg" ;
				
				return $info;
				
					
}
user_list_image.php




<?php
			
			foreach (fetch_user_info($page, 5) as $user){
				?>
                
             
      <p>
          
                <?php echo     echo '<img src="', $info['avatar'], '" alt="avatar" />';
 ?>
                
            
            
      
      </p>
      <p>
      
       

      </p>
     
                
           
                <?php
				
					
			
			}
			
				
			
			
			?>

<p>
<h3>

<?php

$total_pages = ceil(fetch_total_users() / 5);
				
				for ($i = 1; $i <= $total_pages; ++$i){
					echo " <a href=\"?page={$i}\">{$i}</a>  ";
					
				}


?>
</h3>

</p>
 
 
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: user profile - image echo issue.

Post by jacek »

fetch_user_info() just returns the info for one specific user. Do you have a function that fetch all of them ? If not, you should make on :)

It should look a lot like the fetch_user_info() one but without the WHERE part of the query.
Image
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

hi, thanks for your luck but im still not having any luck here :(

this is my updated fetch_user_info function - ive taken the WHERE query away.


function fetch_user_info(){
	$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
	
	$sql = "SELECT
				`user_id` AS `id`,
				`user_name` AS `username`,
				`user_firstname` AS `firstname`,
				`user_lastname` AS `lastname`,
				`user_email` AS `email`,
				`user_about` AS `about`,
				`user_location` AS `location`,
				`user_gender` AS `gender`
			FROM `myusers`
			";
			
				
		$result = mysql_query($sql);
		
		$info = mysql_fetch_assoc($result);
		
		$info['avatar'] = (file_exists("{$GLOBALS['path']}/user_avatars/{$images['id']}.jpg")) ? "core/user_avatars/{$images['id']}.jpg" : "core/user_avatars/default.jpg" ;
		
				
				
				return $info;
				
					
}

and the php that is supposed to call the images:

user_image_list:

 
       <?php
	   foreach(fetch_user_info() as $info){
		   ?>
           <p>
           <?php echo '<img src="', $info['avatar'], '" alt="avatar" />';
 ?>
    
           </p>
           
           <?php
		   
	   }
	   
	   ?>



so '83.jpg' for example should display that image for the user with id 83(like i said before that part is all working fine, avatar file names are being saved as id no's, and you can view each persons page with there image etc).

but when i try and fetch the list of images like this, all its doing currently is outputting the 'avatar' text.

any help would be greatly appriciated at this stage, thanks again.



again any help would be much appriciated
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: user profile - image echo issue.

Post by jacek »

That's still not quite right, if you want to do it from the database you need to use a while loop to fetch all of the rows from the query
while (($row = mysql_fetch_assoc($result)) !== false){
   // do things.
}
And you don''t want to use glob() at all :?

Also I would create a new function for this, since you might need the one that fetches a specific users information at some point.

Maybe somethign like this
function fetch_users(){
	$sql = "SELECT
				`user_id`,
				`user_name`,
			FROM `myusers`";
	
	$result = mysql_query($sql);
	
	$users = array();
	
	while (($row = mysql_fetch_assoc($result)) !== false){
		$users[] = array(
			'id'		=> $row['user_id'],
			'username'	=> $row['user_name'],
			'avatar'	=> (file_exists("{$GLOBALS['path']}/user_avatars/{$images['id']}.jpg")) ? "core/user_avatars/{$images['id']}.jpg" : "core/user_avatars/default.jpg";
		);
	}
	
	return $users;
}
If the images still don''t show up, it might just be that the path is wrong.
Image
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

Thanks for your help , I will try your suggestion later.

Just one question with the above - surely I would need to define $images variable at the top of the function you suggested in order for this to work?

thanks.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: user profile - image echo issue.

Post by jacek »

matthewparker wrote: surely I would need to define $images variable at the top of the function you suggested in order for this to work?
$images['id'] should be $row['user_id'] in the loop ;)
Image
matthewparker
Posts: 10
Joined: Mon May 14, 2012 8:33 pm

Re: user profile - image echo issue.

Post by matthewparker »

OK, so ive got my code working - thanks for all the help! :)

Here is the code for reference.

Jacek, would you mind scanning over this and letting me know if you forsee any security issues with this code, or maybe anything that i should tidy up? thanks!


user.inc.php

function fetch_users_display(){
	$result = mysql_query("SELECT `user_id`, `user_name` FROM `myusers`");

	$users = array();
	
	while (($row = mysql_fetch_assoc($result)) !== false){
		$users[] = array(
				'id'		=> $row['user_id'],
				'username'	=> $row['user_name'],
				'avatar'	=> (file_exists("{$GLOBALS['path']}/user_avatars/{$row['user_id']}.jpg")) ? "core/user_avatars/{$row['user_id']}.jpg" : "core/user_avatars/default.jpg"
				
				);
		}
		
user_list.php
<body>
	<div>
	<?php
	
	foreach(fetch_users_display() as $user){
	?>
    <p>
    	<a href=""><img src ="<?php echo $user['avatar']; ?>" alt="Avatar" /></a>
    
    </p>
    <p>               
<a href="profile.php?uid=<?php echo $user['id']; ?>"><?php echo $user['username']; ?></a> 
     </p>

    <?php
	}
	
	
	
	?>
	</div>
</body>
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: user profile - image echo issue.

Post by jacek »

matthewparker wrote:Jacek, would you mind scanning over this and letting me know if you forsee any security issues with this code, or maybe anything that i should tidy up? thanks!
That looks pretty much perfect :D

The only thing you should be careful of here is the user being able to do an XSS injection with their username. It's probably not actually possible because of the username validation on signup but to be on the safe side I would do
<?php echo htmlentities($user['username']); ?>
:)
Image
Post Reply