Jul 122015 Tagged with , , 0 Responses

PHP script for renaming files

You might downloaded large amount of images or PDFs while doing web scraping of e-commerce store products, blog posts and in many other cases. Most of web scraping tool provides file downloading either they are csv, vcf, images (jpg,jpeg,gif,png), pdf or other kind of files but many of them do not provide way to rename them or add extension to them if it’s not present.

php script to rename images

I have encountered a problem specially with image files – many websites have images but they do not have the extension and web scraper just download files as it is as example given below, they are the file names downloaded using web scraper but they don’t have extension .jpg or .png!!


This files needs to be have extension like .jpg or .png or any correct image extension. So once all files downloaded it’s hard to rename them in bulk so I have developed handy PHP script to rename files.


$dir = "img"; //folder which has all downloaded images

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "Renaming file:".$dir."/".$file."<br />";
			  $file_name_new = $file.".jpg"; //adding extension to file
			rename($file_name_old, $dir."/".$file_name_new); 


In above script I have renamed all the files in  folder “/img” and added “.jpg” extension to all of them. You can use this script to rename any kind of files PDF, images, vcf, csv, xlsx etc. Also if you want to bulk rename images to SEO friendly name then you need to tweak this script little to replace space with “-” in original name.




Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>