I was able to determine that the JsonWireProtocol for uploading the file would be /session/<sessionId>/file
by checking the raw log in the SauceLabs.com blog ( https://saucelabs.com/jobs/1a408cf60af0601f49052f66fa37812c/selenium-server.log ), so I created this function to add to the php-webdriver-bindings library:
public function sendFile($value) { $file = @file_get_contents($value); if( $file === false ) { return false; } $file = base64_encode($file); $request = $this->requestURL . "/file"; $session = $this->curlInit($request); $args = array( 'file' => $file ); $postargs = json_encode($args); $this->preparePOST($session, $postargs); $response = trim(curl_exec($session)); $responseValue = $this->extractValueFromJsonResponse($response); return $responseValue; }
Add this to the WebDriver.php file.
To use, just do something like this:
... $file_location = $webdriver->sendFile('http://test.com/some/file.zip'); $file_input = $webdriver->findElementBy(LocatorStrategy::id, 'uploadfile'); $file_input->sendKeys(array($file_location));
I hope this helps other developers who spend 3 hours finding the answer to this question.
Update:
I had to change this due to getting this error:
Expected there to be only 1 file. There were: 0
We hope that this will lead to Google results (I tried to find the error message on Google, and the only results that he could find were links to the source code in Google Code).
To solve this problem, I was able to deduce that the file you are sending should actually be archived. So I added the source code for using the PHP ZipArchive library. I will keep the old code for writing, but please use the new code here:
public function sendFile($value, $file_extension = '') { $zip = new ZipArchive(); $filename_hash = sha1(time().$value); $zip_filename = "{$filename_hash}_zip.zip"; if( $zip->open($zip_filename, ZIPARCHIVE::CREATE) === false ) { echo 'WebDriver sendFile $zip->open failed\n'; return false; } $file_data = @file_get_contents($value); if( $file_data === false ) { throw new Exception('WebDriver sendFile file_get_contents failed'); } $filename = "{$filename_hash}.{$file_extension}"; if( @file_put_contents($filename, $file_data) === false ) { throw new Exception('WebDriver sendFile file_put_contents failed'); } $zip->addFile($filename, "{$filename_hash}.{$file_extension}"); $zip->close(); $zip_file = @file_get_contents($zip_filename); if( $zip_file === false ) { throw new Exception('WebDriver sendFile file_get_contents for $zip_file failed'); } $file = base64_encode($zip_file); $request = $this->requestURL . "/file"; $session = $this->curlInit($request); $args = array( 'file' => $file ); $postargs = json_encode($args); $this->preparePOST($session, $postargs); $response = trim(curl_exec($session)); return $this->extractValueFromJsonResponse($response); }
Update:. Turns off, you need to set two parameters in the $ zip-> addFile () method. Edited the above code to reflect the changes.