2011-02-07 1 views
2

Я создаю сайт, на котором будут показаны ночные гуляки, список ночных клубов и событий, происходящих в большом городе. Я пытаюсь создать внутреннюю страницу, где администратор может добавлять клубы и вводить информацию, такую ​​как имя учреждения, местоположение, относительные цены и т. Д. И, конечно, некоторые изображения клуба.Загрузка и хранение нескольких файлов с несколькими файлами в папке и базе данных

В каждом клубе должно быть хотя бы одно изображение, основное изображение. Могут быть дополнительные 5, но они необязательны, т.е. поля базы данных могут быть пустыми.

У меня есть форма, которая выглядит следующим образом:

Establishment Main Photo 
TextField: name = "establishment_image" 

Establishment Photo 1 
TextField: name = "establishment_image" 

Establishment Photo 2 
TextField: name = "establishment_image" 

Establishment Photo 3 
TextField: name = "establishment_image" 

Establishment Photo 4 
TextField: name = "establishment_image" 

Establishment Photo 5 
TextField: name = "establishment_image" 

Его любопытное, как Yahoo Mail придают форму файла. Как вы можете видеть, текстовые поля имеют одно и то же имя текстового поля.

Мне нужно знать, какие изменения мне необходимо внести в мою форму отправки, чтобы иметь возможность: например;

Поместите основной ПОС и оставить другие текстовые поля пустым, Поместите основной рис, рис 1 и 2 и оставить другие текстовые поля пустым, Поместите основной рис, рис 1, 2 и 3 и оставить другие текстовые поля пустыми т.д.

Мой establishment_submit.php выглядит следующим образом:

<?php require_once('../Connections/connections.php'); ?> 
<?php //maintain the session 
if (!isset($_SESSION)) 
{ 
    session_start(); 
} 
?> 
<?php 
//retrieve data from Query String 
$establishment_name= $_POST['establishment_name']; 
$short_description= $_POST['short_description'];   
$long_description= $_POST['long_description'];  
$location= $_POST['location'];   
$url_link= $_POST['url_link']; 
$establishment_address= $_POST['establishment_address'];   
$establishment_pricing= $_POST['establishment_pricing']; 
$establishment_telephone= $_POST['establishment_telephone'];   
$establishment_contact= $_POST['establishment_contact']; 
$establishment_email= $_POST['establishment_email'];    
$establishment_image = $_FILES['establishment_image']['name']; 

//escape User Input to help prevent SQL Injection 
$establishment_name= mysql_real_escape_string($establishment_name);  
$short_description= mysql_real_escape_string($short_description);  
$long_description = mysql_real_escape_string($long_description);   
$location= mysql_real_escape_string($location);    
$url_link= mysql_real_escape_string($url_link); 
$establishment_address= mysql_real_escape_string($establishment_address); 
$establishment_pricing= mysql_real_escape_string($establishment_pricing); 
$establishment_telephone= mysql_real_escape_string($establishment_telephone); 
$establishment_contact= mysql_real_escape_string($establishment_contact); 
$establishment_email= mysql_real_escape_string($establishment_email); 
$establishment_image= mysql_real_escape_string($establishment_image); 

//redirect when successful 
$establishmentAddSuccess = "establishment_add_success.php"; 
?> 
<?php 
//define a maximum size for the uploaded images 
define ("MAX_SIZE","10000"); 
// note that these dimensions are considered the maximum and are not fixed 
// because we have to keep the image ratio intact 
//define a maximum size for the uploaded images 
define ("LARGE_WIDTH","500"); 
define ("LARGE_HEIGHT","390"); 
define ("WIDTH","100"); //set here the width you want your thumbnail to be 
define ("HEIGHT","100"); //set here the height you want your thumbnail to be. 
// this is the function that will create the appropriately sized images from the upload 
// the resize will be done considering the width and height defined, but without deforming the image 

function make_largeimage($img_name,$filename,$new_large_w,$new_large_h) 
{ 
    //get image extension. 
    $ext=getExtension($img_name); 
    //creates the new image using the appropriate function from gd library 
    if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) 
    $src_img=imagecreatefromjpeg($img_name); 
    if(!strcmp("png",$ext)) 
    $src_img=imagecreatefrompng($img_name); 
    if(!strcmp("gif",$ext)) 
    $src_img=imagecreatefromgif($img_name); 
    //gets the dimensions of the image 
    $old_x=imageSX($src_img); 
    $old_y=imageSY($src_img); 
    // next we will calculate the new dimensions for the large image 
    // the next steps will be taken: 
    // 1. calculate the ratio by dividing the old dimensions with the new ones 
    // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable 
    // and the height will be calculated so the image ratio will not change 
    // 3. otherwise we will use the height ratio for the image 
    // as a result, only one of the dimensions will be from the fixed ones 
    $ratio1_large=$old_x/$new_large_w; 
    $ratio2_large=$old_y/$new_large_h; 
    if($ratio1_large>$ratio2_large) 
    { 
     $large_w=$new_large_w; 
     $large_h=$old_y/$ratio1_large; 
    }else 
    { 
     $large_h=$new_large_h; 
     $large_w=$old_x/$ratio2_large; 
    } 
    // we create a new image with the new dimensions 
    $dst_large_img=ImageCreateTrueColor($large_w,$large_h); 
    // resize the big image to the newly created one 
    imagecopyresampled($dst_large_img,$src_img,0,0,0,0,$large_w,$large_h,$old_x,$old_y); 
    // output the created image to the file. Now we will have the image into the file named by $filename 
    if(!strcmp("png",$ext)) 
     imagepng($dst_large_img,$filename); 
    else 
     imagejpeg($dst_large_img,$filename); 
    if (!strcmp("gif",$ext)) 
    imagegif($$dst_large_img,$filename); 
    //destroys source and destination images. 
    imagedestroy($dst_large_img); 
    imagedestroy($src_img); 
} 

function make_thumb($img_name,$filename,$new_w,$new_h) 
{ 
    //get image extension. 
    $ext=getExtension($img_name); 
    //creates the new image using the appropriate function from gd library 
    if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) 
    $src_img=imagecreatefromjpeg($img_name); 
    if(!strcmp("png",$ext)) 
    $src_img=imagecreatefrompng($img_name); 
    if(!strcmp("gif",$ext)) 
    $src_img=imagecreatefromgif($img_name); 
    //gets the dimmensions of the image 
    $old_x=imageSX($src_img); 
    $old_y=imageSY($src_img); 
    // next we will calculate the new dimensions for the thumbnail image 
    // the next steps will be taken: 
    // 1. calculate the ratio by dividing the old dimensions with the new ones 
    // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable 
    // and the height will be calculated so the image ratio will not change 
    // 3. otherwise we will use the height ratio for the image 
    // as a result, only one of the dimensions will be from the fixed ones 
    $ratio1=$old_x/$new_w; 
    $ratio2=$old_y/$new_h; 
    if($ratio1>$ratio2) 
    { 
     $thumb_w=$new_w; 
     $thumb_h=$old_y/$ratio1; 
    }else 
    { 
     $thumb_h=$new_h; 
     $thumb_w=$old_x/$ratio2; 
    } 
    // we create a new image with the new dimensions 
    $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); 
    // resize the big image to the newly created one 
    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
    // output the created image to the file. Now we will have the thumbnail into the file named by $filename 
    if(!strcmp("png",$ext)) 
     imagepng($dst_img,$filename); 
    else 
     imagejpeg($dst_img,$filename); 
    if (!strcmp("gif",$ext)) 
    imagegif($dst_img,$filename); 
    //destroys source and destination images. 
    imagedestroy($dst_img); 
    imagedestroy($src_img); 
} 
// This function reads the extension of the file. 
// It is used to determine if the file is an image by checking the extension. 
function getExtension($str) 
{ 
$i = strrpos($str,"."); 
if (!$i) { return ""; } 
$l = strlen($str) - $i; 
$ext = substr($str,$i+1,$l); 
return $ext; 
} 
// This variable is used as a flag. The value is initialized with 0 (meaning no error found) 
//and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded. 
$errors=0; 
// if it is not empty 
for($i=0;$i<count($_FILES['establishment_image']["name"]);$i++) 
{ 
// get the original name of the file from the clients machine 
$filenames = stripslashes($_FILES['establishment_image']['name'][$i]); 

// get the extension of the file in a lower case format 
$extensions = getExtension($filenames); 
$extensions = strtolower($extensions); 
// if it is not a known extension, we will suppose it is an error, print an error message 
//and will not upload the file, otherwise we continue 
if (($extensions != "jpg") && ($extensions != "jpeg") && ($extensions != "png") && ($extensions != "gif")) 
{ 
$warning = ("File extension of an image(s) not allowed"); 
header("location:establishment_add.php?warning=$warning"); 
$errors=1; 
exit(); 
} 
else 
{ 
// get the size of the image in bytes 
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server 
$size=getimagesize($_FILES['establishment_image']['tmp_name'][$i]); 
$sizekb=filesize($_FILES['establishment_image']['tmp_name'][$i]); 

//compare the size with the maxim size we defined and print error if bigger 
if ($sizekb > MAX_SIZE*1024) 
{ 
$warning = ("Images have exceeded the size limit of 10MB"); 
header("location:establishment_add.php?warning=$warning"); 
$errors=1; 
exit(); 
} 
$rand= rand(0, 100000); 
//we will give an unique name, for example a random number 
$image_name=$rand.'.'.$extension; 
//the new name will be containing the full path where the image will be stored (images folder) 
$consname="C:/wamp/www/NNL/Administrator/Establishment_Images/".$image_name; //change the image/ section to where you would like the original image to be stored 
$consname2="C:/wamp/www/NNL/Administrator/Establishment_Images/Thumbs/".$image_name; 
//change the image/thumb to where you would like to store the new created thumbnail of the image 
$copied = copy($_FILES['establishment_image']['tmp_name'][$i], $consname); 
$copied = copy($_FILES['establishment_image']['tmp_name'][$i], $consname2); 
//localhost calling of images 
$img_large="../Establishment_Images/".$image_name; //change the image/ section to where you would like the original image to be stored 
$img_thumb="../Establishment_Images/Thumbs/".$image_name; 
//we verify if the image has been uploaded, and print error instead 
if (!$copied) { 
$warning = ("Unable to upload image file"); 
header("location:establishment_add.php?warning=$warning"); 
$errors=1; 
exit(); 
}else{ 
// the new large image will be placed in Images/ folder 
$imagelarge_name=$consname ; 
// call the function that will create the thumbnail. The function will get as parameters 
// the image name, the thumbnail name and the width and height desired for the thumbnail 
$imagelarge=make_largeimage($consname,$imagelarge_name,LARGE_WIDTH,LARGE_HEIGHT); 
// the new thumbnail image will be placed in Images/Thumbs/ folder 
$thumb_name=$consname2 ; 
// call the function that will create the thumbnail. The function will get as parameters 
// the image name, the thumbnail name and the width and height desired for the thumbnail 
$thumb=make_thumb($consname,$thumb_name,WIDTH,HEIGHT); 
} 
} 
} 
?> 
<?php 
//If no errors registered, redirect page 
if(isset($_POST['Submit']) && !$errors) 
{ 
//insert into database 
$query2 = "INSERT INTO establishment(establishment_name, 
          establishment_short_description, 
          establishment_long_description, 
          establishment_address, 
          establishment_telephone, 
          establishment_contact, 
          establishment_email, 
          location_id, 
          establishment_pricing,       
          establishment_url_link, 
          establishment_mainphoto_url, 
          establishment_thumb_url) 
          VALUES 
          ('$establishment_name', 
          '$short_description', 
          '$long_description', 
          '$establishment_address', 
          '$establishment_telephone', 
          '$establishment_contact', 
          '$establishment_email', 
          '$location', 
          '$establishment_pricing', 
          '$url_link',        
          '$img_large[0]', 
          '$img_thumb[0]')";       
//Execute query 
$qry_result2 = mysql_query($query2) or die(mysql_error()); 

header("Location: " . $establishmentAddSuccess); 
} 
else 
{ 
    $establishment_msg = ("Unable to add establishment"); 
    header("location:establishment_add.php?establishment_msg=$establishment_msg"); 
    exit(); 
}  
?> 

Теперь это работало отлично для одного загрузки изображения, но не работает. Я знаю, что мне нужно внести изменения из строки;

for($i=0;$i<count($_FILES['establishment_image']["name"]);$i++) 
{ 

Как сделать эту форму возможным для загрузки нескольких изображений. Буду признателен за любую помощь.

+0

после всего, что вам просто нужно знать, как загрузить несколько изображений? сначала поднимите свои методы поиска на этом сайте. – Yehonatan

+0

@ Yehonatan. Мы не все эксперты здесь. Из прошлого опыта на этом сайте я видел это, если вы не поняли и просто задали общий вопрос: например, как вы загружаете несколько изображений в PHP? вы не можете получить то, что ищете. Мне нравится показывать код, чтобы люди могли точно видеть, что я пытаюсь сделать. Например, для Марка Б. –

+0

Если вы посмотрите в верхнем правом углу этой страницы, вы увидите окно поиска. Введите «загрузить несколько изображений в PHP» и нажмите «Возврат». Проверьте это, 115 страниц результатов. Если это не поможет, продолжайте и напишите подробные вопросы. – Yehonatan

ответ

2

Вы можете использовать обозначение массива в PHP, как вы бы в обычных полях формы:

Pic 1: <input type="file" name="establishment_image[]" /> 
Pic 2: <input type="file" name="establishment_image[]" /> 

Однако обработка файлов материал в PHP будет обрабатывать его немного иначе, чем вы ожидали бы на стороне сервера:

$_FILES = array(
    'establishment_image' => array(
      'name' => array(
       0 => 'name of Pic 1 file', 
       1 => 'name of Pic 2 file' 
     ), 
      'error' => array(
       0 => error code for pic1 upload, 
       1 => error code for pic2 upload 
     etc... 
); 

это достаточно легко обрабатывать, хотя:

foreach(array_keys($_FILES['establishment_image']['name']) as $idx) { 
    .... 
} 

другой вариант чтобы каждый файл вводил уникальное имя и работал с этим сервером. Если жесткий код числовой «суб ключ» в каждом:

<input type="file" name="establishment_image_1" /> 
<input type="file" name="establishment_image_2" /> 

Тогда вы можете просто сделать

for ($i = 1; $i <= 5; $i++) { 
    echo "Name of file is ", $_FILES["establishment_image_$i"]['name']; 
    ... 
} 
+0

Большое спасибо за ваш быстрый ответ. Я попробую вариант 2. Дайте вам знать, как это происходит –

0

загружать изображения страниц много повреждения головного мозга, если учесть, причуды Imagick, UI шаблоны для страницы загрузки, разрешения и т. д. Мой ярлык в ситуации, когда внутренний администратор делает страницу, - Gallery.

Администратор затем использует галерею для загрузки, изменения размера, обрезки и т. Д. По существу, основы плюс «дополнительные», которые могут потребовать мои клиенты, но я не могу оправдать зарядку достаточно, чтобы сделать с нуля. С пользовательской стороны я запрашиваю галерею из базы данных MySQL и соглашаюсь любым способом, как мне хотелось бы, обычно через яркий интерфейс JQuery, который я подстраивал. Но это может быть что угодно ... и я мог бы даже использовать front-end для галереи.

Умственно, пользователю не становится понятнее. Я могу запустить его и запустить менее чем за 2 часа. И поскольку изображения хранятся статически в файловой системе, больше нет дополнительной нагрузки, чем ожидалось.

Если вы решите пойти в одиночку, есть, конечно, более одного способа атаковать этот вызов. Я бы рекомендовал проверить этот популярный пост: How can I upload files asynchronously?

Смежные вопросы