Check for false meaning failure in your functions

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the algorithms category.

Last Updated: 2024-04-24

I had the following code for uploading files:

<?php

function uploadFileViaSftp($file)
{
  $this->sftp->put($file, $file, SFTP::SOURCE_LOCAL_FILE);
  return true;
}

The entire function returned true, yet it didn't work right. The issue? The first function call sftp->put returned false (instead of an exception, as I was expecting with no good reason). I didn't inspect this output and just returned true no matter what.

Instead I should have had:

<?php

$success = $this->sftp->put($file, $file, SFTP::SOURCE_LOCAL_FILE);
if (!$success) {
  throw new Exception('File upload failed');
}

Lesson

Use more if statements and exceptions to ensure some crucial step didn't return false. Not all library or language functions throw exceptions where you imagine they would or should.