Fully converted from Node to PHP