I would like to convert all images in the folder to jpg
The script in the question is not doing that, it's simply renaming files; a gif named foo.jpg
is still a gif.
A browser may ignore the headers and display the misnamed image file correctly (to a browser the filename/url is unimportant - the headers are what determine the format, however the webserver will send the content-type header based on the filename) - It may however simply treat the image as a broken jpeg and display nothing.
Converting files is more than renaming them
You can use tools such as ImageMagik to correctly convert image files from one format to another.
A script to use ImageMagik (cheating via cli since it's simpler to use) would be for example:
<?php
$directory = "img/";
chdir($directory);
$images = glob($directory . "*");
foreach($images as $image) {
if (substr($image, -4) === '.jpg') {
continue;
}
$newname = preg_replace('@\..*$@', '.jpg', $image);
`convert $image $newname`;
}
Use the right tool for the job
Note that the above PHP script may work but there are more appropriate tools that can be used. For example mogrify is another cli provided by ImageMagik which can be used to perform batch operations. Converting all png files to jpeg in a single folder is this simple:
$ cd imgs/are/here/
$ mogrify -format jpg *.png