Jump to content

Self Validating PHP Email Form with attachment file not getting passed


TGWSE_GY

Recommended Posts

I am attempting to get my email form with file attachment to work. Apparently the file is not reaching getting to the validation portion of the page I have switched $_FILES['X'] on line 203 from file to fakefile as they are labeled in the form also I am employing css hacks to change the input file upload field to have a custom button example -> http://visualrealityink.com/dev/clients/arzan/snell_form_final/form.php

 

here is my code I appreciate any help :D

<!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>
<style>
    #form_container{ display:block; position:absolute; width:610px; min-height:450px; background:#f8f8f8; padding: 5px 5px 5px 5px; font-family:Arial, Helvetica, sans-serif; font-size:14px; }
    #form { min-height:450px; width:100%; background:#ececec; padding:0 0 0 0; }
    #formheader { background:url(images/form2_08.png) no-repeat #2f2f2f; margin:0 0 0 0; padding:0 0 0 0; width:631; height:30px;}
    form{margin:35px 0 0 35px;}
     fieldset div 
     {
        margin:0.3em 0;
        clear:both;
     }
     label 
     {
        float:left;
        width:10em;
        text-align:left;
        margin-right:1em;
	font-family:Arial, Helvetica, sans-serif;
	font-size:14px;
     }
     input 
     {
        padding:0.15em;
	margin:0 0 0 -110px;
        width:300px;
	background:url(images/inputbg.png) no-repeat;
        border:0px solid #ddd;
        background:#fafafa;
        -moz-border-radius:0.4em;
        -khtml-border-radius:0.4em;
    }
.bg2{background:url(images/inputbg.png) no-repeat; height:28px; line-height:28px;}
     
    fieldset 
    {
        border:0px solid #ddd;
        padding:0 0.5em 0.5em;
	margin:0 0 0 -100px;
    }

    #details{font-size:10px;}
    #logo{background:url(images/form2_11.png) no-repeat; width:189px; height:238px; margin:-200px 0 0 400px; position:absolute;}
    #submit{margin:14px 0 0 -5px; border:none; position:absolute; cursor:pointer; cursor:hand;}
    #reset{border:none; margin:14px 0 0 115px; position:absolute; cursor:pointer; cursor:hand; }
    #divinputfile{
     background:url(images/form2_27.png) no-repeat 100% 1px;
     height:43px;
     line-height:43px;
     width:340px;
     
    }#divinputfile #filepc{
     opacity: 0.0;
     -moz-opacity: 0.0;
     filter: alpha(opacity=00); 
     font-size:18px;
     margin:0 0 0 0;
cursor:hand; cursor:pointer;

}
    #fakeinputfile{
     margin-top:-28px;
    }
    #fakeinputfile #fakefilepc{
	 background:url(images/inputbg2.png) no-repeat; style:none;
	 width:240px;
	 height:28px;
	 line-height:28px;
	 border:0;
	 margin:5px 0 0 0;
	 font-size:18px;
	 font-family:Arial;
     }
button {
	cursor: hand;
	cursor: pointer;
	padding: 0px;
	margin: 0 0 0 0;
    }
    a.link_button{
    cursor: hand;
    cursor: pointer;
    }
.fileupload{
	margin:0 0 0 50px;
}
    input[type="file"] { cursor: pointer; }  
    .error{font-size:9px; font-family:Arial, Helvetica, sans-serif; color:#F00; }
    .error ul { text-decoration: none; list-style: none; }
    .error li { color: #F00;}       
.captcha_form { margin: 0 0 0 -45px; width:235px; }
#captchaimage{ padding:0 0 10px 0;}
.small { font-size:9px;}
</style> 

</head>

<body>
<?php

  if ($_POST['_submit_check']) 
{
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) 
    {
        show_form($form_errors);
    } else {
    // The submitted data is valid, so process it
        process_form();
    }
} else {
// The form wasn't submitted, so display
    show_form();
}

function show_form($errors = '')
{
// If the form is submitted, get defaults from submitted parameters
    if ($_POST['_submit_check']) 
    {
        $defaults = $_POST;
    } else 
    {
    // Otherwise, set our own defaults: medium size and yes to delivery
        $defaults = array('IssueDate' => '','ExpiryDate' => '');
    }
    if ($errors) 
    {
        $error_text = 'You need to correct the following errors:';
        $error_text .= '<br /><ul>';
        $error_text .= implode('<li>',$errors);
        $error_text .= '</li></ul>';
    } else 
    {  
    // No errors? Then $error_text is blank
    $error_text = '';
    }
    include 'formhelpers.php'
    ?>
     <div id="form_container">
  <div id="form">
  <br />
      <div id="formheader">
    </div>
        <form method="POST" action="<?php print $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
         <span class="error"> <?php print $error_text ?> </span>
         
         <input type="hidden" name="_submit_check" value="1"/>
          <div>
            <label for="name">Name: </label>
            <?php input_text('name', $defaults) ?> </div>
        <div>
        <label for="email">Email:</label>
        <?php input_text('email', $defaults) ?>  </div>
        
       <div> Attach Resume: 
       <span class="small">(1MB : PDF : DOC : DOCX : TXT)</span>
         </div>
            
          <div>
                <!--<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
                <label for="userfile"></label>
                <input type="file" name="userfile" id="userfile"/> </div>-->
                <div id="divinputfile"> 
      			<input name="file" type="file" size="30" id="filepc" onchange="document.getElementById('fakefilepc').value = this.value;"/>
      			<div id="fakeinputfile">
      				<input name="fakefile" type="text" class="link_button" id="fakefilepc" />
      			</div>
		</div>

        <div id="captchaimage"><img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /></div>
        <div><label for="email"><a style="text-decoration: none" href="#" onclick="document.getElementById('captcha').src = 'securimage/securimage_show.php?' + Math.random(); return false">New Captcha: </a></label>
         <input type="text" name="captcha_code" class="captcha_form" size="10" maxlength="6" /> </div>
         
         <button type="submit" value="submit" id="submit" ><img src="images/form2_33.png" /></button> <button type="reset" value="reset" id="reset" ><img src="images/form2_37.png" /></button>
         
         </form>
        </div>
    <div id="logo"></div>
  </div>
</div>
    <?php
    
}
function validate_form()
{
    $errors = array( );
    // name is required
    if ($_POST['name'] == "") 
    {
        $errors[ ] = 'Please enter your name.';
    }
    if (! strlen(trim($_POST['email']))) 
    {
        $errors[ ] = 'Please enter your Email.';
    }
    if (! preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $_POST['email'])) 
    {
        $errors[ ] = 'Please enter a valid e-mail address';
    }
    
    $filename=$_FILES['file']['name'];
    //For size
     
    if($_FILES["file"]["size"]>1000000) //1 mb
        {
            $errors[ ] = "File size should be less than 1MB";    
        }
     
    // for extention
     
$ext = end(explode('.', $filename));


    
    if($ext=='doc' || $ext=='txt' || $ext=='pdf' || $ext=='docx' )
    {
        echo "write the code to upload file";
	$max_allowed_file_size = 1024; // size in KB   
	$name_of_uploaded_file =  basename($_FILES['file']['name']);  
	//get the file extension of the file  
	$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1);
	$size_of_uploaded_file =  $_FILES["file"]["size"]/1024;//size in KBs 
	//copy the temp. uploaded file to uploads folder  
	$upload_folder = 'upload/';
	$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;  
	$tmp_path = $_FILES["file"]["tmp_name"];  
	if(is_uploaded_file($tmp_path)) {  
		if(!copy($tmp_path,$path_of_uploaded_file)){  
			echo 'error while copying the uploaded file';
			die();
		}
	}  
    }
    else
    {
        $errors[ ] = "Only doc or pdf or txt file is allowed: $filename ";
    }

     
     
     return $errors;
}

function process_form()
{
     

                 
                    $image = "http://www.visualrealityink.com/dev/clients/arzan/snell_form/images/email.png";
                    include_once('Mail.php');  
                    include_once('Mail_Mime/mime.php'); 
                    $to = 'george@visualrealityink.com';
                    $text = $image . "<br />" . $values['name'] . "submitted a resume on our website. Please review the applications and contact the candidate if their resume is a fit for any open opportunities with the company. <br><br> Thank you. <br><br> SEI Team";
                    $message=new Mail_mime();
                    $message=setTXTBody($text);
                    $message=addAttachment($path_of_uploaded_file);
                    $body = $message->get();
                    $extraheaders = array("From"=>$formValues['email'], "Subject"=>$subject, "Reply-To"=>$formValues['email']);
                    $headers = $message->headers($extraheaders);
                    $mail = Mail::factory("mail");
                    $mail->send($to, $headers, $body);
                    echo "email sent"; 

    

}
?>
</body>
</html>

Link to comment
Share on other sites

Im going to go out on a limb here, and say there is likely a good reason why almost every website doesn't attach files to emails.. And I would say you should follow suit with that. Almost every website that sends an email regarding a file is always linked to a specific location on the server where the user can gain access to it via some measure or another. Rather than physically attached to the email. I can see several security reasons for this say if your form ever got hijacked for example (it happens)..

 

But then theres the other reasons, file size constraints, improper headings, hosting constraints. Then things like server bandwidth. Everytime that email has to send, its gotta enact the concept of uploading the file somewhere, which means wait times, which means functions time out, an its a mess.. your best to just link the file within the email for direct download rather than figure out how to attach it to the message.

Link to comment
Share on other sites

monkeytooth: thanks for the reply, I understand what you are saying and we both know the security issues behind attachments via php and yes it should be uploaded and linked in the email. However the client has no experience with ftp and the designer that wants this done is not budging on email attachment through php no matter how I tell him that its wrong. So I guess this is something that I am going to need to plug away with until I get it. I thought someone could offer some reasoning to why the file was not getting pulled from the form. Although I like the information you provided and yes I knew most of it before its down to what the client wants and sometimes you just cant change their mind no matter how much talking you do and smoke you blow.

 

Thanks Again, any other suggestions would be appreciated. :D

Link to comment
Share on other sites

<input name="file" type="file" size="30" id="filepc" onchange="document.getElementById('fakefilepc').value = this.value;"/>
      			<div id="fakeinputfile">
      				<input name="fakefile" type="text" class="link_button" id="fakefilepc" />
      			</div>

 

shows that the file input is named file and so I should be able to call $_FILES['file']['name'] and get the file name but its not working. This is becomming frustrating because I have done upload forms before. Its not making any sense why the file is not getting uploaded and retrieved.

Link to comment
Share on other sites

ok so I have progress! now the file is retrieved and uploaded but even though it is uploaded it still gives me an error that the upload failed (hardcoded error trap). Where I am now confused is that even though "if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))" succeeds and uploads the file it still gives me the else error statement, this doesn't make much sense does anyone have a suggestion?

 

Here is the trouble area

$target_path = "uploads/";

	$target_path = $target_path . basename( $_FILES['file']['name']); 
	echo $target_path;
	if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
		echo "The file ".  basename( $_FILES['file']['name']). 
		" has been uploaded";
	} else{
		echo "There was an error uploading the file, please try again!";
	}
	$path_of_uploaded_file = '/uploads/' . $_FILES['file']['name'];
	process_form();

 

Here is my full source code

<!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>
<style>
    #form_container{ display:block; position:absolute; width:610px; min-height:450px; background:#f8f8f8; padding: 5px 5px 5px 5px; font-family:Arial, Helvetica, sans-serif; font-size:14px; }
    #form { min-height:450px; width:100%; background:#ececec; padding:0 0 0 0; }
    #formheader { background:url(images/form2_08.png) no-repeat #2f2f2f; margin:0 0 0 0; padding:0 0 0 0; width:631; height:30px;}
    form{margin:35px 0 0 35px;}
     fieldset div 
     {
        margin:0.3em 0;
        clear:both;
     }
     label 
     {
        float:left;
        width:10em;
        text-align:left;
        margin-right:1em;
	font-family:Arial, Helvetica, sans-serif;
	font-size:14px;
     }
     input 
     {
        padding:0.15em;
	margin:0 0 0 -110px;
        width:300px;
	background:url(images/inputbg.png) no-repeat;
        border:0px solid #ddd;
        background:#fafafa;
        -moz-border-radius:0.4em;
        -khtml-border-radius:0.4em;
    }
.bg2{background:url(images/inputbg.png) no-repeat; height:28px; line-height:28px;}
     
    fieldset 
    {
        border:0px solid #ddd;
        padding:0 0.5em 0.5em;
	margin:0 0 0 -100px;
    }

    #details{font-size:10px;}
    #logo{background:url(images/form2_11.png) no-repeat; width:189px; height:238px; margin:-200px 0 0 400px; position:absolute;}
    #submit{margin:14px 0 0 -5px; border:none; position:absolute; cursor:pointer; cursor:hand;}
    #reset{border:none; margin:14px 0 0 115px; position:absolute; cursor:pointer; cursor:hand; }
    #divinputfile{
     background:url(images/form2_27.png) no-repeat 100% 1px;
     height:43px;
     line-height:43px;
     width:340px;
     
    }#divinputfile #filepc{
     opacity: 0.0;
     -moz-opacity: 0.0;
     filter: alpha(opacity=00); 
     font-size:18px;
     margin:0 0 0 0;
cursor:hand; cursor:pointer;

}
    #fakeinputfile{
     margin-top:-28px;
    }
    #fakeinputfile #fakefilepc{
	 background:url(images/inputbg2.png) no-repeat; style:none;
	 width:240px;
	 height:28px;
	 line-height:28px;
	 border:0;
	 margin:5px 0 0 0;
	 font-size:18px;
	 font-family:Arial;
     }
button {
	cursor: hand;
	cursor: pointer;
	padding: 0px;
	margin: 0 0 0 0;
    }
    a.link_button{
    cursor: hand;
    cursor: pointer;
    }
.fileupload{
	margin:0 0 0 50px;
}
    input[type="file"] { cursor: pointer; }  
    .error{font-size:9px; font-family:Arial, Helvetica, sans-serif; color:#F00; }
    .error ul { text-decoration: none; list-style: none; }
    .error li { color: #F00;}       
.captcha_form { margin: 0 0 0 -45px; width:235px; }
#captchaimage{ padding:0 0 10px 0;}
.small { font-size:9px;}
</style> 

</head>

<body>
<?php

  if ($_POST['_submit_check']) 
{
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) 
    {
        show_form($form_errors);
    } else {
    // The submitted data is valid, so process it
        process_form();
    }
} else {
// The form wasn't submitted, so display
    show_form();
}

function show_form($errors = '')
{
// If the form is submitted, get defaults from submitted parameters
    if ($_POST['_submit_check']) 
    {
        $defaults = $_POST;
    } else 
    {
    // Otherwise, set our own defaults: medium size and yes to delivery
        $defaults = array('IssueDate' => '','ExpiryDate' => '');
    }
    if ($errors) 
    {
        $error_text = 'You need to correct the following errors:';
        $error_text .= '<br /><ul>';
        $error_text .= implode('<li>',$errors);
        $error_text .= '</li></ul>';
    } else 
    {  
    // No errors? Then $error_text is blank
    $error_text = '';
    }
    include 'formhelpers.php'
    ?>
     <div id="form_container">
  <div id="form">
  <br />
      <div id="formheader">
    </div>
        <form method="POST" action="<?php print $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
         <span class="error"> <?php print $error_text ?> </span>
         
         <input type="hidden" name="_submit_check" value="1"/>
          <div>
            <label for="name">Name: </label>
            <?php input_text('name', $defaults) ?> </div>
        <div>
        <label for="email">Email:</label>
        <?php input_text('email', $defaults) ?>  </div>
        
       <div> Attach Resume: 
       <span class="small">(1MB : PDF : DOC : DOCX : TXT)</span>
         </div>
            
          <div>
                <!--<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
                <label for="userfile"></label>
                <input type="file" name="userfile" id="userfile"/> </div>-->
                <div id="divinputfile"> 
      			<input name="file" type="file" size="30" id="filepc" onchange="document.getElementById('fakefilepc').value = this.value;"/>
      			<div id="fakeinputfile">
      				<input name="fakefile" type="text" class="link_button" id="fakefilepc" />
      			</div>
		</div>

        <div id="captchaimage"><img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /></div>
        <div><label for="email"><a style="text-decoration: none" href="#" onclick="document.getElementById('captcha').src = 'securimage/securimage_show.php?' + Math.random(); return false">New Captcha: </a></label>
         <input type="text" name="captcha_code" class="captcha_form" size="10" maxlength="6" /> </div>
         
         <button type="submit" value="submit" id="submit" ><img src="images/form2_33.png" /></button> <button type="reset" value="reset" id="reset" ><img src="images/form2_37.png" /></button>
         
         </form>
        </div>
    <div id="logo"></div>
  </div>
</div>
    <?php
    
}
function validate_form()
{
    $errors = array( );
    // name is required
    if ($_POST['name'] == "") 
    {
        $errors[ ] = 'Please enter your name.';
    }
    if (! strlen(trim($_POST['email']))) 
    {
        $errors[ ] = 'Please enter your Email.';
    }
    if (! preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $_POST['email'])) 
    {
        $errors[ ] = 'Please enter a valid e-mail address';
    }
    
    $filename=$_FILES['file']['name'];
    //For size
     
    if($_FILES["file"]["size"]>1000000) //1 mb
        {
            $errors[ ] = "File size should be less than 1MB";    
        }
     echo $_FILES['file']['name'];
    // for extention
     
     $ext = end(explode('.', $filename));


    
    if($ext=='doc' || $ext=='txt' || $ext=='pdf' || $ext=='docx' )
    {

	$target_path = "uploads/";

	$target_path = $target_path . basename( $_FILES['file']['name']); 
	echo $target_path;
	if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
		echo "The file ".  basename( $_FILES['file']['name']). 
		" has been uploaded";
	} else{
		echo "There was an error uploading the file, please try again!";
	}
	$path_of_uploaded_file = '/uploads/' . $_FILES['file']['name'];
	process_form();
    }
    else
    {
        $errors[ ] = "Only doc or pdf or txt file is allowed: $filename ";
    }

     
     
     return $errors;
}

function process_form()
{
     

                 
                    $image = "http://www.visualrealityink.com/dev/clients/arzan/snell_form/images/email.png";
                    include_once('Mail.php');  
                    include_once('Mail_Mime/mime.php'); 
                    $to = 'george@visualrealityink.com';
                    $text = $image . "<br />" . $values['name'] . "submitted a resume on our website. Please review the applications and contact the candidate if their resume is a fit for any open opportunities with the company. <br><br> Thank you. <br><br> SEI Team";
                    $message=new Mail_mime();
                    $message=setTXTBody($text);
                    $message=addAttachment($path_of_uploaded_file);
                    $body = $message->get();
                    $extraheaders = array("From"=>$formValues['email'], "Subject"=>$subject, "Reply-To"=>$formValues['email']);
                    $headers = $message->headers($extraheaders);
                    $mail = Mail::factory("mail");
                    $mail->send($to, $headers, $body);
                    echo "email sent"; 

    

}
?>
</body>
</html>

 

Thanks Again

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.