blakeusmate
blakeusmate

Reputation: 13

Upload word document to create a file download (PHP)

I am doing a school project where students can upload study notes to help other students. I have created the ability to upload word/pages files but I want to enable that once the file is uploaded, other users can click on that file and it will download for them.

Not really sure what code to put.. (This is upload.php)

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        $name     = $_FILES['file']['name'];
        $tmpName  = $_FILES['file']['tmp_name'];
        $error    = $_FILES['file']['error'];
        $size     = $_FILES['file']['size'];
        $ext      = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        switch ($error) {
            case UPLOAD_ERR_OK:
                $valid = true;
                //validate file extensions
                if ( !in_array($ext, array('jpg','jpeg','png','gif', 'docx', 'mp3')) ) {
                    $valid = false;
                    $response = 'Invalid file extension.';
                }

And this is where the files go (files.php)

<?php
        //scan "uploads" folder and display them accordingly
       $folder = "uploads";
       $results = scandir('uploads');
       foreach ($results as $result) {
        if ($result === '.' or $result === '..') continue;

        if (is_file($folder . '/' . $result)) {
            echo '
            <div class="col-md-3">
                <div class="thumbnail">
                    <img src="'.$folder . '/' . $result.'" alt="...">
                        <div class="caption">
                        <p><a href="remove.php?name='.$result.'" class="btn btn-danger btn-xs" role="button">Remove</a></p>
                    </div>
                </div>
            </div>';
        }
       }
       ?>

Cheers!

Upvotes: 1

Views: 990

Answers (1)

catzilla
catzilla

Reputation: 1981

If you want to add a link where other users can download the files that are uploaded, try adding an <a> tag with the link of the file in it:

<?php
  //scan "uploads" folder and display them accordingly
  $folder = "uploads";
  $results = scandir('uploads');
  foreach ($results as $result) {
    if ($result === '.' or $result === '..') continue;

    if (is_file($folder . '/' . $result)) {
      $file = $folder.'/'.$result;
      echo '<a href="{$file}" target="_blank">{$result}</a><br/>';
      //other codes
    }
  }
?>

Upvotes: 1

Related Questions