php getimagesize with persian file name

119 views Asked by At

I'm trying to write an Joomla plugin to add width and height tag to each <img> in HTML file. Some image file names are Persian, and getimagesize faces error.

The code is this:

   @$dom->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    <img src="images\banners\س.jpg" style="max-width: 90%;" >
    </body>
    </html>
');

   $x = new DOMXPath($dom);

    foreach($x->query("//img") as $node)
    {   
        $imgtag = $node->getAttribute("src");
        
        $imgtag = pathinfo($imgtag);
        $imgtag = $imgtag['dirname'].'\\'.$imgtag['basename'];
        $imgtag = getimagesize($imgtag);
        
        $node->setAttribute("width",$imgtag[0]);
        $node->setAttribute("height",$imgtag[1]);
    }
    $newHtml = urldecode($dom->saveHtml($dom->documentElement));

And when Persian characters exist in file name, getimagesize shows:

Warning: getimagesize(images\banners\س.jpg): failed to open stream: No such file or directory in C:\wamp64\www\plugin.php

How can I solve this?

1

There are 1 answers

0
Hossein On

Thanks to all, I couldn't reach to results on WAMP server (local server on Windows), but when I migrated to Linux server, finally this code worked properly.


        $html = $app->getBody();

        setlocale(LC_ALL, '');
        $dom = new DOMDocument();
        @$dom->loadHTML($html);

        $x = new DOMXPath($dom);

        foreach($x->query("//img") as $node)
        {   
                $imgtag = $node->getAttribute("src");
            if(strpos($imgtag,"data:image")===false)
            {

                $imgtag = getimagesize($imgtag);
                
                $node->setAttribute("width",$imgtag[0]);
                $node->setAttribute("height",$imgtag[1]);
            }
        }

        $bodytag = $x->query("//body");
        $node = $dom->createElement("script", ' /* java script which may be necessary on client */ '); 

        $bodytag[0]->appendChild($node);

        $html = '<!DOCTYPE html>'."\n" . $dom->saveHtml($dom->documentElement);

Some hints:

  1. the code, shouldn't touch base64 image sources, so I added an condition to the code.
  2. if some script (or whatever, div, p, ....) should be added to body tag, you can use appendChild method.
  3. <!DOCTYPE html> should be added to final DOM object output :)