Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate file upload in php command line

Tags:

php

phpunit

I'm new to PHPUnit testing framework.

as we know that move_uploaded_file() function of PHP will not work until the file is uploaded via http POST method

So, the Question is how to simulate this in PHP command line

Note: using selenium we can simulate webform.. but i need another alternative.

like image 315
khizar ansari Avatar asked Nov 26 '12 11:11

khizar ansari


People also ask

How do I upload a file using curl command?

How to send a file using Curl? To upload a file, use the -d command-line option and begin data with the @ symbol. If you start the data with @, the rest should be the file's name from which Curl will read the data and send it to the server. Curl will use the file extension to send the correct MIME data type.

What is Tmp_name in PHP file upload?

tmp_name is the temporary name of the uploaded file which is generated automatically by php, and stored on the temporary folder on the server. name is the original name of the file which is store on the local machine.


1 Answers

You basically need to make your code more testable. Break it down so you can test the simple act of uploading a file through HTTP separately from the rest of the code. The primary use of move_uploaded_file is to put in an extra security stop so you cannot be tricked into moving some other file, move_uploaded_file simply makes sure that the file was uploaded in the same request and then moves it. You can simply move the file using rename as well. As such, break your application down to have one Request object which represents and encapsulates the current HTTP request, including making it check uploaded files using is_uploaded_file. Once that's validated, you can use rename instead of move_uploaded_file. In your tests you can then mock the Request object and test your other code.

You can also simply make move_uploaded_file mockable, for example like this:

class Foo {

    public function do() {
        ...
        $this->move_uploaded_file($from, $to);
        ...
    }

    protected function move_uploaded_file($from, $to) {
        return move_uploaded_file($from, $to);
    }

}

In your tests you can extend/mock the class and override Foo::move_uploaded_file to always return true, for instance.

like image 107
deceze Avatar answered Nov 14 '22 21:11

deceze