1

I'm a frontend developer trying to struggle my way through a PHP form for a freelance client. This is quite an extensive job application form, which the client has requested to include two file uploads: an image (jpg, png) and a CV (pdf, doc). These files would attach to the email containing the form answers. Uploading the files to a folder on the server permanently is not required.

As I am woefully inadequate at all things PHP, I resorted to a site called Formbakery to generate said form for me, which is great - except it doesn't include file upload capabilities.

I have tried a couple of different resources for php file upload and email attachment, including this tutorial and this answer, however the issue is that I just don't know how to incorporate this with the code I already have. I am hoping that someone could help me out with combining the various different elements. If a multiple file upload is too much to ask for, even just a single one for the CV would be a massive help.

PHP for sending form

<?php
// get value from array
function array_get(array $array, $key, $default = null)
{
    return (array_key_exists($key, $array)) ? $array[$key] : $default;
}

// get string value from array
function array_get_string(array $array, $key, $default = '', $trim = true)
{
    $val = array_get($array, $key);
    if (is_string($val)) {
        return ($trim) ? trim($val) : $val;
    }
return $default;
}

// takes a form array and validates it
function validateForm(array $form)
{
    // array of error messages
    $errors = array();

    // for each field in the form
    foreach ($form as $field)
    {
        // if the field doesnt require any validation, skip it
        if (!isset($field['validation'])) continue;
        // for each validation type
        foreach ($field['validation'] as $validate)
        {
            // if the field is empty, there is nothing to check
            if (trim($field['value']) === '') break;

            switch($validate)
            {
                case 'email':
                if(!filter_var($field['value'], FILTER_VALIDATE_EMAIL)) {
                    $errors[] = '"' . $field['value'] . '" is an invalid email address.';
                }
                break;
                case 'number':
                if(!preg_match('/^[0-9 ]+$/', $field['value'])) {
                    $errors[] = '"' . $field['value'] . '" is an invalid number.';
                }
                break;
                case 'alpha':
                if(!preg_match('/^[a-zA-Z ]+$/', $field['value'])) {
                    $errors[] = '"' . $field['value'] . '" contains invalid characters. This field only accepts letters and spaces.';
                }
                break;
            }
        }

        // if field is required and empty
        if (isset($field['required']) && trim($field['value']) === '') {
            // overwrite errors with only the required error message
            $errors[] = '"' . $field['name'] . '" is a required field.';
        }
    }

    // return an array of errors
    return $errors;
}

// define form
$FORM = array(
    'position-applied-for' => array(
        'name' => 'Position applied for',
    ),
    // CONTINUE ARRAY ITEMS
);

// populate form values from POST
foreach ($FORM as $field_name => &$field_data) {

    $value_type = gettype($_POST[$field_name]);

    if ($value_type == 'string')
    {
        // get the string value from POST data
        $field_data['value'] = array_get_string($_POST, $field_name);
    }

    elseif ($value_type == 'array')
    {
        // these are multiple checkbox values
        // we need to concat them into a string
        $concat = '';

        foreach (array_get($_POST, $field_name) as $item) {
            $concat .= $item . '; ';
        }

        $field_data['value'] = $concat;
    }
}

// unset referenced variable to avoid quirks
unset($field_data);

$AJAX = array_get_string($_POST, 'request_method') === 'ajax';
$ERRORS = validateForm($FORM);
$SUCCESS = count($ERRORS) ? false : true;

// send email
if ($SUCCESS)
{
    // Full Name: $fullname \nEmail Address: $emailaddress
    $formcontent = '';
    $emailtemplate = "INSERT EMAIL TEMPLATE HTML";
    foreach ($FORM as $field_name => $field_data) {
        $formcontent .= $field_data['name'] . ': ' . $field_data['value'] . " \n";
    }

    $formcontent = wordwrap($formcontent, 70, "\n", true);
    $recipient = 'EMAIL@hotmail.com';
    $subject = 'Creed Coffee Application Form';
    $mailheader = "From: applications@creed.coffee \r\nContent-Type: text/html;";

    mail($recipient, $subject, $emailtemplate, $mailheader);
}

?>

<?php if ($AJAX): ?>
    <?php if ($SUCCESS): ?>
        PASS
    <?php else: ?>
        FAIL
    <?php endif; ?>
<?php else: ?>
    Do a redirect
<?php endif; ?>

This is accompanied by jQuery for validation etc. I understand that this is a big ask and I don't expect anyone to take the time required to write this all out for me, but I would really appreciate if anyone could even point me in the right direction or give me enough pointers to struggle onwards with this!

  • 1
    I think it would be beneficial to describe the issues you've encountered while trying various things, you might've been closer than you realize. – axwr Sep 11 '17 at 21:20
  • I would suggest you start simple by finding a tutorial for uploading a single item. Then work on attaching it to email. Then add a second upload. – Mike S Sep 11 '17 at 21:21
  • There are 4 areas that you need to look at 1) use the multiple attribute in the on your web page, 2) php uses the $_FILES superglobal to handle the actual file (not $_POST or $_GET and 3) read the php manual about file uploads http://php.net/manual/en/features.file-upload.php 4) the php mail() doesn't handle attachments too well - use an alternative (can;t think of its name at the moment) –  Sep 11 '17 at 21:23
  • Thanks for the feedback everyone. I haven't added what I tried here as it was literally lifting out the code from the tutorials and trying to slot it in amongst what I currently have. That's the main problem. I could probably easily enough get a simple file upload to work, but it's taking that and incorporating it with what I already have, making sure it works along with it, that has proved to be the problem. Especially since I didn't write said code, which makes it more difficult to understand. However I'll take this advice and try and piece it together starting from the ground up. – gracehcoote Sep 12 '17 at 18:22

0 Answers0