Jump to content

Please help uploading images


lingo5

Recommended Posts

Hi,

I have this upload script that uploads a file and writes path to DB:

 

<?php

$uploadDir = '../uploads/';

if(isset($_POST['upload']))
{
foreach ($_FILES as $file)
{
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];

if($fileName==""){

$filePath = '../img/none.jpg';
}
else{

$filePath = $uploadDir . $fileName;
}

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$fileinsert[]=$filePath;
}
?>

 

this works fine for a single image, but I eed to upload 2 images with a single submission....any ideas how to do this?

Thanks

Link to comment
Share on other sites


<form action="<?php $PHP_SELF;?>" method="post" enctype="multipart/form-data">
  <br />
  <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0" class="CP_LineBottom">
    <tr valign="baseline">
      <td height="23" colspan="2" align="right" nowrap="nowrap"><div align="right"><span class="CP_LineTop"> </span>
        <div align="right">
          <div align="left" class="CP_TituloSecciones">Insertar Imagen</div>
        </div>
        <span class="CP_LineTop"></span><span class="CP_LineTop"> </span></div></td>
    </tr>
    </table>
  <br />
  <table width="85%" border="0" align="center" cellpadding="1" cellspacing="0">
    <tr>
      <td bgcolor="#85765F"><table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td bgcolor="#FFFFFF"><table width="100%" border="0" align="center" cellpadding="15" cellspacing="1">
            <tr valign="baseline">
              <td align="right" valign="top" nowrap="nowrap" bgcolor="#85765F" class="CP_TableHeaders"> </td>
              <td bgcolor="#ECEACE"><select name="id_categoria" id="id_categoria" title="<?php echo $row_categorias_list_RS['categoria_nombre']; ?>">
                <option value="Seleccione una categoría">Seleccione una categoría</option>
                <?php
do {  
?>
                <option value="<?php echo $row_categorias_list_RS['id_categoria']?>"><?php echo $row_categorias_list_RS['categoria_esp']?></option>
                <?php
} while ($row_categorias_list_RS = mysql_fetch_assoc($categorias_list_RS));
  $rows = mysql_num_rows($categorias_list_RS);
  if($rows > 0) {
      mysql_data_seek($categorias_list_RS, 0);
  $row_categorias_list_RS = mysql_fetch_assoc($categorias_list_RS);
  }
?>
              </select></td>
            </tr>
            <tr valign="baseline">
              <td width="17%" align="right" valign="top" nowrap="nowrap" bgcolor="#85765F" class="CP_TableHeaders">Antes:</td>
              <td width="83%" bgcolor="#ECEACE"><br />
                <br />
  <input name="imagen_before" type="file" id="imagen_before" />
                <br />
                <br />
                <label>
                  <textarea name="imagen_antes_txt_esp" cols="50" rows="5" class="CP_loginFormFields" id="imagen_antes_txt_esp">Descripción de la imagen español</textarea>
                  <br />
                  <br />
                  <textarea name="imagen_antes_txt_eng" cols="50" rows="5" class="CP_loginFormFields" id="imagen_antes_txt_eng">Descripción de la imagen español</textarea>
<br />
                  <br />
                </label></td>
            </tr>
            <tr valign="baseline">
              <td align="right" valign="top" nowrap="nowrap" bgcolor="#85765F" class="CP_TableHeaders">Después:</td>
              <td bgcolor="#ECEACE"><input name="imagen_after" type="file" id="imagen_after" />
                <br />
                <br />
                <label>
                  <textarea name="imagen_despues_txt_esp" cols="50" rows="5" class="CP_loginFormFields" id="imagen_despues_txt_esp">Descripción de la imagen español</textarea>
                  <br />
                  <br />
                  <textarea name="imagen_despues_txt_eng" cols="50" rows="5" class="CP_loginFormFields" id="imagen_despues_txt_eng">Descripción de la imagen español</textarea>
<br />
                </label></td>
            </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>
  </table>
  <br />
  <table width="90%" border="0" align="center" cellpadding="4" cellspacing="0" class="CP_LineTopBottomMarron">
    <tr>
      <td width="84%" height="38" valign="middle"><div align="left"><a href="javascript:history.go(-1)" class="CP_welcomeText"><< volver atrás</a></div></td>
      <td width="16%" valign="middle" nowrap="nowrap"><div align="right">
        <input name="upload" type="submit" class="box" id="upload" value="insertar imagen">
      </div></td>
      </tr>
  </table>
                    <br />
                    </form>

Link to comment
Share on other sites

OK, I have tried this:

 

tis is my form:

<?php
<form action="<?php $PHP_SELF;?>" method="post" enctype="multipart/form-data">
  <br />
  <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0" class="CP_LineBottom">
    <tr valign="baseline">
      <td height="23" colspan="2" align="right" nowrap="nowrap"><div align="right"><span class="CP_LineTop"> </span>
        <div align="right">
          <div align="left" class="CP_TituloSecciones">Insertar Imagen</div>
        </div>
        <span class="CP_LineTop"></span><span class="CP_LineTop"> </span></div></td>
    </tr>
    </table>
  <br />
  <table width="85%" border="0" align="center" cellpadding="1" cellspacing="0">
    <tr>
      <td bgcolor="#85765F"><table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td bgcolor="#FFFFFF"><table width="100%" border="0" align="center" cellpadding="15" cellspacing="1">
            <tr valign="baseline">
              <td align="right" valign="top" nowrap="nowrap" bgcolor="#85765F" class="CP_TableHeaders"> </td>
              <td bgcolor="#ECEACE"><select name="id_categoria" id="id_categoria" title="<?php echo $row_categorias_list_RS['categoria_nombre']; ?>">
                <option value="Seleccione una categoría">Seleccione una categoría</option>
                <?php
do {  
?>
                <option value="<?php echo $row_categorias_list_RS['id_categoria']?>"><?php echo $row_categorias_list_RS['categoria_esp']?></option>
                <?php
} while ($row_categorias_list_RS = mysql_fetch_assoc($categorias_list_RS));
  $rows = mysql_num_rows($categorias_list_RS);
  if($rows > 0) {
      mysql_data_seek($categorias_list_RS, 0);
  $row_categorias_list_RS = mysql_fetch_assoc($categorias_list_RS);
  }
?>
              </select></td>
            </tr>
            <tr valign="baseline">
              <td width="17%" align="right" valign="top" nowrap="nowrap" bgcolor="#85765F" class="CP_TableHeaders">Antes:</td>
              <td width="83%" bgcolor="#ECEACE"><br />
                <br />
                <input name="userfile[]" type="file" id="userfile[]" />
                <br />
                <br />
                <label>
                  <textarea name="imagen_antes_txt_esp" cols="50" rows="5" class="CP_loginFormFields" id="imagen_antes_txt_esp">Descripción de la imagen español</textarea>
                  <br />
                  <br />
                  <textarea name="imagen_antes_txt_eng" cols="50" rows="5" class="CP_loginFormFields" id="imagen_antes_txt_eng">Descripción de la imagen español</textarea>
<br />
                  <br />
                </label></td>
            </tr>
            <tr valign="baseline">
              <td align="right" valign="top" nowrap="nowrap" bgcolor="#85765F" class="CP_TableHeaders">Después:</td>
              <td bgcolor="#ECEACE"><input name="userfile[]" type="file" id="userfile[]" />
                <br />
                <br />
                <label>
                  <textarea name="imagen_despues_txt_esp" cols="50" rows="5" class="CP_loginFormFields" id="imagen_despues_txt_esp">Descripción de la imagen español</textarea>
                  <br />
                  <br />
                  <textarea name="imagen_despues_txt_eng" cols="50" rows="5" class="CP_loginFormFields" id="imagen_despues_txt_eng">Descripción de la imagen español</textarea>
<br />
                </label></td>
            </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>
  </table>
  <br />
  <table width="90%" border="0" align="center" cellpadding="4" cellspacing="0" class="CP_LineTopBottomMarron">
    <tr>
      <td width="84%" height="38" valign="middle"><div align="left"><a href="javascript:history.go(-1)" class="CP_welcomeText"><< volver atrás</a></div></td>
      <td width="16%" valign="middle" nowrap="nowrap"><div align="right">
        <input name="upload" type="submit" class="box" id="upload" value="insertar imagen">
      </div></td>
      </tr>
  </table>
                    <br />
                    </form>?>

 

and this is my upload script and the query that saves the path to the DB:

 

$uploadDir = '../uploads/';

if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

if($fileName==""){

$filePath = '../uploads/img/none.jpg';
}
else{

$filePath = $uploadDir . $fileName;
}

$filePath = str_replace(" ", "_", $filePath);
$result = move_uploaded_file($tmpName, $filePath);

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
} 

$categoria = $_POST["id_categoria"];
$textoantesesp = $_POST["imagen_antes_txt_esp"];
$textodespuesesp = $_POST["imagen_despues_txt_esp"];
$textoanteseng = $_POST["imagen_antes_txt_eng"];
$textodespueseng = $_POST["imagen_despues_txt_eng"];


$query = "INSERT INTO carmansa.t_imagenes (id_categoria,imagen_antes_txt_esp,imagen_despues_txt_esp,imagen_antes_txt_eng,imagen_despues_txt_eng,imagen_before,imagen_after) ".
"VALUES ('$categoria','$textoantesesp','$textodespuesesp','$textoanteseng','$textodespueseng','$filePath','$filePath')";

mysql_query($query) or die('Error, query failed : ' . mysql_error()); 



header("Location: PC_images_inserted.php"); 
}
?>

 

but the images are not uploaded.

Any help will be much appreciated

Link to comment
Share on other sites

On your form, have this for all the file uploads

 

<label for="image[]">LABEL HERE</label><input type="file" name="image[]" id="image[]" />

 

Then, use this script inside your "if submitted" if statement to upload your files

 

<?php

//Declare the  variables for the first image
$image1 = $_FILES['image']['name'][0];
$tmpImage1 =  $_FILES['image']['tmp_name'][0];
$imageError1 = $_FILES['image']['error'][0];

//Declare the  variables for the second image
$image2 = $_FILES['image']['name'][1];
$tmpImage2 =  $_FILES['image']['tmp_name'][1];
$imageError2 = $_FILES['image']['error'][1];

//For both the images
for ($i = 1; $i <= 2; $i++) {

	//If there is a file
	if(${image.$i} != '' && ${tmpImage.$i} != ''){

		//If there is an error with the file uploaded
		if(${imageError.$i} > 0) {

			//Provide an error message


		}else{

			//encode the image name for the www
			urlencode(${image.$i});

                                //If magic quotes are off
                                if(!get_magic_quotes_gpc()) {

                                    
                                    ${image.$i} = addslashes(${image.$i});
                                    $target = addslashes($target);

                                 }

                                 //Declare the target location and move the file there
                                $target = $target . ${image.$i};
			$target = $target . basename(${image.$i});	
			move_uploaded_file(${tmpImage.$i}, $target);
		        
		}

	}else{

                      //If there is an error with the file uploaded
		if(${imageError.$i} > 0) {

			//Provide an error message


		}else{

                                //Declare the target
			$target = '../img/none.jpg';

                        }

                //Add the target to the fileinsert array
                $fileinsert[]=$target;

}
?>
[code]

Link to comment
Share on other sites

Hi lingo, I missed a line out. This:

 

<?php 
//Declare the target location and move the file there
$target = $target . ${image.$i};
$target = $target . basename(${image.$i});	
move_uploaded_file(${tmpImage.$i}, $target);
?>

 

Needs to be this:

 

<?php 
//Declare the target location and move the file there
$target = 'uploads/';                                                     //Declare your upload path here
$target = $target . ${image.$i};
$target = $target . basename(${image.$i});	
move_uploaded_file(${tmpImage.$i}, $target);
?>

 

And your new query should be inside the for loop beneath where you add to the array and look like this:

<?php
$query = "INSERT INTO carmansa.t_imagenes (id_categoria,imagen_antes_txt_esp,imagen_despues_txt_esp,imagen_antes_txt_eng,imagen_despues_txt_eng,imagen_before,imagen_after) ".
"VALUES ('$categoria','$textoantesesp','$textodespuesesp','$textoanteseng','$textodespueseng','$target','$target')";
?>

 

I'm not sure why you need to enter the file path in twice though, is that a mistake?

Link to comment
Share on other sites

I add the $target twicw one for each of the images (image_before. image_after)...but I'm not sure this is the way to go.

Also, how do I trigger the upload?...would  this be correct?

 

<?php
if(isset($_POST['upload']))
{
//Declare the variables for the first image
$image1 = $_FILES['image']['name'][0];
$tmpImage1 = $_FILES['image']['tmp_name'][0];
$imageError1 = $_FILES['image']['error'][0];

//Declare the variables for the second image
$image2 = $_FILES['image']['name'][1];
$tmpImage2 = $_FILES['image']['tmp_name'][1];
$imageError2 = $_FILES['image']['error'][1];

//For both the images
for ($i = 1; $i <= 2; $i++) {

//If there is a file
if(${image.$i} != '' && ${tmpImage.$i} != ''){

//If there is an error with the file uploaded
if(${imageError.$i} > 0) {

//Provide an error message


}else{

//encode the image name for the www
urlencode(${image.$i});

//If magic quotes are off
if(!get_magic_quotes_gpc()) {


${image.$i} = addslashes(${image.$i});
$target = addslashes($target);

}

//Declare the target location and move the file there
$target = 'uploads/'; //Declare your upload path here
$target = $target . ${image.$i};
$target = $target . basename(${image.$i}); 
move_uploaded_file(${tmpImage.$i}, $target);

}

}else{

//If there is an error with the file uploaded
if(${imageError.$i} > 0) {

//Provide an error message


}else{

//Declare the target
$target = '../img/none.jpg';

}

//Add the target to the fileinsert array
$fileinsert[]=$target;

}
?>

Link to comment
Share on other sites

OK, got it working, but instead it's adding 2 records to the DB. I only need to create one with 2 images. Here's the code

 

<?php

//Declare the variables for the first image
$image1 = $_FILES['image']['name'][0];
$tmpImage1 = $_FILES['image']['tmp_name'][0];
$imageError1 = $_FILES['image']['error'][0];

//Declare the variables for the second image
$image2 = $_FILES['image']['name'][1];
$tmpImage2 = $_FILES['image']['tmp_name'][1];
$imageError2 = $_FILES['image']['error'][1];


if(isset($_POST['upload']))

//For both the images
for ($i = 1; $i <= 2; $i++) {

//If there is a file
if(${image.$i} != '' && ${tmpImage.$i} != ''){

//If there is an error with the file uploaded
if(${imageError.$i} > 0) {

//Provide an error message


}else{

//encode the image name for the www
urlencode(${image.$i});

//If magic quotes are off
if(!get_magic_quotes_gpc()) {


${image.$i} = addslashes(${image.$i});
$target = addslashes($target);

}

//Declare the target location and move the file there
$target = 'uploads/'; //Declare your upload path here
$target = $target . ${image.$i};
$target = $target . basename(${image.$i}); 
move_uploaded_file(${tmpImage.$i}, $target);

}

}else{

//If there is an error with the file uploaded
if(${imageError.$i} > 0) {

//Provide an error message


}else{

//Declare the target
$target = '../img/none.jpg';

}

//Add the target to the fileinsert array
$fileinsert[]=$target;

}

$categoria = $_POST["id_categoria"];
$textoantesesp = $_POST["imagen_antes_txt_esp"];
$textodespuesesp = $_POST["imagen_despues_txt_esp"];
$textoanteseng = $_POST["imagen_antes_txt_eng"];
$textodespueseng = $_POST["imagen_despues_txt_eng"];

$query = "INSERT INTO carmansa.t_imagenes (id_categoria,imagen_antes_txt_esp,imagen_despues_txt_esp,imagen_antes_txt_eng,imagen_despues_txt_eng,imagen_before,imagen_after) ".
"VALUES ('$categoria','$textoantesesp','$textodespuesesp','$textoanteseng','$textodespueseng','$image1','$image2')";

mysql_query($query) or die('Error, query failed : ' . mysql_error()); 

//echo "<br>Files uploaded<br>";

header("Location: PC_images_inserted.php"); 
}
?>

Link to comment
Share on other sites

This is my code with query included...still not doing what I want..

 

<?php

//Declare the variables for the first image
$image1 = $_FILES['image']['name'][0];
$tmpImage1 = $_FILES['image']['tmp_name'][0];
$imageError1 = $_FILES['image']['error'][0];

//Declare the variables for the second image
$image2 = $_FILES['image']['name'][1];
$tmpImage2 = $_FILES['image']['tmp_name'][1];
$imageError2 = $_FILES['image']['error'][1];


if(isset($_POST['upload']))

//For both the images
for ($i = 1; $i <= 2; $i++) {

//If there is a file
if(${image.$i} != '' && ${tmpImage.$i} != ''){

//If there is an error with the file uploaded
if(${imageError.$i} > 0) {

//Provide an error message


}else{

//encode the image name for the www
urlencode(${image.$i});

//If magic quotes are off
if(!get_magic_quotes_gpc()) {


${image.$i} = addslashes(${image.$i});
$target = addslashes($target);

}

//Declare the target location and move the file there
$target = 'uploads/'; //Declare your upload path here
$target = $target . ${image.$i};
$target = $target . basename(${image.$i}); 
move_uploaded_file(${tmpImage.$i}, $target);

}

}else{

//If there is an error with the file uploaded
if(${imageError.$i} > 0) {

//Provide an error message


}else{

//Declare the target
$target = '../img/none.jpg';

}

//Add the target to the fileinsert array
$fileinsert[]=$target;

}

$categoria = $_POST["id_categoria"];
$textoantesesp = $_POST["imagen_antes_txt_esp"];
$textodespuesesp = $_POST["imagen_despues_txt_esp"];
$textoanteseng = $_POST["imagen_antes_txt_eng"];
$textodespueseng = $_POST["imagen_despues_txt_eng"];

$query = "INSERT INTO carmansa.t_imagenes (id_categoria,imagen_antes_txt_esp,imagen_despues_txt_esp,imagen_antes_txt_eng,imagen_despues_txt_eng,imagen_before,imagen_after) ".
"VALUES ('$categoria','$textoantesesp','$textodespuesesp','$textoanteseng','$textodespueseng','$image1','$image2')";

mysql_query($query) or die('Error, query failed : ' . mysql_error()); 

//echo "<br>Files uploaded<br>";

header("Location: PC_images_inserted.php"); 
}
?>

Link to comment
Share on other sites

move:

<?php
$query = "INSERT INTO carmansa.t_imagenes (id_categoria,imagen_antes_txt_esp,imagen_despues_txt_esp,imagen_antes_txt_eng,imagen_despues_txt_eng,imagen_before,imagen_after) ".
"VALUES ('$categoria','$textoantesesp','$textodespuesesp','$textoanteseng','$textodespueseng','$image1','$image2')";

mysql_query($query) or die('Error, query failed : ' . mysql_error()); 
?>

 

to after:

 

<?php
header("Location: PC_images_inserted.php"); 
}
?>

 

The code is currently inside the for loop, so it will insert records twice. I'd recommend coding on notepad++ or another program with similar syntax highlighting, as it highlights your curly braces and shows what is contained inside loops and if statements etc.

Link to comment
Share on other sites

FYI - variable variables are three times slower than using an array and you have a lot of variable variable references in your code.

 

The $_FILES['image'] or $_FILES['userfile'] (in the original code) structure is already an array of arrays. All you need to do is use a simple foreach loop (see Example #3 at this link - http://us3.php.net/manual/en/features.file-upload.post-method.php ) to iterate over the uploaded file information.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.