Функции для загрузки и сжатия файлов в своем блоге. GD LIB

Автор: | 18.03.2016
<?
function cyrtolat($text)
{
$cyr  = array('а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у', 
            'ф','х','ц','ч','ш','щ','ъ', 'ы','ь', 'э', 'ю','я','А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У',
            'Ф','Х','Ц','Ч','Ш','Щ','Ъ', 'Ы','Ь', 'Э', 'Ю','Я' );
$lat = array( 'a','b','v','g','d','e','yo','zh','z','i','y','k','l','m','n','o','p','r','s','t','u',
            'f' ,'h' ,'ts' ,'ch','sh' ,'sch' ,'', 'i', '', 'e' ,'yu' ,'ya','A','B','V','G','D','E','YO','Zh','Z','I','Y','K','L','M','N','O','P','R','S','T','U',
            'F' ,'H' ,'Ts' ,'Ch','Sh' ,'SCH' ,'' ,'I','','E' ,'YU' ,'YA' );

return str_replace($cyr,$lat, $text);
}
?>
function makeurl($text)
{
$spec  = array(',','.','!','@','#','$','%','^','&','*','(',')','_','+','=','~','`','\'','\\','/','"',';',':', 
            '<','>','?','{','}','[',']', '|',' ','\t','»','«');
$rep = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','', '','-','-','','');
$text = str_replace(html_entity_decode('&mdash;'),'',$text);
$text=mb_str_replace($spec, $rep, $text);
$text=mb_str_replace("--","-", $text);
$text=mb_str_replace("--","-", $text);
$text=mb_str_replace("--","-", $text);

return $text;
}

 

function compress($path,$file)
{
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
error_reporting(0);
ini_set('memory_limit', '512M');
    if($ext=='jpg' || $ext=='jpeg'|| $ext=='png'|| $ext=='gif')
      {
      $stamp = imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].'/images/wm.png');
      $sfile=$path."s_".$file;
      $lfile=$path."l_".$file;
      $fullfile=$path.$file;
      if(!($im = imagecreatefromjpeg($fullfile)))
        $im = imagecreatefrompng($fullfile);
      if($im)
        {
        $marge_right = 10;
        $marge_bottom = 10;
        $sx = imagesx($stamp);
        $sy = imagesy($stamp);
        imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
        imagejpeg($im,$fullfile);
        $iw = imagesx($im); 
        $ih = imagesy($im);
        $k = 650 / $iw;
        if($k>1)$k=1;
        $sx = floor($iw * $k); $sy = floor($ih * $k);
        $im_m = imagecreatetruecolor($sx, $sy);
        imagealphablending( $im_m, false );
        imagesavealpha( $im_m, true );
        $transparent = imagecolorallocatealpha($im_m, 255, 255, 255,255);
        
        imagefilledrectangle($im_m, 0, 0, $sx, $sy, $transparent);				
        imagecopyresampled($im_m, $im, 0, 0, 0, 0, $sx, $sy, $iw, $ih);
        $r_l = imagejpeg($im_m,$lfile);

        $iw = imagesx($im); $ih = imagesy($im);
        $k = 200 / $iw;
        if($k>1)$k=1;
        $sx = floor($iw * $k); $sy = floor($ih * $k);
        $im_m = imagecreatetruecolor($sx, $sy);
        imagealphablending( $im_m, false );
        imagesavealpha( $im_m, true );
        $transparent = imagecolorallocatealpha($im_m, 255, 255, 255, 127);
        imagefilledrectangle($im_m, 0, 0, $sx, $sy, $transparent);				
        imagecopyresampled($im_m, $im, 0, 0, 0, 0, $sx, $sy, $iw, $ih);
        $r_s = imagejpeg($im_m,$sfile);
        }
      else
        {
        copy($fullfile, $lfile);
        copy($fullfile, $sfile);
        }
      }
  
  
error_reporting(1);
}

 

function getpath($max)
  {
  $docroot=$_SERVER['DOCUMENT_ROOT']."/";
  include $docroot."config.php";
  
  
  if($max<10)$max='00'.$max;
        else
      if($max<100)$max='0'.$max;
      $targetPath=$docroot.'uploads/'.$max[0].'/'.$max[1].'/'.$max[2].'/';
      
  return $targetPath; 
  }
mysql_connect("localhost","root","");
mysql_select_db("img");
mysql_query("insert into `img` (`path`) values 
('{$_FILES[fileToUpload][name]}')");
$t=mysql_query(
"select `id` from `img` order by `id` desc limit 1");
$res=mysql_fetch_array($t);//последний id
$ext = strtolower(pathinfo($_FILES[fileToUpload][name], 
PATHINFO_EXTENSION));//расширение файла

$filename=makeurl(cyrtolat(
pathinfo(
$_FILES[fileToUpload][name],PATHINFO_FILENAME)));//имя в латиницу и убираем спец символы
$file=$filename.".".$ext;
$path=getpath($res['id']);//получаем полный путь с учетом id ->/0/0/1/
move_uploaded_file( $_FILES[fileToUpload]['tmp_name'], $path.$file);
compress($path,$file);
$fullfile=$path.$file;
mysql_query("update `img` set `path`='{$fullfile}' where `id`='{$res['id']}'");
<?
//-------------------------------------------------------------------------------------------------------------
function cyrtolat($text)
{
$cyr  = array('а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у', 
            'ф','х','ц','ч','ш','щ','ъ', 'ы','ь', 'э', 'ю','я','А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У',
            'Ф','Х','Ц','Ч','Ш','Щ','Ъ', 'Ы','Ь', 'Э', 'Ю','Я' );
$lat = array( 'a','b','v','g','d','e','yo','zh','z','i','y','k','l','m','n','o','p','r','s','t','u',
            'f' ,'h' ,'ts' ,'ch','sh' ,'sch' ,'', 'i', '', 'e' ,'yu' ,'ya','A','B','V','G','D','E','YO','Zh','Z','I','Y','K','L','M','N','O','P','R','S','T','U',
            'F' ,'H' ,'Ts' ,'Ch','Sh' ,'SCH' ,'' ,'I','','E' ,'YU' ,'YA' );

return str_replace($cyr,$lat, $text);
}
//-------------------------------------------------------------------------------------------------------------
function makeurl($text)
{
$spec  = array(',','.','!','@','#','$','%','^','&','*','(',')','_','+','=','~','`','\'','\\','/','"',';',':', 
            '<','>','?','{','}','[',']', '|',' ','\t','»','«');
$rep = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','', '','-','-','','');
$text = str_replace(html_entity_decode('&mdash;'),'',$text);
$text=str_replace($spec, $rep, $text);
$text=str_replace("--","-", $text);
$text=str_replace("--","-", $text);
$text=str_replace("--","-", $text);

return $text;
}
//-------------------------------------------------------------------------------------------------------------
function compress($path,$file)
{
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
error_reporting(0);
ini_set('memory_limit', '512M');
    if($ext=='jpg' || $ext=='jpeg'|| $ext=='png'|| $ext=='gif')
      {
      $stamp = imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].'/images/wm.png');
      $sfile=$path."s_".$file;
      $lfile=$path."l_".$file;
      $fullfile=$path.$file;
      if(!($im = imagecreatefromjpeg($fullfile)))
        $im = imagecreatefrompng($fullfile);
      if($im)
        {
        $marge_right = 10;
        $marge_bottom = 10;
        $sx = imagesx($stamp);
        $sy = imagesy($stamp);
        imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
        imagejpeg($im,$fullfile);
        $iw = imagesx($im); 
        $ih = imagesy($im);
        $k = 600 / $iw;
        if($k>1)$k=1;
        $sx = floor($iw * $k); $sy = floor($ih * $k);
        $im_m = imagecreatetruecolor($sx, $sy);
        imagealphablending( $im_m, false );
        imagesavealpha( $im_m, true );
        $transparent = imagecolorallocatealpha($im_m, 255, 255, 255,255);
        
        imagefilledrectangle($im_m, 0, 0, $sx, $sy, $transparent);				
        imagecopyresampled($im_m, $im, 0, 0, 0, 0, $sx, $sy, $iw, $ih);
        $r_l = imagejpeg($im_m,$lfile);

        $iw = imagesx($im); $ih = imagesy($im);
        $k = 200 / $iw;
        if($k>1)$k=1;
        $sx = floor($iw * $k); $sy = floor($ih * $k);
        $im_m = imagecreatetruecolor($sx, $sy);
        imagealphablending( $im_m, false );
        imagesavealpha( $im_m, true );
        $transparent = imagecolorallocatealpha($im_m, 255, 255, 255, 127);
        imagefilledrectangle($im_m, 0, 0, $sx, $sy, $transparent);				
        imagecopyresampled($im_m, $im, 0, 0, 0, 0, $sx, $sy, $iw, $ih);
        $r_s = imagejpeg($im_m,$sfile);
        }
      else
        {
        copy($fullfile, $lfile);
        copy($fullfile, $sfile);
        }
      }
  
  
error_reporting(1);
}
//---------------------------------------------------------------------------------------------------------
function getpath($max)
  {
  $docroot=$_SERVER['DOCUMENT_ROOT']."/";

  
  
  if($max<10)$max='00'.$max;
        else
      if($max<100)$max='0'.$max;
      $targetPath=$docroot.'uploads/'.$max[0].'/'.$max[1].'/'.$max[2].'/';
      
  return $targetPath;		
  }
//-------------------------------------------------------------------------------------------------------
?>
<?
mysql_connect("localhost","root","");
mysql_select_db("img");
mysql_query("insert into `img` (`path`) values 
('{$_FILES[fileToUpload][name]}')");
$t=mysql_query(
"select `id` from `img` order by `id` desc limit 1");
$res=mysql_fetch_array($t);//последний id
$ext = strtolower(pathinfo($_FILES[fileToUpload][name], 
PATHINFO_EXTENSION));//расширение файла

$filename=makeurl(cyrtolat(
pathinfo(
$_FILES[fileToUpload][name],PATHINFO_FILENAME)));//имя в латиницу и убираем спец символы
$file=$filename.".".$ext;
$path=getpath($res['id']);//получаем полный путь с учетом id ->/0/0/1/
move_uploaded_file( $_FILES[fileToUpload]['tmp_name'], $path.$file);
compress($path,$file);
$fullfile=$path.$file;
mysql_query("update `img` set `path`='{$fullfile}' where `id`='{$res['id']}'");
?>
<html>
  <head>
    <meta name='robots' content='noindex'>
  </head>
  
  <body>
    <form action="" method="post" enctype="multipart/form-data">
      Выберите файл для загрузки:
      <input type="file" name="fileToUpload" id="fileToUpload">
      <input type="submit" value="Загрузить" name="submit">
    </form>
  </body>
  
</html>

 

Раздел: PHP