.htaccess kodu
Webp_generator.php
PHP:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^webp/(.*)\.webp?$ webp_generator.php?file=$1 [QSA]
Webp_generator.php
PHP:
<?php
$settings_document_root = dirname(__FILE__);
$file = trim(strip_tags($_GET['file']));
if(!is_file($file)){
// include("404.php");
echo "resim bulunamadı";
exit;
}
// detect if file is png/jpg/gif, for gif we use gif2webp command
$file_extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
// mkdir -p to create parent directories if needed (e.g a full path of sub directories)
exec("mkdir -p ".escapeshellarg("webp/".dirname($file)));
// convert png, jpg
if($file_extension=="png" or $file_extension=="jpg"){
exec("cwebp -q 80 ".escapeshellarg($settings_document_root."/".$file)." -o ".escapeshellarg($settings_document_root."/webp/".$file.".webp"));
}
// convert gif
if($file_extension=="gif"){
exec("gif2webp -q 80 ".escapeshellarg($settings_document_root."/".$file)." -o ".escapeshellarg($settings_document_root."/webp/".$file.".webp"));
}
// show warning if file was not generated properly, you can replace this with a header() redirect to a default image
if(!file_exists($settings_document_root."/webp/".$file.".webp")){
echo "cannot generate webp file ".escapeshellarg("webp/".$file);
exit;
}
// maintenance, delete old webp files, then delete empty directories
exec("find webp/ -type f -mtime +30 -delete");
exec("find webp/ -type d -empty -delete");
// continue to showing the generated web file
// the ?time() is there so that it doesn't redirect back to itself on first time when image is generated
// that can cause an infinite loop because it caches file as a redirect back to itself
header("Location: /webp/".$file.".webp?".time());
exit;
?>