PHP ssh2.sftp opendir/readdir fix

This bug related to the PECL ssh2 extension bit us yesterday, so this post is a public service announcement that will (hopefully) save you from writing your own workaround like I almost did.

Problem: PHP 5.6.28 (and apparently 7.0.13) introduced a security fix to URL parsing, that caused the string interpolation of the $sftp resource handle to no-longer be recognized as a valid URL. In turn, that causes opendir(), readdir(), etc. to fail when you use an $sftp resource in the path string, after an upgrade to one of those PHP versions.

Solution: Instead of using "ssh2.sftp://$sftp" as a stream path, convert $sftp to an integer like so: "ssh2.sftp://" . intval($sftp) . "/". Then it will work just fine.

Thanks to the people who fixed the URL parsing security flaw, thanks to the people who wrote the PECL ssh2 extension, and thanks to the people who provided the fix.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving your codebase, all while keeping it running the whole time.

9 thoughts on “PHP ssh2.sftp opendir/readdir fix

  1. OMG I owe you a beer and a pizza! Two pizzas!!! I’ve spent the last two days pulling out what was left of my hair trying to figure out why something that has worked for years suddenly stopped working.

    THANK YOU!!!

    And a heartfelt to the PHP devs for totally screwing us up with this….

  2. Thank you so much for this. I’m trying to move some legacy code to a server which looks at least a little more modern, and this was failing time after time. This is the first article I found with an actual solution other than using a third party library, which would have involved a total rebuild. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *