Fake uploading files

A few days ago I encountered a problem where I needed to test a controller that handles file uploads. I couldn’t find an easy way to unit test the code which used built-in uploading functionality so I decided to whip up this simple extension that allows to fake file uploads.

The extension is doing things that shouldn’t be done, it probably doesn’t even run anywhere else than on CLI, it is insecure, it might behave incorrectly but in this scenario it worked fine so I decided to share it. Don’t ask for support or any updates for this extension and use it on your own risk. I take no responsibility of anything (especially related to this extension).

The following example code might work with the extension:

  1. <?php
  2. fakeupload_file("userFile", '/Users/test/test.txt',
  3.                         "/tmp/upload.tmp", "text/plain", "This is a test upload");
  4.  
  5. var_dump(is_uploaded_file('/tmp/upload.tmp'));
  6.  
  7. var_dump($_FILES);
  8.  
  9. var_dump(move_uploaded_file("/tmp/upload.tmp", "/tmp/test_file.txt"));
  10.  
  11. unlink("/tmp/test_file.txt");
  12. ?>

And it can be executed using:

  1. # php -dfakeupload.enabled=1 test.php
  2. bool(true)
  3. array(1) {
  4.   ["userFile"]=>
  5.   array(5) {
  6.     ["name"]=>
  7.     string(20) "/Users/test/test.txt"
  8.     ["type"]=>
  9.     string(10) "text/plain"
  10.     ["tmp_name"]=>
  11.     string(15) "/tmp/upload.tmp"
  12.     ["error"]=>
  13.     int(0)
  14.     ["size"]=>
  15.     int(21)
  16.   }
  17. }
  18. bool(true)

The source can be found here: fakeupload-0.0.2.tgz