PHP fopen security risk?

After reading this blog post I realized that getimagesize() doesn’t provide absolute safety so I decided to use imagepng based on this answer. However to be able to use imagepng from image that is uploaded via xmr request, I need to use first this:

$input = fopen("php://input","r");
$temp = tmpfile();
$target = fopen($path,"w")
fseek($tamp,0,SEEK_SET)
stream_copy_to_stream($temp,$target_file_name)

Then I can use

$sourceImg = @imagecreatefromstring(@file_get_contents($source));
if ($sourceImg === false) {
  throw new Exception("{$source}: Invalid image.");
}
$width = imagesx($sourceImg);
$height = imagesy($sourceImg);
$targetImg = imagecreatetruecolor($width, $height);
imagecopy($targetImg, $sourceImg, 0, 0, 0, 0, $width, $height);
imagedestroy($sourceImg);
imagepng($targetImg, $target);
imagedestroy($targetImg);

If image contains some malicious code, could in this case using fopen and stream_copy_to_stream posses any risk? If so, is there any better way if image is uploaded with xmr?