应用笔记 · 2014年2月24日

HOWTO: Do PUT requests with PHP cURL without writing to a file

From: http://developer.sugarcrm.com/2011/11/22/howto-do-put-requests-with-php-curl-without-writing-to-a-file/

I was helping a partner the other day with an issue they were having in a module they developed for Sugar that is safe to load on our On Demand environment. Here’s the code he was using that was causing issues:

The problem here is that the tmpfile(), fwrite(), and fseek() functions are not allowed on the OD environment, as we don’t block raw file operations for potential security issues. However, the suggested way of doing PUT requests with cURL implies that you are PUTing a file, and it assumes you are reading a file from the filesystem. In this case however, the PUT payload is being generated as JSON, but to work with cURL it’s wanting you to inefficiently write it to a temporary file in order to send it.

Then I came across this post from esteemed PHP Community member Lorna Jane Mitchell, which showed a techique to get around this. So with help from that post, here’s how we refactored the code to eliminate the extranous file write.

The key here is to not use the built-in PUT handling, but instead use the  CURLOPT_CUSTOMREQUESTattribute to specify the request type we want manually, and then the CURLOPT_POSTFIELDS to pass the payload. And this works perfectly for Sugar On Demand, and eliminates the overhead of a filesystem write and read.