Securing an Image Upload Script
This is a bad example of correcting user input:

$filecontent = str_replace(array("&lt;?php", "&lt;?", "?&gt;"), "", $filecontent);


I could still upload an image with the following comment in it:

&lt;?&lt;?phpphp echo "this code gets executed"; ??&gt;&gt;


because after your str_replace the comment would be

&lt;?php echo "this code gets executed"; ?&gt;


Instead of correcting user input, you should simply search for these strings reject and the image if it contains &lt;?. Why should you save the image anyway if you suspect an hacker attack? ;-)

Edit: This would be better

// test for opening php tags
// including asp-style opening tags (http://www.php.net/manual/en/ini.core.php#ini.asp-tags)
if(strpos($filecontent, "&lt;?") !== false || strpos($filecontent, "&lt;%") !== false) {
  // stop upload
}


Edit:
And one other thing I forgot to mention. Never use the original filename of the upload without validating it!

Because you could receive a request like this:

POST /upload.php HTTP/1.1
Host: localhost
Content-Length: 318
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="../hello.jpg"
Content-Type: image/jpeg

&lt;?php echo "evil code"; ?&gt;
------WebKitFormBoundaryePkpFF7tjBAqx29L


And the "image" file gets saved in the directory above.

Better generate your own file names.