Link to home
Start Free TrialLog in
Avatar of BrighteyesDesign
BrighteyesDesignFlag for Afghanistan

asked on

Uploading profile pic to user details PHP +MySQL

I am building a content managed business directory.

So far I have this working in that a user can login and update their details. What I want to add is the ability to upload a profile pic.

To do this I have found a script that uploads an image resizes it and send the filename to a database and the image to the server. This is fine but...the profile pic table is different to the main user info table and the two are not linked in any way.

So currently I have a table with user info and a separate table with profile image paths.

The code for the image upload form is...

 </form></td>
                    <td width="48%" align="center" valign="top">  <form action="<?php echo $editFormAction; ?>" method="POST" name="image_upload" id="image_upload" enctype="multipart/form-data">

        <!-- begin image label and input -->
            <label>SelECT Profile Photo Image (gif, jpg, png)</label><br />
            <input type="file" size="30" name="uploadfile" id="uploadfile" class="file margin_5_0" onchange="ajaxUpload(this.form);" /><!-- end image label and input --><br />
            <br />
              <!-- begin display uploaded image -->
                  <div id="upload_area" class="corners align_center">
                  please select image
                  </div><!-- begin display uploaded image -->
                    </form>


This resizes the image and calls ajax.js the in turn calls the upload.php script (both attached).

At the bottom of the upload.php script is the code that add the info to the database...

// database connection
      include('inc/db.inc.php');

                  // insert into mysql database and show success message
                  mysql_query("INSERT INTO `image_upload` (`id`, `image`, `thumbnail`, `thumbnail2`, `thumbnail3` ) VALUES (NULL, '". $image ."', 'thumb-". $image ."', 'thumb2-". $image ."', 'thumb3-". $image ."')");
        }
            // error all fileds must be filled
      } else {
            echo '<div class="wrong">You must to fill all fields!</div>'; }


What I think I need to do here is either update a 'thumbnail' row of main user profile table (rather than image_upload table). I'm just not show how to carry over the unique user id to the upload.php file inorder to achieve this or...

insert to the image_upload table but send the unique id too.

I realise this may be confusing so please fire away if you need me to clear up anything!










<?php

//----------------------------------------- start edit here ---------------------------------------------//
$script_location = "http://www.anjoman.co.uk/upload/"; // location of the script
$maxlimit = 1048576; // maxim image limit
$folder = "upload"; // folder where to save images

// requirements
$minwidth = 200; // minim width
$minheight = 200; // minim height
$maxwidth = 2400; // maxim width
$maxheight = 2400; // maxim height

//thumbnails - 1 or 0 to allow or disallow
$thumb = 1; // allow to create thumb n.1


// allowed extensions
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG');
//----------------------------------------- end edit here ---------------------------------------------//

	// check that we have a file
	if((!empty($_FILES["uploadfile"])) && ($_FILES['uploadfile']['error'] == 0)) {

	// check extension
	$extension = strrchr($_FILES['uploadfile']['name'], '.');
	if (!in_array($extension, $extensions))	{
		echo 'wrong file format, alowed only .png , .gif, .jpg, .jpeg
		<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
	} else {

// get file size
$filesize = $_FILES['uploadfile']['size'];

	// check filesize
	if($filesize > $maxlimit){ 
		echo "File size is too big.";
	} else if($filesize < 1){ 
		echo "File size is empty.";
	} else {

// temporary file
$uploadedfile = $_FILES['uploadfile']['tmp_name'];

// capture the original size of the uploaded image
list($width,$height) = getimagesize($uploadedfile);

	// check if image size is lower
	if($width < $minwidth || $height < $minheight){ 
		echo 'Image is to small. Required minimum '.$minwidth.'x'.$minheight.'
		<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
	} else if($width > $maxwidth || $height > $maxheight){ 
		echo 'Image is to big. Required maximum '.$maxwidth.'x'.$maxheight.'
		<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
	} else {

// all characters lowercase
$filename = strtolower($_FILES['uploadfile']['name']);

// replace all spaces with _
$filename = preg_replace('/\s/', '_', $filename);

// extract filename and extension
$pos = strrpos($filename, '.'); 
$basename = substr($filename, 0, $pos); 
$ext = substr($filename, $pos+1);

// get random number
$rand = time();

// image name
$image = $basename .'-'. $rand . "." . $ext;

// check if file exists
$check = $folder . '/' . $image;
	if (file_exists($check)) {
		echo 'Image already exists';
	} else {

// check if it's animate gif
$frames = exec("identify -format '%n' ". $uploadedfile ."");
	if ($frames > 1) {
		// yes it's animate image
		// copy original image
		copy($_FILES['uploadfile']['tmp_name'], $folder . '/' . $image);

		// orignal image location
		$write_image = $folder . '/' . $image;
		//ennable form
		echo '<img src="' . $write_image . '" alt="'. $image .'" alt="'. $image .'" width="300" /><br />
<input type="text" name="location" value="[IMG]'.$script_location.''.$write_image.'[/IMG]" class="location corners" />
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
	} else {

// create an image from it so we can do the resize
 switch($ext){
  case "gif":
	$src = imagecreatefromgif($uploadedfile);
  break;
  case "jpg":
	$src = imagecreatefromjpeg($uploadedfile);
  break;
  case "jpeg":
	$src = imagecreatefromjpeg($uploadedfile);
  break;
  case "png":
	$src = imagecreatefrompng($uploadedfile);
  break;
 }

// copy original image
copy($_FILES['uploadfile']['tmp_name'], $folder . '/' . $image);

// orignal image location
$write_image = $folder . '/' . $image;

if ($thumb == 1){
// create first thumbnail image - resize original to 80 width x 80 height pixels 
$newheight = ($height/$width)*200;
$newwidth = 200;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagealphablending($tmp, false);
imagesavealpha($tmp,true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// write thumbnail to disk
$write_thumbimage = $folder .'/thumb-'. $image;
 switch($ext){
  case "gif":
	imagegif($tmp,$write_thumbimage);
  break;
  case "jpg":
	imagejpeg($tmp,$write_thumbimage,100);
  break;
  case "jpeg":
	imagejpeg($tmp,$write_thumbimage,100);
  break;
  case "png":
	imagepng($tmp,$write_thumbimage);
  break;
 }
}



// all is done. clean temporary files
imagedestroy($src);
imagedestroy($tmp);

// image preview
if ($thumb == 1){
echo "<img src='" . $write_thumbimage . "' alt='". $image ."' /><br />
<input type='text' name='location' value='[IMG]".$script_location."". $write_thumbimage ."[/IMG]' class='location corners' /><br />
<br />";
}


	  }
	}
  }
}
	// database connection
	include('inc/db.inc.php');

			// insert into mysql database and show success message
			mysql_query("INSERT INTO `image_upload` (`id`, `image`, `thumbnail`, `thumbnail2`, `thumbnail3` ) VALUES (NULL, '". $image ."', 'thumb-". $image ."', 'thumb2-". $image ."', 'thumb3-". $image ."')");
	  }
		// error all fileds must be filled
	} else {
		echo '<div class="wrong">You must to fill all fields!</div>'; }
?>

Open in new window

ajax.js
Screen-shot-2011-11-02-at-15.28..png
Screen-shot-2011-11-02-at-15.29..png
Screen-shot-2011-11-02-at-15.41..png
ASKER CERTIFIED SOLUTION
Avatar of Gary Coltharp
Gary Coltharp
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BrighteyesDesign

ASKER

That sounds good xterm.

The main problem i'm having though it that the insert to database code is on a separate page (upload.php) which is called by ajax.js.

Because of this I can't figure out how to get for example the user-id on the main admin page to carry over to ajax.js and then upload.php.

The my_insert_id sounds perfect but because the insert code is not on the same page as the main admin page I can't see how to get that return value.

Hope this makes sense?
Avatar of xterm
xterm

I guess I'm a bit confused - can't you just post the user-id as a hidden field, and then right after the INSERT into the image_upload table, just do an insert into the main_user_info table directly afterwards?
why do you have 3 thumbs fields for one image?
all you need is one field for image name then reuse that image name for main image and thumb
e.g.
123.jpg 123_tumb.jpg

if you only require one picture for profile then you don not need a image table just use the user_id for image name

e.g
md5("$user_id somesalt").'jpg'
Didn't solve it completely but put me in the right direction...