if (!$mysql->query($query, array($media_id))) { die($mysql->error); } if ($mysql->num_row > 0) { $media = $mysql->data[0]; if (file_exists(dirname(__DIR__) . '/upload/' . $media['filePath'])) { if ($media['media_type'] == 'image') { $path = '../upload/' . $media['filePath']; $header = image_type_to_mime_type(exif_imagetype($path)); } else { $returnArr = array('code' => 200, 'type' => $media['media_type'], 'path' => '../upload/' . $media['filePath']); die(json_encode($returnArr)); } } } else { $result = $wechat->getPermanentMedia($media_id); try { if (!$result['hasError']) { if (($rawdata = json_decode($result['data'], true)) == null) { $rawdata = $result['data']; // ------------- save the file -------------- $filename = time(); $tempFile = "tmp/" . $filename . ".tmp"; $destination = dirname(__DIR__) . '/upload/' . $tempFile; $fp = fopen($destination, 'w+'); fwrite($fp, $rawdata); fclose($fp); if (!file_exists($destination)) { throw new Exception('file cannot be saved'); } // get the media type and map the file extension