Solved

PHP upload and display profile image

Posted on 2007-11-26
26
1,960 Views
Last Modified: 2012-06-21
Hello.  First off, i'm a beginner to PHP, but I'm getting into it, and would appreciate a little help. Here's what I want to do.  I've got a webpage that has user profile information, and it is pretty much finished except for the fact that I want to allow the user to add a picture of themselves in their profile page.  I have 2 documents, one that is the main page, called My_Files.php, and it is used for uploading the files.  It works fine for uploading the information to my webserver, however, once there, I need for the image to be stored inside the user's profile independently, so if that requires that I also store the image inside of my mysql table, called USER, then that is fine.  This document looks like the following:
<<<<<My_Files.php>>>>>>

<html>
<head>
<title>My Files</title>
<link rel="Stylesheet" type="text/css" href="CS170/Stylesheet2.css">
</head>
<body>
<form enctype="multipart/form-data" action="b.php" method="POST">
      <table border="0" height="96%" width="89%" id="table1">
            <tr>
                  <td width="65%">                  
<?php  
$email = $_POST['email'];
$username = $_POST['username'];  
$plaintext = $_POST['password'];  
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$profileimage = $_POST['profileimage'];
$education_level = $_POST['education_level'];
$company = $_POST['company'];
$jobtitle = $_POST['jobtitle'];
$street = $_POST['street'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$birthday = $_POST['birthday'];
$website = $_POST['website'];
$phone = $_POST['phone'];
$aboutme = $_POST['aboutme'];
$resume = $_POST['resume'];
$ciphertext = md5($plaintext);
$rv = mysql_connect("localhost","USERNAME","PASSWORD");  
mysql_select_db("DATABASENAME");  
$qs = "select * from USER where username='$username';";  
$result = mysql_query($qs);  
$nrows = mysql_numrows($result);
$query = mysql_query($qs);
while ($row = mysql_fetch_array($query))  
if($nrows == 1)
{    
$dbpass = mysql_result($result, 0, "password");            
{
}  
$dbpass = mysql_result($result, 0, "password");    
$dbpass = mysql_result($result, 0, "password");    
if($dbpass == $ciphertext)
{      
echo "<h1> " ."Welcome " . $username . "!" . "</h1> " . "\n";
printf("<img border='0' src='Images\Profiles\NoImage.gif'>\n");
printf("<input type='hidden' name='MAX_FILE_SIZE' value='100000'>\n");
echo "<h2>" . "Upload a Profile Picture: " . "</h2>" . "\n";
printf("<input name='file' type='file'>\n");
printf("<input type='submit' value='Add Picture'>\n");
echo "<br>" . "\n";
echo "<br>" . "\n";
echo "<h2> " ,$row['fname'] ." " . $row['lname'] . "<br> " .  "Email: " ,$row['email'] . "</h2> " . "\n";
echo "<h3> " ."Other Information";  
echo "<h4> " ."Name: " .$row['fname'] ." " . $row['lname'] . "<br> " .  "Education Level: " .$row['education_level'] . "<br> " .  "Current Employer: " .$row['company'] . "<br> " .  "Job Title: " .$row['jobtitle']. "<br> " .  "Address: " .$row['street'] . "<br> " .  "City: " .$row['city'] . "<br> " .  "State: " .$row['state'] . "<br> " .  "Zip Code: " .$row['zip'] . "<br> " .  "Birthday: " .$row['birthday'] . "<br> " .  "Website: " .$row['website'] . "<br> " .  "Phone Number: " .$row['phone'] . "</h4> " . "\n";  
echo "<h3> " ."My Background " . "</h3> " . "\n";
echo "<h4> " .$row['aboutme'] . "</h4> " . "\n";
echo "<h3> " . "Skills" . "</h3>" . "<br> " . "<h4> " .$row['resume'] . "</h4>" . "\n";
printf("<input type='hidden' name='email' value='$email'>\n");    
printf("<input type='hidden' name='username' value='$name'>\n");    
printf("<input type='hidden' name='password' value='$ciphertext'>\n");
printf("<input type='hidden' name='fname' value='$fname'>\n");
printf("<input type='hidden' name='lname' value='$lname'>\n");            
printf("</form>\n");  
}
else
{      
printf("<h1>Password incorrect.</h1><br><br><br><br><br><br>\n");    
}  
}
else
{    
printf("<h1>Invalid name: %s</h1>\n",$username);  
}  
mysql_close();
?>
<td width="40%"></td>      
</tr>
</form>
</table>
</body>
</html>

While b.php is the document that processes when they attempt to upload the information.  It looks as follows:

<<<<<<<<b.php>>>>>>>>

<?php
 $username = $_POST['username'];
 $profileimage = $_POST['profileimage'];
 mysql_connect("localhost","USERNAME","PASSWORD");  
 mysql_select_db("DATABASE");
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 100000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    if (file_exists("FILEPATHNAMECHANGED" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "/FILEPATHNAMECHANGED" . $_FILES["file"]["name"]);
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

My question is, how would I use this to display the image that is uploaded onto My_Files.php when it is next loaded?  If I need to use a sql statement to pull info that's fine, but I'm a little lost.  Help please!!!
0
Comment
Question by:lstraw
  • 13
  • 13
26 Comments
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
Easyist way is after here

    move_uploaded_file($_FILES["file"]["tmp_name"],
    "/FILEPATHNAMECHANGED" . $_FILES["file"]["name"]);

do an sql that updates the users record in the database to set there imagefile to
$_FILES["file"]["name"]
ie
UPDATE user SET image_file=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE id=".$row['id'];

now, your page has some large security issues, SQL injection and XSS. You need to escape/sanatize all user input! Do a google search will provide you with some articles.
0
 

Author Comment

by:lstraw
Comment Utility
I should have probably specified, sorry for that, but I'm not completely concerned about security right now.  Still beginning, trying to teach myself some about php, and that's all I'm doing at this point, trying to learn some basic things, I'm sure right now it would be very easy to hack this.   Once it's put together, I'll go back and try to implement some security measures, may not be the best way of thinking about it, but it's all I can do at this point.  Thank you very much for your suggestion, and I'll try that later this evening, greatly appreciate your help.
0
 

Author Comment

by:lstraw
Comment Utility
OK, tried it, but with no success, although I'm not sure I did it right.  Forgive my ignorance, but would I insert the SQL Statement exactly how you typed it, or would I add anything?  Also, my unique identifier is the username field, which I substituted for ID.  Is that ok?  The mysql field I would use to put the file into would be field name of "profileimage".  Finally, once this information works, how would I display the image in My_Files.php?  I'm raising the points, as I see now that this is a big question, but please to avoid confusion, is there any way you could copy the code I'm using and modify, letting me know of any variables that need to be changed, besides the obvious variables which I've made all caps?  Once I see it in front of me, then I can figure out what's going on, but right now I'm kind of lost, sorry.  
0
 
LVL 10

Accepted Solution

by:
wildzero earned 350 total points
Comment Utility
Make sure username is included in the form (with the image).
Update your database to include a profileimage column.

Then on your other page you should be able to do
echo '<img src="/FILEPATHNAMECHANGED' . $row['profileimage'].'"'>


<?php

 $username = $_POST['username'];

 $profileimage = $_POST['profileimage'];

 mysql_connect("localhost","USERNAME","PASSWORD");  

 mysql_select_db("DATABASE");

 

 

if (($_FILES["file"]["type"] == "image/gif")

|| ($_FILES["file"]["type"] == "image/jpeg")

|| ($_FILES["file"]["type"] == "image/pjpeg")

&& ($_FILES["file"]["size"] < 100000))

  {

  if ($_FILES["file"]["error"] > 0)

    {

    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    }

  else

    {

    echo "Upload: " . $_FILES["file"]["name"] . "<br />";

    echo "Type: " . $_FILES["file"]["type"] . "<br />";

    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

    if (file_exists("FILEPATHNAMECHANGED" . $_FILES["file"]["name"]))

      {

      echo $_FILES["file"]["name"] . " already exists. ";

      }

    else

      {

      move_uploaded_file($_FILES["file"]["tmp_name"],

      "/FILEPATHNAMECHANGED" . $_FILES["file"]["name"]);

      

      mysql_query("UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username)) OR DIE("ERROR: ".mysql_error());

      }

    }

  }

else

  {

  echo "Invalid file";

  }

Open in new window

0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
Also you want to be checking the type of file they are uploading.
You don't want them uploading a php or other executable file - that would be a disaster!
0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
0
 

Author Comment

by:lstraw
Comment Utility
Thanks for the tip, i'll keep that in mind.  Appreciate all of your help so far.  I tried this last bit of code, and I get the following:

Upload: pic.jpg
Type: image/pjpeg
Size: 36.4765625 Kb
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

When I use the following:
<?php
 $username = $_POST['username'];
 $profileimage = $_POST['profileimage'];
 mysql_connect("localhost","USERNAME","PASSWORD");  
 mysql_select_db("DATABASE");
 
 
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 100000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    if ("FILEPATHNAMECHANGED" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "FILEPATHNAMECHANGED" . $_FILES["file"]["name"]);
     
      mysql_query("UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username)) OR DIE("ERROR: ".mysql_error());
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Any thoughts?
0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
change this
 mysql_query("UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username)) OR DIE("ERROR: ".mysql_error());


to

die("| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username))." |");
that should show us what is being executed.

Also you added the column profileimage to your USER table?
0
 

Author Comment

by:lstraw
Comment Utility
I tried that, when I added that line, it brings up a blank screen as if there is an error somewhere.  Where am I adding the column profileimage to my USER table?  As far as I could tell I simply copied the code you gave me and changed the basic variables.  I know we have to be close, what are we missing?
0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
You need to update your database table
to add another column called profileimage - this is where the profileimage data is stored for the user. Same table that has the username, email address etc etc.

0
 

Author Comment

by:lstraw
Comment Utility
Sorry, just caught that.  Yes, I did that to start, I didn't know what you meant, but there is already a column called profileimage in my table called USER.  Also, if it helps, it seems I keep getting the blank screens whenever I add the DIE function to the SQL Statement.  Otherwise, it runs fine other than the fact that it isn't adding the image to my table.  I know this is where we determine the errors, but does this help at all?
0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
die there
the die function will cause the script to end, but by placing the sql statement in the die function it should cause it to display the statement.

lets try this again.

echo "| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username))." |";
die();
0
 

Author Comment

by:lstraw
Comment Utility
Sorry, no luck.  Still have a blank screen when it goes to b.php.  Want to ensure I'm doing this right, I'm using the following:

move_uploaded_file($_FILES["file"]["tmp_name"],
      "/FILEPATHNAMECHANGED" . $_FILES["file"]["name"]);
      echo "| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username))." |";
      die();

If this is correct, it still isn't showing up for some reason.  
move_uploaded_file($_FILES["file"]["tmp_name"],

"/FILEPATHNAMECHANGED" . $_FILES["file"]["name"]);

echo "| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username))." |";

die();

Open in new window

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:lstraw
Comment Utility
My MySQL Version is 5.0.37, not sure if that helps or not, but the error msg it was giving was:
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1.

Does that affect the query syntax we are using at all?
0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
echo "| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES['file']['name'])." WHERE username=".mysql_real_escape_string($username))." |";

Can you change it to that please.
0
 

Author Comment

by:lstraw
Comment Utility
OK, took that and got a blank screen.  So I removed the final ) and got the following to use:
echo "| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES['file']['name'])." WHERE username=".mysql_real_escape_string($username)." |";

This gave me the following result:

Are we on the right track?
Upload: Pic.jpg

Type: image/pjpeg

Size: 16.986328125 Kb

| UPDATE USER set profileimage=Pic.jpg WHERE username= | 

Open in new window

0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
Right!
This shows that $username is not getting set.
So in the form that is posting the image, it needs to post the username as well.

In your script you have
$username = $_POST['username'];

But you need to make it so that is set in the forum.
So edit your forum on the other page to include the username.

then change
echo "| UPDATE USER set profileimage=".mysql_real_escape_string($_FILES['file']['name'])." WHERE username=".mysql_real_escape_string($username)." |";

back to

 mysql_query("UPDATE USER set profileimage=".mysql_real_escape_string($_FILES["file"]["name"])." WHERE username=".mysql_real_escape_string($username)) OR DIE("ERROR: ".mysql_error());

and you should be set.
0
 

Author Comment

by:lstraw
Comment Utility
OK, looks like we're close.  You said to edit the forum on the other page to include the username.  I thought I had, so I guess we're not on the same page.  I'm attaching the code from my first page for you to review, but just in case, I added a hidden field for the username, and I also referenced it at the top with a
$username = $_POST['username'];
as you can see.  Yet, I'm still getting the following error when I upload now:
Upload: PIC.jpg
Type: image/pjpeg
Size: 16.986328125 Kb
ERROR: Unknown column 'USER123' in 'where clause'

With USER123 being the username that is currently logged on.  What am I missing?
<HTML>

<body>

<form enctype="multipart/form-data" action="b.php" method="POST">

<?php  

$email = $_POST['email'];

$username = $_POST['username'];  

$plaintext = $_POST['password'];  

$fname = $_POST['fname'];

$lname = $_POST['lname'];

$profileimage = $_POST['profileimage'];

$education_level = $_POST['education_level'];

$company = $_POST['company'];

$jobtitle = $_POST['jobtitle'];

$street = $_POST['street'];

$city = $_POST['city'];

$state = $_POST['state'];

$zip = $_POST['zip'];

$birthday = $_POST['birthday'];

$website = $_POST['website'];

$phone = $_POST['phone'];

$aboutme = $_POST['aboutme'];

$resume = $_POST['resume'];

$ciphertext = md5($plaintext);

$rv = mysql_connect("localhost","USERNAME","PASSWORD");  

mysql_select_db("DATABASE");  

$qs = "select * from USER where username='$username';";  

$result = mysql_query($qs);  

$nrows = mysql_numrows($result);

$query = mysql_query($qs);

while ($row = mysql_fetch_array($query))  

if($nrows == 1)

{    

$dbpass = mysql_result($result, 0, "password");             

{

}   

$dbpass = mysql_result($result, 0, "password");    

$dbpass = mysql_result($result, 0, "password");    

if($dbpass == $ciphertext)

{      

echo "<h1> " ."Welcome " . $username . "!" . "</h1> " . "\n"; 

echo "<h3>" . $now . "</h3>";

printf("<input type='hidden' name='email' value='$email'>\n");    

printf("<input type='hidden' name='username' value='$name'>\n");    

printf("<input type='hidden' name='password' value='$ciphertext'>\n");

printf("<input type='hidden' name='fname' value='$fname'>\n");

printf("<input type='hidden' name='lname' value='$lname'>\n"); 

printf("<input type='hidden' name='username' value='$username'>\n");

printf("<img border='0' src='Images\Profiles\NoImage.gif'>\n");

printf("<input type='hidden' name='profileimage' value='$profileimage'>\n");

echo '<img src="/u1/class/cs17013/public_html/Images/Profiles/' . $row['profileimage'].'"'>

printf("<input type='hidden' name='MAX_FILE_SIZE' value='100000'>\n");

echo "<h2>" . "Upload a Profile Picture: " . "</h2>" . "\n";

printf("<input name='file' type='file'>\n");

printf("<input type='submit' value='Add Picture'>\n");

echo "<h2> " ,$row['username'] . "<br> " . $row['fname'] ." " . $row['lname'] . "<br> " .  "Email: " ,$row['email'] . "</h2> " . "\n";

echo "<h3> " ."Other Information";  

echo "<h4> " ."Name: " .$row['fname'] ." " . $row['lname'] . "<br> " .  "Education Level: " .$row['education_level'] . "<br> " .  "Current Employer: " .$row['company'] . "<br> " .  "Job Title: " .$row['jobtitle']. "<br> " .  "Address: " .$row['street'] . "<br> " .  "City: " .$row['city'] . "<br> " .  "State: " .$row['state'] . "<br> " .  "Zip Code: " .$row['zip'] . "<br> " .  "Birthday: " .$row['birthday'] . "<br> " .  "Website: " .$row['website'] . "<br> " .  "Phone Number: " .$row['phone'] . "</h4> " . "\n";   

echo "<h3> " ."My Background " . "</h3> " . "\n";

echo "<h4> " .$row['aboutme'] . "</h4> " . "\n";

echo "<h3> " . "Skills" . "</h3>" . "<br> " . "<h4> " .$row['resume'] . "</h4>" . "\n";         

printf("</form>\n");   

} 

else 

{      

printf("<h1>Password incorrect.</h1><br><br><br><br><br><br>\n");    

}  

} 

else 

{    

printf("<h1>Invalid name: %s</h1>\n",$username);  

}  

mysql_close();

?>

<td width="40%"></td>	

</tr>

</form>

</table>

</body>

</html>

Open in new window

0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
quotes around the item

mysql_query("UPDATE USER set profileimage=\"".mysql_real_escape_string($_FILES["file"]["name"])."\" WHERE username=\"".mysql_real_escape_string($username)."\"") OR DIE("ERROR: ".mysql_error());

0
 

Author Comment

by:lstraw
Comment Utility
OK, it worked!!  One more thing though and I'll award points.  You said to use the following for displaying the image on the other page, for some reason it's not showing up.  The image is being stored in the MySql database, I checked that, but if I use the following it doesn't show up.  I tried an apostrophe afterwards, and a few options, still with no luck.  Am I missing anything?
echo '<img src="/FILEPATHNAMECHANGED' . $row['profileimage'].'"'>

Open in new window

0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
View your source code and see what it's out putting.
Make sure that /FILEPATHNAMECHANGED is the correct file path
Look in the folder that has your images and make sure it shows up there.
0
 

Author Comment

by:lstraw
Comment Utility
It shows up in images, and the source code doesn't even recognize that an image is supposed to show up. That's why I'm wondering if there is something wrong with the syntax of it.  I tried the filepath that was used in the previous file, as well as trying the web address, and the web address shows the image in the browser.  Any other ideas would be greatly appreciated.
0
 
LVL 10

Assisted Solution

by:wildzero
wildzero earned 350 total points
Comment Utility
echo '<img src="/FILEPATHNAMECHANGED' . $row['profileimage'].'">';


0
 

Author Closing Comment

by:lstraw
Comment Utility
Very good job working with me as a beginner.  Thank you.
0
 

Author Comment

by:lstraw
Comment Utility
Thanks wildzero, works great now.  Greatly appreciated!!
0
 
LVL 10

Expert Comment

by:wildzero
Comment Utility
phew :-) lol was a effort lol
make sure to make it all secure!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now