Registration / Image Upload Problem

Hi there,

Not sure if anyone can help me with a coding problem that has arisen when creating a user registration system with an image upload. Everything was working great until I began coding the image upload feature (I want to force users to add a profile picture image when registering). If all the parameters are entered correctly, the script works properly and will upload their picture and display it with their other profile information. However, I am getting an undefined index error that is conflicting with the scripts internal error reporting, thereby causing it to fail.

Here is the relevant php:

if (isset ($_POST['username'])){
	 
	 $username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']); // filter everything but letters and numbers
	 $gender = preg_replace('#[^a-z]#i', '', $_POST['gender']); // filter everything but lowercase letters
	 $b_m = preg_replace('#[^0-9]#i', '', $_POST['birth_month']); // filter everything but numbers
     $b_d = preg_replace('#[^0-9]#i', '', $_POST['birth_day']); // filter everything but numbers
	 $b_y = preg_replace('#[^0-9]#i', '', $_POST['birth_year']); // filter everything but numbers
     $email1 = $_POST['email1'];
     $email2 = $_POST['email2'];
     $pass1 = $_POST['pass1'];
     $pass2 = $_POST['pass2'];
	 $user_pic = $_POST['user_pic'];

     include_once "scripts/connect_to_mysql.php";
     $emailCHecker = mysql_real_escape_string($email1);
	 $emailCHecker = str_replace("`", "", $emailCHecker);
	 $sql_uname_check = mysql_query("SELECT username FROM myMembers WHERE username='$username'"); 
     $uname_check = mysql_num_rows($sql_uname_check);
     $sql_email_check = mysql_query("SELECT email FROM myMembers WHERE email='$emailCHecker'");
     $email_check = mysql_num_rows($sql_email_check);
     if ((!$username) || (!$gender) || (!$b_m) || (!$b_d) || (!$b_y) || (!$email1) || (!$email2) || (!$pass1) || (!$pass2) || (!$user_pic)) { 

     $errorMsg = 'ERROR: You did not submit the following required information:<br /><br />';
  
     if(!$username){ 
       $errorMsg .= ' * User Name<br />';
     } 
     if(!$gender){ 
       $errorMsg .= ' * Gender: Confirm your sex.<br />';
     } 	
	 if(!$b_m){ 
       $errorMsg .= ' * Birth Month<br />';      
     }
	 if(!$b_d){ 
       $errorMsg .= ' * Birth Day<br />';        
     } 
	 if(!$b_y){ 
       $errorMsg .= ' * Birth year<br />';        
     } 		
	 if(!$email1){ 
       $errorMsg .= ' * Email Address<br />';      
     }
	 if(!$email2){ 
       $errorMsg .= ' * Confirm Email Address<br />';        
     } 	
	 if(!$pass1){ 
       $errorMsg .= ' * Login Password<br />';      
     }
	 if(!$pass2){ 
       $errorMsg .= ' * Confirm Login Password<br />';        
     } 	
	 if(!$user_pic){ 
       $errorMsg .= ' * Add a Profile Plank<br />';        
     } 	
	
     } else if ($email1 != $email2) {
              $errorMsg = 'ERROR: Your Email fields below do not match<br />';
     } else if ($pass1 != $pass2) {
              $errorMsg = 'ERROR: Your Password fields below do not match<br />';
     } else if (strlen($username) < 4) {
	           $errorMsg = "<u>ERROR:</u><br />Your User Name is too short. 4 - 20 characters please.<br />"; 
     } else if (strlen($username) > 20) {
	           $errorMsg = "<u>ERROR:</u><br />Your User Name is too long. 4 - 20 characters please.<br />"; 
     } else if ($uname_check > 0){ 
              $errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside of our system. Please try another.<br />"; 
     } else if ($email_check > 0){ 
              $errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside of our system. Please use another.<br />"; 
     } else if ($_FILES['user_pic']['tmp_name'] != "") { 
            $maxfilesize = 51200; // 51200 bytes equals 50kb
            if($_FILES['user_pic']['size'] > $maxfilesize ) { 

                        $error_msg = '<font color="#FF0000">ERROR: Your image was too large, please try again.</font>';
                        unlink($_FILES['user_pic']['tmp_name']); 

            } else if (!preg_match("/\\.(gif|jpg|png)$/i", $_FILES['user_pic']['name'] ) ) {

                        $error_msg = '<font color="#FF0000">ERROR: Your image was not one of the accepted formats, please try again.</font>';
                        unlink($_FILES['user_pic']['tmp_name']); 
			}

    } { 
     $email1 = mysql_real_escape_string($email1);
     $pass1 = mysql_real_escape_string($pass1);
     $db_password = md5($pass1); 
	 $full_birthday = "$b_y-$b_m-$b_d";
     $ipaddress = getenv('REMOTE_ADDR');

     $sql = mysql_query("INSERT INTO myMembers (username, gender, birthday, email, password, ipaddress, sign_up_date) 
     VALUES('$username','$gender','$full_birthday','$email1','$db_password', '$ipaddress', now())")  
     or die (mysql_error());
 
     $id = mysql_insert_id();

     mkdir("members/$id", 0755);
          $newname = "image01.jpg";
          $place_file = move_uploaded_file( $_FILES['user_pic']['tmp_name'], "members/$id/".$newname);

   
   include_once 'msgToUser.php'; 
   exit();

   }

} else { // if the form is not posted with variables, place default empty variables so no warnings or errors show
	  
	  $errorMsg = "";
      $username = "";
	  $gender = "";
	  $b_m = "";
	  $b_d = "";
	  $b_y = "";
	  $email1 = "";
	  $email2 = "";
	  $pass1 = "";
	  $pass2 = "";
	  $user_pic = "";
}


And the html form:


    <table class="table_f" width="100%" cellpadding="3"> 
       <form action="register.php" method="post" enctype="multipart/form-data">
          <tr>
            <td colspan="2"><font color="#94A0D1"><?php print "$errorMsg"; ?></font></td></tr>       
          <tr><td><h11>Add Profile Photo: </h11></td>         
              <td width="521"><input name="user_pic" type="file" class="formFields" id="user_pic" size="42" />
              50 kb max </td></tr> 
          <tr><td>
              <input type="submit" style="color: #a2a2a2; font-family: helvetica; font-size: 11px; letter-spacing: 1px" name="Submit" value="Register" /></td></tr>
        </form>
      </table>

I am getting an undefined index for “user_pic” on line

$user_pic = $_POST['user_pic'];

that seems to be conflicting with the scripts internal error reporting. When everything is entered properly, the script works fine. But if the user inputs incorrect information (i.e. image too large, duplicate username, invalid email, etc) the script fails.

Does anyone have any ideas? I feel as if I have painted myself into a corner.

Thanks in advance for any suggestions.
nbewley


if (isset($_POST['user_pic'])) {
$user_pic = $_POST['user_pic'];
} else {
// give an error message here
}

Sorry to be dense here.

But where would I implement if (isset($_POST[‘user_pic’])) { ? I tried it in a variety of places but couldn’t find the proper way to implement it. If I add it in the beginning my form does not seem to submit.

I made a few other adjustments that seemed to benefit (changed $user_pic = $_POST[‘user_pic’]:wink: to ($user_pic = $_FILES[‘user_pic’];), for example, but have yet to get all the error messages to work simultaneously.

Thank you very much for contributing to my understanding. Any further elaboration is very appreciated.

Thanks,
nbewley

$_FILES[‘user_pic’] is not sent through the POST array!
therefore it wont ever exist.

You would need to check the $_FILES[‘error’] number to see if an image has been uploaded.
In this case the error number is 4 so


if($_FILES['error'] == 4) {
    //throw the error message because no file was uploaded
} else {
    // do something else
}

Ref: http://php.net/manual/en/features.file-upload.errors.php

Thank you both very much for your inputs. Although I felt quite close to a workable code, I encountered too many problems implementing the right error codes to accompany, so I am attempting to reformulate the code. I’m not sure if anyone has any further advice for me based on the recent attempt listed below.

I understand that there might be many errors in my construction, but any helpful thoughts would be appreciated.


<?php

// sorry guessing here with this first line. Not sure if this is the appropriate way to construct the isset(). Not sure if && is the proper comparison.
if( isset( $_FILES['user_pic'] ) && isset( $_POST['username'] ) ) {
    $username = isset( $_POST['username'] ) ? $_POST["username"] : '';
    $gender = isset( $_POST['gender'] ) ? $_POST["gender"] : '';
    $b_m = isset( $_POST['b_m'] ) ? $_POST["b_m"] : '';
    $b_d = isset( $_POST['b_d'] ) ? $_POST["b_d"] : '';
    $b_y = isset( $_POST['b_y'] ) ? $_POST['b_y'] : '';
    $email1 = isset( $_POST['email1'] ) ? $_POST["email1"] : '';
    $email2 = isset( $_POST['email2'] ) ? $_POST["email2"] : '';
    $pass1 = isset( $_POST['pass1'] ) ? $_POST["pass1"] : '';
    $pass2 = isset( $_POST['pass2'] ) ? $_POST["pass2"] : '';
    $user_pic = isset( $_FILES['user_pic'] ) ? $_FILES["user_pic"] : '';
        
    include_once "scripts/connect_to_mysql.php";
    $emailCHecker = mysql_real_escape_string($email1);
    $emailCHecker = str_replace("`", "", $emailCHecker);
    $sql_uname_check = mysql_query("SELECT username FROM myMembers WHERE username='$username'"); 
    $uname_check = mysql_num_rows($sql_uname_check);
    $sql_email_check = mysql_query("SELECT email FROM myMembers WHERE email='$emailCHecker'");
    $email_check = mysql_num_rows($sql_email_check);

    $maxfilesize = 51200; 

    $errormessage =  array();
    if( empty( $username ) )
        $errormessage[] = "Please enter a username";
    if( empty( $gender ) )
        $errormessage[] = "Please identify your gender";
    if( empty( $b_m ) )
        $errormessage[] = "Please select the month of your birth";
    if( empty( $b_d ) )
        $errormessage[] = "Please select the day of your birth";
    if( empty( $b_y ) )
        $errormessage[] = "Please select the year you were born";
    if( empty( $email1 ) )
        $errormessage[] = "Please enter your email address";
    if( empty( $email2 ) )
        $errormessage[] = "Please verify your email by re-entering it";
    if( empty( $pass1 ) )
        $errormessage[] = "Please enter a password";
    if( empty( $pass2 ) )
        $errormessage[] = "Please verify your password by re-entering it";
    if( $email1 != $email2 )
        $errormessage[] = "Your email entries do not match";
    if( $pass1 != $pass2 )
        $errormessage[] = "Your password entries do not match";
    if( strlen( $username ) < 4 ) 
        $errormessage[] = "Your username must be longer than 4 characters";
    if( strlen( $username ) > 20 )
        $errormessage[] = "Your username must be shorter than 20 characters";
    if( $uname_check > 0 )
        $errormessage[] = "Your username is already inside of our system";
    if( $email_check > 0 )
        $errormessage[] = "Your email is already inside of our system";
    if( $_FILES['user_pic']['tmp_name'] != "" )
        $errormessage[] = "You must upload an image";
        unlink($_FILES['user_pic']['tmp_name']); 
    if( $_FILES['user_pic']['size'] > $maxfilesize )
        $errormessage[] = "Your image is too large";
        unlink($_FILES['user_pic']['tmp_name']); 
    if( !preg_match("/\\.(gif|jpg|png)$/i", $_FILES['user_pic']['name'] ) )
        $errormessage[] = "Your image is in an unacceptabe format";
        unlink($_FILES['user_pic']['tmp_name']); 
    // sorry this might be the wrong way to construct this error
    if( $_FILES['user_pic']['error'] == 4 )
        $errormessage[] = "There was an error uploading your image";
        unlink($_FILES['user_pic']['tmp_name']); 

    } else {
         
    // Add MD5 Hash to the password variable
    $db_password = md5($pass1); 
         
    // Convert Birthday to a DATE field type format(YYYY-MM-DD) out of the month, day, and year supplied 
    $full_birthday = "$b_y-$b_m-$b_d";

    // GET USER IP ADDRESS
    $ipaddress = getenv('REMOTE_ADDR');

    // Add user info into the database table for the main site table
    $sql = mysql_query("INSERT INTO myMembers (username, gender, birthday, email, password, ipaddress, sign_up_date) 
    VALUES('$username','$gender','$full_birthday','$email1','$db_password', '$ipaddress', now())")  
    or die (mysql_error());
 
    $id = mysql_insert_id();
         
    // Create directory to hold each user's files(pics, MP3s, etc.)             
    mkdir("members/$id", 0755); 
    $newname = "image01.jpg";
    $place_file = move_uploaded_file( $_FILES['user_pic']['tmp_name'], "members/$id/".$newname);
        
    }
        
?>

<!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=iso-8859-1" />
<meta name="Description" content="Register to yourdomain" />
<meta name="Keywords" content="register, yourdomain" />
<meta name="rating" content="General" />
<title>Register at <?php echo $dyn_www; ?></title>
<link href="style/main.css" rel="stylesheet" type="text/css" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript"> 
$(document).ready(function() {
        $("#username").blur(function() {
                $("#nameresponse").removeClass().text('Checking Username...').fadeIn(1000);
                $.post("scripts/check_signup_name.php",{ username:$(this).val() } ,function(data) {
                        $("#nameresponse").fadeTo(200,0.1,function() { 
                          $(this).html(data).fadeTo(900,1);     
                        });
        });
        });
});
function toggleSlideBox(x) {
                if ($('#'+x).is(":hidden")) {
                        $('#'+x).slideDown(300);
                } else {
                        $('#'+x).slideUp(300);
                }
}
</script>
<style type="text/css">
<!--
.style26 {color: #FF0000}
.style28 {font-size: 14px}
.brightRed {
        color: #F00;
}
.textSize_9px {
        font-size: 9px;
}
-->
</style>
</head>
<body>

<?php include_once "header_template.php"; ?>

<br />
<div id="table">
        <center><h4>Create your Account: </h4><h9>all fields required</h9></center>
<div class="hr5"> </div>
<br />
        
<table class="table_f" width="100%" cellpadding="3">
        
    <form action="register.php" method="post" enctype="multipart/form-data">
        
        <tr><td colspan="2"><font color="#94A0D1"><?php print "$errormessage"; ?></font></td></tr>       
        <tr><td><h11>User Name:</h11></td><td><input name="username" type="text" class="formFields" id="username" value="<?php print "$username"; ?>" size="32" maxlength="20" /></tr>

        <tr><td><h11>Gender:</h11></td>
        <td><label><input name="gender" style="color: #a2a2a2; font-family: 'light', Verdana; font-size: 11px; letter-spacing: 1px" type="radio" id="gender" value="m" checked="checked" />Male  <input type="radio" name="gender" id="gender" value="f" />Female</label></td></tr>
 
        <tr><td><h11>Date of Birth: </h11></td>
        <td>
            <select name="birth_month" class="formFields" id="birth_month">
            <option value="<?php print "$b_m"; ?>"><?php print "$b_m"; ?></option>
            <option value="01">January</option>
            <option value="02">February</option>
            <option value="03">March</option>
            <option value="04">April</option>
            <option value="05">May</option>
            <option value="06">June</option>
            <option value="07">July</option>
            <option value="08">August</option>
            <option value="09">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
            </select> 
            <select name="birth_day" class="formFields" id="birth_day">
            <option value="<?php print "$b_d"; ?>"><?php print "$b_d"; ?></option>
            <option value="01">1</option>
            <option value="02">2</option>
            <option value="03">3</option>
            <option value="04">4</option>
            <option value="05">5</option>
            <option value="06">6</option>
            <option value="07">7</option>
            <option value="08">8</option>
            <option value="09">9</option>
            <option value="10">10</option>
            <option value="11">11</option>
            <option value="12">12</option>
            <option value="13">13</option>
            <option value="14">14</option>
            <option value="15">15</option>
            <option value="16">16</option>
            <option value="17">17</option>
            <option value="18">18</option>
            <option value="19">19</option>
            <option value="20">20</option>
            <option value="21">21</option>
            <option value="22">22</option>
            <option value="23">23</option>
            <option value="24">24</option>
            <option value="25">25</option>
            <option value="26">26</option>
            <option value="27">27</option>
            <option value="28">28</option>
            <option value="29">29</option>
            <option value="30">30</option>
            <option value="31">31</option>
            </select> 
            <select name="birth_year" class="formFields" id="birth_year">
            <option value="<?php print "$b_y"; ?>"><?php print "$b_y"; ?></option>
            <option value="2010">2010</option>
            <option value="2009">2009</option>
            <option value="2008">2008</option>
            <option value="2007">2007</option>
            <option value="2006">2006</option>
            <option value="2005">2005</option>
            <option value="2004">2004</option>
            <option value="2003">2003</option>
            <option value="2002">2002</option>
            <option value="2001">2001</option>
            <option value="2000">2000</option>
            <option value="1999">1999</option>
            <option value="1998">1998</option>
            <option value="1997">1997</option>
            <option value="1996">1996</option>
            <option value="1995">1995</option>
            <option value="1994">1994</option>
            <option value="1993">1993</option>
            <option value="1992">1992</option>
            <option value="1991">1991</option>
            <option value="1990">1990</option>
            <option value="1989">1989</option>
            <option value="1988">1988</option>
            <option value="1987">1987</option>
            <option value="1986">1986</option>
            <option value="1985">1985</option>
            <option value="1984">1984</option>
            <option value="1983">1983</option>
            <option value="1982">1982</option>
            <option value="1981">1981</option>
            <option value="1980">1980</option>
            <option value="1979">1979</option>
            <option value="1978">1978</option>
            <option value="1977">1977</option>
            <option value="1976">1976</option>
            <option value="1975">1975</option>
            <option value="1974">1974</option>
            <option value="1973">1973</option>
            <option value="1972">1972</option>
            <option value="1971">1971</option>
            <option value="1970">1970</option>
            <option value="1969">1969</option>
            <option value="1968">1968</option>
            <option value="1967">1967</option>
            <option value="1966">1966</option>
            <option value="1965">1965</option>
            <option value="1964">1964</option>
            <option value="1963">1963</option>
            <option value="1962">1962</option>
            <option value="1961">1961</option>
            <option value="1960">1960</option>
            <option value="1959">1959</option>
            <option value="1958">1958</option>
            <option value="1957">1957</option>
            <option value="1956">1956</option>
            <option value="1955">1955</option>
            <option value="1954">1954</option>
            <option value="1953">1953</option>
            <option value="1952">1952</option>
            <option value="1951">1951</option>
            <option value="1950">1950</option>
            <option value="1949">1949</option>
            <option value="1948">1948</option>
            <option value="1947">1947</option>
            <option value="1946">1946</option>
            <option value="1945">1945</option>
            <option value="1944">1944</option>
            <option value="1943">1943</option>
            <option value="1942">1942</option>
            <option value="1941">1941</option>
            <option value="1940">1940</option>
            <option value="1939">1939</option>
            <option value="1938">1938</option>
            <option value="1937">1937</option>
            <option value="1936">1936</option>
            <option value="1935">1935</option>
            <option value="1934">1934</option>
            <option value="1933">1933</option>
            <option value="1932">1932</option>
            <option value="1931">1931</option>
            <option value="1930">1930</option>
            <option value="1929">1929</option>
            <option value="1928">1928</option>
            <option value="1927">1927</option>
            <option value="1926">1926</option>
            <option value="1925">1925</option>
            <option value="1924">1924</option>
            <option value="1923">1923</option>
            <option value="1922">1922</option>
            <option value="1921">1921</option>
            <option value="1920">1920</option>
            <option value="1919">1919</option>
            <option value="1918">1918</option>
            <option value="1917">1917</option>
            <option value="1916">1916</option>
            <option value="1915">1915</option>
            <option value="1914">1914</option>
            <option value="1913">1913</option>
            <option value="1912">1912</option>
            <option value="1911">1911</option>
            <option value="1910">1910</option>
            <option value="1909">1909</option>
            <option value="1908">1908</option>
            <option value="1907">1907</option>
            <option value="1906">1906</option>
            <option value="1905">1905</option>
            <option value="1904">1904</option>
            <option value="1903">1903</option>
            <option value="1902">1902</option>
            <option value="1901">1901</option>
            <option value="1900">1900</option>
            </select> 
        </td></tr>                  

        <tr><td><h11>Email Address: </h11></td>
        <td><input name="email1" type="text" class="formFields" id="email1" value="<?php print "$email1"; ?>" size="32" maxlength="48" /></td></tr>
          
        <tr><td><h11>Confirm Email: </h11></td>
        <td><input name="email2" type="text" class="formFields" id="email2" value="<?php print "$email2"; ?>" size="32" maxlength="48" /></td></tr>
          
        <tr><td><h11>Create Password: </h11></td>
        <td><input name="pass1" type="password" class="formFields" id="pass1" size="32" maxlength="16" /></tr>
        
        <tr><td><h11>Confirm Password: </h11></td>
        <td><input name="pass2" type="password" class="formFields" id="pass2" size="32" maxlength="16" /></tr>
        
        <tr><td><h11>Add Profile Photo: </h11></td>         
        <td width="521"><input name="user_pic" type="file" class="formFields" id="user_pic" size="42" /> 50 kb max </td></tr> 
          
        <tr><td> </td>
        <td><input type="submit" style="color: #a2a2a2; font-family: helvetica; font-size: 11px; letter-spacing: 1px" name="Submit" value="Register" /></td></tr>

        </form>
      
</table>
<br />
</div>
<?php include_once "footer_template.php"; ?>
</div>
</body>
</html>

Currently, the script is generating this error code:

"Warning: mysql_query() [function.mysql-query]: Access denied for user ‘nbewley’@‘localhost’ (using password: NO) in /home/nbewley/public_html/manualprintcompany.com/register.php on line 82

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/nbewley/public_html/manualprintcompany.com/register.php on line 82
Access denied for user ‘nbewley’@‘localhost’ (using password: NO)"

which corresponds with the query:


$sql = mysql_query("INSERT INTO myMembers (username, gender, birthday, email, password, ipaddress, sign_up_date) 
    VALUES('$username','$gender','$full_birthday','$email1','$db_password', '$ipaddress', now())")  
    or die (mysql_error());

Truthfully, I’m guessing here a bit, but hoping to piece together my knowledge into a workable piece of code. I’m not sure why my query is now generating an error, to begin with. The query is the same that I was using before (which was working) and the database values are the same. I’m sure something is wrong with the way I have structured the code, but I’m not sure what.

Thanks in advance for any advice.
nbewley