We help IT Professionals succeed at work.
Get Started

Uploading profile pic to user details PHP +MySQL

BrighteyesDesign
on
3,343 Views
Last Modified: 2012-05-12
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
Comment
Watch Question
Sr. Systems Engineer
Commented:
This problem has been solved!
Unlock 2 Answers and 6 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE