Mantığı tam çözemedim ama, ilk if sorgusunu şöyle değiştirip dener misiniz:

if(curl_errno($ch) != '')