How to write to a text file and save it in a folder for later download?

Tom has a good point. I wouldn’t suggest anyone to do this.

However… Here’s how I previously did it 😉

It’s quite extensive, though.


Step 1 – Cut a hole in the box

  1. Add a file called ‘custom-upload-file.php’ in your WordPress theme-folder, and add this to it:
<?php
// Getting the header to get WordPress-functions available
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

$errors       = [];
$confirmation = [];
$post_id      = '';

if( is_user_logged_in() ):

  // Check that post_id is set
  if( ! empty( $_POST['post_id'] ) ):
    $post_id = $_POST['post_id'];

    $docs_folder = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/custom-uploaded-files';
    // Check that the doc-folder exists
    if( file_exists( $docs_folder ) ):

      // Create the folder, if it doesn't exist
      if( ! file_exists( $docs_folder . '/post' . $post_id ) ):
        $folder_created = mkdir( $docs_folder . '/post' . $post_id );
        if( ! $folder_created ):
          $errors[] = 'Destination folder didnt exists and couldnt be created.';
        endif; // if( $folder_created ):
      endif; // if( file_exists( $docs_folder . '/post' . $post_id ) ):

      // Check that the folder exists (which it always will, now)
      if( file_exists( $docs_folder . '/post' . $post_id ) ):

        // Check that the file aren't empty
        if( ! empty( $_FILES['files']['name'][0] ) ):
          $sanitized_filename = filter_var( $_FILES['files']['name'][0], FILTER_SANITIZE_URL );
          $approved_formats   = array(
            'jpg',
            'jpeg',
            'png',
            'gif',
            //          'mov',
            //          'avi',
            'mpg',
            //          '3gp',
            //          '3g2',
            //          'midi',
            //          'mid',
            'pdf',
            'doc',
            'ppt',
            'odt',
            'pptx',
            'docx',
            //          'pps',
            //          'ppsx',
            'xls',
            'xlsx',
            //          'key',
            //          'mp3',
            //          'ogg',
            //          'flac',
            //          'm4a',
            //          'wav',
            //          'mp4',
            //          'm4v',
            //          'webm',
            //          'ogv',
            //          'flv'
          );

          $fileinfo  = pathinfo( $sanitized_filename );
          $extension = $fileinfo['extension'];

          if( in_array( $extension, $approved_formats ) ):

            // Determining the filename
            $counter                      = 1;
            $file_name_path_not_available = true;
            $filename                     = $fileinfo['filename'];
            $filename_modification        = '';
            while( $file_name_path_not_available ):
              if( file_exists( $docs_folder . '/post' . $post_id . "https://wordpress.stackexchange.com/" . $filename . $filename_modification . '.' . $extension ) ):
                $filename_modification = '-' . $counter;
                $counter ++;
              else:
                $file_name_path_not_available = false;
              endif; // if( file_exists( $docs_folder . '/post' . $post_id . "https://wordpress.stackexchange.com/" . $fileinfo['basename'] ) ):
            endwhile; // while( $file_name_path_not_available ):

            // Saving the file
            $file_uploaded = move_uploaded_file( $_FILES['files']['tmp_name'][0], $docs_folder . '/post' . $post_id . "https://wordpress.stackexchange.com/" . $filename . $filename_modification . '.' . $extension );
            if( $file_uploaded ):
              $file_info_array = array(
                'uploaded_by' => get_current_user_id(),
                'file_name' => $filename . $filename_modification . '.' . $extension
              );
              add_post_meta( $post_id, 'fileupload', serialize( $file_info_array ) );
              $confirmation[] = 'Filen blev gemt.';
            else:
              $errors[] = 'Error. File was not saved.';
            endif; // if( $file_saved ):

          else:
            $errors[] = 'Error. The format of the uploaded file wasnt allowed. Please try another format.';
          endif; // if( in_array( $extension, $approved_formats ) ):

        else:
          $errors[] = 'No file was selected.';
        endif; // if( !empty( $_POST['file'] ) ):
      endif; // if( file_exists( $docs_folder . '/post' . $post_id ) ):

    else:
      $errors[] = 'The destination-folder didnt exists and couldnt be created.';
    endif; // if( file_exists( $folder ) ):

  else:
    $errors[] = "The Post-ID was empty, so it couldnt be determined where it should be saved.";
  endif; //  if( !empty( $_POST['post_id'] ) ):

else:
  $errors[] = "You are not logged in.";
endif; // if( ! is_user_logged_in() ):

$_SESSION['display_messages']          = true;
$_SESSION['upload_errors']       = $errors;
$_SESSION['upload_confirmation'] = $confirmation;

header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
exit();
?>

It checks for a bunch of things. I tried added some good comments.


Step 2 – Put your junk in the box

Now create a custom page-template, again in your theme-folder and call it page-upload-file.php. Then put this inside that file:

<?php
/**
 * Template Name: Upload file template
 */

get_header(); ?>

<main>

  <div class="container-fluid">
    <div class="container">
      <div class="row">
        <div class="col-8">

          <h1>
            <?php the_title(); ?>
          </h1>

          <div class="entry-content">
            <?php the_content(); ?>
          </div>

        </div>
        <!-- /.col-8 -->

        <div class="col-4">
          <form action="<?php echo get_stylesheet_directory_uri() . '/custom-upload-file.php'; ?>" method="post" enctype="multipart/form-data">
            <input class="upload__file-button" type="file" name="files[]">
            <!-- /.upload__files-label -->
            <input type="hidden" name="post_id" value="<?php echo get_the_id(); ?>">
            <input type="submit" value="Upload">
          </form>
        </div>
        <!-- /.col-4 -->

      </div>
      <!-- /.row -->
    </div>
    <!-- /.container -->
  </div>
  <!-- /.container-fluid -->

</main>

<?php get_footer(); ?>

Step 3 – Make her open the box

Then create a new page and set the new page-template. And try it out.

I haven’t tested it though, but the code is pulled and modified a bit from a previous solution that is in production. So I know that I got it working at some point.