Alan
Alan

Reputation: 57

Contact form with file upload

I'm would like to add file upload to my current code. The form I have works great and would prefer not to change it. I've been searching google and youtube and can't find a code that I can add to my current code. It's so frustrating when all I get is errors upon errors.

<?php 

if ($_POST['submit']) {

  if (!$_POST['username']) {
    $error = "<br>- Please enter your name! \r\n";
  }

  if (!$_POST['email']) {
    $error .= "<br>- Please enter your email! \r\n";
  }

  if (!$_POST['message']) {
    $error .= "<br>- Please enter your message! \r\n";
  }

  if ($error) {
    $result = "<div class='alert alert-danger' role='alert'>Whoops, there is an error. Please correct the following: $error</div>";
  } else {
    mail("[email protected]", "Message from contact form", "From: ".$_POST['username']."

      Reply to: ".$_POST['email']."

      Message: ".$_POST['message']);
    {
      $result = "<div class='alert alert-success text-center' role='alert'>
      <p>Thank you for your message. We will contact you socket_get_option(socket, level, optname)</p>
      </div>";
    }
  }

}

 ?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <title>Title</title>

        <!-- Bootstrap -->
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">

        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
<body>

    <section>
        <div class="container">
            <div class="row">
                <div class="col-xs-12 col-sm-4 col-sm-offset-4">
                <h1 class="text-center">Contact us</h1>
                        <?php echo $result;?>
                    <form action="material.php" method="post" role="form">

                        <div class="form-group input-group input-group-lg">
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-user"></span>
                            </span>
                            <input type="text" name="username" class="form-control">
                        </div>

                        <div class="form-group input-group input-group-lg">
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-envelope"></span>
                            </span>
                            <input type="email" name="email" class="form-control">
                        </div>

                        <div class="form-group">
                            <textarea name="message" id="message" rows="5" placeholder="Message box"></textarea>
                        </div>

                        <p>Send us your photo</p>

                        <div>
                            <input type="file" name="file" enctype="multipart/form-data">
                        </div>

                        <div class="form-group input-group btn-margin">
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-send"></span>
                            </span>
                            <input type="submit" name="submit" class="form-control btn btn-primary" value="Submit request">
                        </div>


                    </form>
                </div>
            </div>
        </div>
    </section>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

Upvotes: 2

Views: 1137

Answers (2)

InfiniteStack
InfiniteStack

Reputation: 458

You already have the front-end done, with

<form action = "material.php">

    <input type="file" name="file" enctype="multipart/form-data">

The filename you are submitting, will be automatically available from $_FILES['file']['tmp_name'] array, because the name of the input field is "file", and tmp_name is something PHP adds on its own as the default key.

So, on your back end, add the following to capture the file upload.

The move_uploaded_file is what does the trick!

<?php
    $upload_dir = "/var/www/misyte.com/uploads/";
    $filename = "uploaded_file.txt"; // Rename it to whatever file format..
    $destination = $upload_dir . "/" . $filename;

    if (move_uploaded_file($_FILES['file']['tmp_name'], $destination))
    {
        // If this here succeeds, the file has been moved to destination folder
    }
?>

As a bonus, I've included a function I've written, that will help you split the filename received at the extension "." point and rename your uploaded files to your heart's desires:

    <?php 
        function ExplodeFileAtExtention($Filename)
        {
            $len = strlen($Filename);
            for ($i = 0; $i < $len; $i++)
            {
                $curidx = $len-($i+1);
                if ($Filename[$curidx] == '.')
                {
                    return array(substr($Filename, 0, $curidx), substr($Filename, $curidx + 1));
                }
            }
         }
    ?>

The only reason it exists, is that sometimes the filenames contain more than 1 dot character, as in "some.file.name.txt", and if you simply split it at the first dot character, it still won't return the extension.

So, for example:

$split = ExplodeFileAtExtention("some.file.name.txt");

$filename = $split[0]; // "some.file.name"
$ext      = $split[1]; // "txt"

This way, you can reconstruct (rename) the uploaded file and keep the extension, for example:

$filename= time() . "." . $ext;   // "1471979296.txt"

If you plug that into the first code sniplet, the script will upload and store the file at:

/var/www/misyte.com/uploads/1471979296.txt

Which is good because you probably want some kind of a pattern for all uploaded files, rather than storing them as

"This Awesome Window95~ filename___I__got__from my Program Files folder!!!.txt"

Upvotes: 0

Jodi
Jodi

Reputation: 63

Your code isn't handling the file upload at all. There are a lot of resources on how to handle saving a file upload in PHP. Perhaps if you updated your code to try to handle the file upload, and then said what types of errors you were getting someone could assist you. You could get any number of errors depending on all sorts of things.

Do you have read/write access to the directory you are trying to save the file to?

Do you know the php.ini "upload_max_filesize" setting and is your file smaller than the max upload?

Here's a helpful website that explains the basics: https://davidwalsh.name/basic-file-uploading-php

Upvotes: 1

Related Questions