السلام عليكم ورحمة الله وبركاته ..
ياليت مشاركتي تطوير برمجة بسيطه لرفع الصور م جميع النواحي
هيكلة الكود وامنه و سهولته و و و
1. استقبال الصورة + تعيين الاعدادات
كود PHP:
//المتغيرات
$file_type = $_FILES['image']['type'];
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
//الاعدادات
$path_images = "images";
$path_thumb = "thumbimages";
$limitedext = array(".gif",".jpg",".png",".jpeg");
$minsize = 20000 ;
$maxsize = 2000000;
$ThumbWidth = 150;
2. فحص الأخطاء
كود PHP:
if (isset($_FILES["image"]["size"]) < $minsize)
{
$errors[] = "الملف اصغر من 2 كيلو بايت";
}
if ($_FILES["image"]["size"] > $maxsize)
{
$errors[] = " الملف اكبر من 2 ميقا ";
}
// فحص تم اختيار ملف ام لا.
if(!is_uploaded_file($file_tmp)){
$errors[] = "الرجاء اختيار ملف";
}
// فحص امتداد الصورة
if(!isset($errors)){
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
// امتداد غير مسموح
if (!in_array($ext,$limitedext)) {
$errors[] = "نوع الملف غير مسموح";
}
else {
3. تصغير ونسخ الصورة
كود PHP:
// تكوين اسم ملف جديد
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
$rand_name = md5(time());
$rand_name= rand(0,999999999);
// تكوين الصور حسب نوعها لغرض تصغييرها
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//تفصيل العرض و الارتفاع و نسبة الارتفاع.
list($width, $height) = getimagesize($file_tmp);
// حساب الطول والعرض الجديد
$imgratio=$width/$height;
if ($imgratio>1)
{
$newwidth = $ThumbWidth;
$newheight = 150/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = 150*$imgratio;
}
// دوال اعادة تصغير الصورة.
if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth,$newheight);
}else{
$errors[] = "الرجاء التاكد انك تمتلك مكتبة gd");
}
// تصغير الصورة
imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// اخيرا حفظ الصورة
ImageJpeg ($resized_img,"../$path_thumb/$rand_name.$file_ext");
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
// نسخ الملف الاصلي لمجلد اخر
move_uploaded_file ($file_tmp, "../$path_images/$rand_name.$file_ext");
// اسم الملف النهائي
$image = $rand_name.".".$file_ext ;
}
}
اتمنى التطوير مع بعض :nosweat: