Jump to content

Recommended Posts

Hi!
We have a form that's been used for years, and now we would like to have the added capability of attaching an image. (So a consumer can send us an image that might help with their problem.) Currently, a "confirmation" email is sent to the consumer with all of the info they gave us; a copy of the same information also goes to us. We would like the consumer's image to be saved onto our server, so when we look at the completed form, the "Image:" line has a link to that page.
I.e. a consumer attaches an image named "picture.jpg". The copy of the information we get would have a line that reads: "Image: http://www.example.com/test/uploads/picture.jpg". I'm assuming I would use a variable to get the image name to display in order to complete the link. I'm lost about which variable I would use... but that might be because I can't get the image to even save in the folder (I think) it's supposed to. Obviously there's something messed up, but I am lost as to what that is. Any help would be greatly appreciated!

The field to attach the image on the form:

<label for="upload_file" class="main-label">If you have an image that would help us assist you, please attach it here.</label>
<input type="file" name="uploaded_file">



The process file (the attachment part is at the bottom):

<?php
    //Collect contact form data
    //Check Special Field
    //Email ASC & Webmaster
    //Email Sender
    //Redirect to thank you page

    require_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');


    /********  CONTACT DATA **********/
    $name = stripslashes($_POST['name']);
    $company = stripslashes($_POST['company']);
    $address = stripslashes($_POST['address']);
    $city = stripslashes($_POST['city']);
    $state = stripslashes($_POST['state']);
    $zipcode = stripslashes($_POST['zipcode']);
    $country = stripslashes($_POST['country']);
    $website = $_POST['website'];
    $phone = stripslashes($_POST['phone']);
    $fax = stripslashes($_POST['fax']);
    $email = stripslashes($_POST['contact']);
    $Referred = stripslashes($_POST['referred']);
    $CustomerType = stripslashes($_POST['CustomerType']);
    $Comments = stripslashes($_POST['comments']);
    $ConsumerHelp = stripslashes($_POST['ConsumerHelp']);
    $UPC = stripslashes($_POST['UPC']);
    $Describe = stripslashes($_POST['Describe']);
    $uploaded_file = ($_FILES['uploaded_file']);
    /********  CHECK SPECIAL FIELD **********/
    $spamcheck = stripslashes($_POST['email']);
    

    //if spamcheck isnt blank exit page, no need for error message to user, as its a spam bot
    if ($spamcheck!=="") {

        exit;

    }

        
        /********  EMAIL ASC & WEBMASTER  **********/
        $message = "
    -----------------------------------------------------------------------------
       Information Inquiry
    -----------------------------------------------------------------------------

    $name has visited the web site and would like some information.
    The details they entered on the website are:

    Name: $name
    Company: $company
    Address: $address
    City: $city
    State: $state
    Zip Code: $zipcode
    Country: $country
    Website: $website
    Phone: $phone
    Fax: $fax
    Email: $email

    Referred to web site: $Referred

    CustomerType: $CustomerType

    Comments: $Comments
    
    I need help with: $ConsumerHelp
    
    UPC code or Item #: $UPC
    
    What I am looking for: $Describe
    
    Image: $uploaded_file

    Kind Regards,

    ";
        $email_address = "example@example";

        $subject = "Information Inquiry";
        $headers = "From: $name <$email>";
        $message = str_replace("\r",'',$message); //fixes postfix php bug that double spaces messages





        /********  EMAIL SENDER **********/
        $message2 = "
    -----------------------------------------------------------------------------
      Re: Information Inquiry
    -----------------------------------------------------------------------------

    Thank you $name for visiting the web site. We will be using the details you entered to contact you.

    Name: $name
    Company: $company
    Address: $address
    City: $city
    State: $state
    Zip Code: $zipcode
    Country: $country
    Website: $website
    Phone: $phone
    Fax: $fax
    Email: $email

    Referred to web site: $Referred

    CustomerType: $CustomerType

    Comments: $Comments
    
    I need help with: $ConsumerHelp
    
    UPC code or Item #: $UPC
    
    What I am looking for: $Describe
    

    Kind Regards,
 
    ";
        $email_address2 = "$email";
        $subject2 = "Re: Information Inquiry";
        $headers2 = "From:  <example@example.com>";
        $message2 = str_replace("\r",'',$message2); //fixes postfix php bug that double spaces messages

    //send message 1 and save result in success var (either true for success, or false for fail
    $success = mail($email_address, $subject, $message, $headers);

    //conditionally send message2, no need to check success on this one
    if (strpos($email,'@aol.com') == false) {
        mail($email_address2, $subject2, $message2, $headers2);
    }

    if (!$success) {
    // What happens when the form does not validate
    header("Location: sorry.php");
    die ();
    } else {
      // Your code here to handle a successful verification
      header("Location: thanks.php");
        $success;

    }
?>  

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["uploaded_file"]["name"]);
$extension = end($temp);

if ((($_FILES["uploaded_file"]["type"] == "image/gif")
|| ($_FILES["uploaded_file"]["type"] == "image/jpeg")
|| ($_FILES["uploaded_file"]["type"] == "image/jpg")
|| ($_FILES["uploaded_file"]["type"] == "image/pjpeg")
|| ($_FILES["uploaded_file"]["type"] == "image/x-png")
|| ($_FILES["uploaded_file"]["type"] == "image/png"))
&& ($_FILES["uploaded_file"]["size"] < 20000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["uploaded_file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["uploaded_file"]["name"] . "<br>";
    echo "Type: " . $_FILES["uploaded_file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["uploaded_file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["uploaded_file"]["tmp_name"] . "<br>";
    if (file_exists("upload/" . $_FILES["uploaded_file"]["name"])) {
      echo $_FILES["uploaded_file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],
      "upload/" . $_FILES["uploaded_file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  }
} else {
  echo "Invalid file";
}
?> 

Link to comment
https://forums.phpfreaks.com/topic/288118-attaching-image-to-email-from-form/
Share on other sites

Thank you for the response! I have attached the functions.php file... it's kind of lengthy though! We do have a MySQL database that the rest of the website uses. As it's set up now, nothing from the form goes into the database or is saved at all. We just get an email with the user's input from the form fields. Are you thinking having the image save to the database? We hadn't thought of that! We had just been thinking that we could have the image save to an uploads folder on the server... but if the database option works, great! :)

functions.php

I would approach it a little differently.  Rather than just email the webmaster with the info and pic, I would want something more permanent and extensible.  For example something like:

 

  1. The customer fills out the form and submits a picture file (modify the form
  2. The customer receives an acknowledgement email
  3. The image is uploaded to a file location (/customer_image/some_pic.jpg)
  4. Database is used to capture the form information plus the filename of the image.
  5. Webmaster gets notified (and others) of inquiry.
  6. Webmaster goes to the query page and can review all customer queries and images (have to build page for this)
  7. Webmaster can click on customer link and respond to query (email response form).  This response is also put in the database so if someone else needs the info or review.
  8. Additional  responses to the customer could be sent from the response page and entered into the db.

This would allow a permanent record of customer queries and responses.  It takes a bit of work to send attachments in emails and would require a function being built to handle the mime types for attachments or you can find a package that provides this.  With the amount of work, I would rather go with what I have described above.  

 

Either way you should update your functions file to use mysqli instead of mysql or use PDO, mysql is obsolete.

You shoudl really do all processing and error handling before building any email message strings, it's just a waste of processing power to build those strings if there are errors anyway.  So move the file checking code just under the $spamcheck if() and use a else{} to hold the rest of the code, the else{} is not needed but I think it provides a easy way to distinguish what's supposed to happen if the spamcheck if fine.  Next turn this line into a variable instead.

"upload/" . $_FILES["uploaded_file"]["name"]

$location = "upload/" . $_FILES["uploaded_file"]["name"]; // Do this instead

Then move that line just above the move_uploaded_file() line and replace the previous code with the new variable in the function.

$location = "upload/" . $_FILES["uploaded_file"]["name"];
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $location);

      echo "Stored in: " . $location;

Now you can use the $location var in your email and append the domain name to the beginning of it.

What I am looking for: $Describe

    

    Image: http://yourdomain.com/$location


    Kind Regards,

The database way is a good way to but will take a lot of code to build.

Edited by fastsol

@possien, It would definitely be ideal to have everything saved and backed up. However, our entire site is going to be revamped in the next few months, so putting in a ton of time and effort into making that many changes... just to be wiped out soon isn't really useful. If the site wasn't going to be re-done... I would definitely go for that though! Thank you! :)

@fastsol, I implemented the changes you suggested... with complete success!! :D :D :D I just had to increase the max file size to get it to work. THANK YOU SO MUCH!!

 

Edit:

Is there an easy way to assign a random number to the image name when it's saved? We're pretty sure it won't happen very often, but if, for example, user 1 uploads 2901.jpg, and then user 4 comes along and also uploads 2901.jpg. When user 4 clicks submit, it takes them to a page that says that file name already exists... but then still submits the form. Rather than having that person go back and have to change the name of their image and submit a duplicate form, it would be a lot easier if the image is just assigned a random number for it's name. Thank you! :)

Edited by hhartman1027

I don't know how you have it set up, but I check my database to see how many images are in the directory, then just add 1 for the new image. I pretty sure you could count on how many image files are in the directory also.

 

For example I do the following:

        $query = "SELECT * FROM pictures WHERE subDirectory=:subDirectory";
        $stmt = $pdo->prepare($query);
        $stmt->execute(array(':subDirectory' => $name));
        $result = $stmt->fetchAll();

        $fileNumber = count($result) + 1;
        

        $result = null;
        if ($fileNumber < 10) {
          $this->uniqueFileName = $name . '-0' . $fileNumber;
        } else {
          $this->uniqueFileName = $name . '-' . $fileNumber;
        }

Before anyone says I anything I know I could had done the count in the $query. :tease-03: This way it insures that I have a unique name and there is even a way to prevent duplicates doing it through PDO, but for my purposes I don't think a duplicate will happen and if I does I'll add the added code.

Sure easy enough.  Change the $location line to this.

$location = "upload/" . $temp[0].".".time().".".$extension;

That will take the first temp array element as the start of the file name and append the current timestamp and then the extension.

Sure easy enough.  Change the $location line to this.

$location = "upload/" . $temp[0].".".time().".".$extension;

That will take the first temp array element as the start of the file name and append the current timestamp and then the extension.

Holy cow... I need to put you on speed dial! :thumb-up:  That line worked perfectly!! Thank you, thank you, thank you! :D

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.