Foros del Web » Programando para Internet » PHP »

ayuda , bucle

Estas en el tema de ayuda , bucle en el foro de PHP en Foros del Web. Hola que tal, les comento... estaba haciendo un código el cual consta de 5 partes las 3 primeras son una copia entre sí solo que ...
  #1 (permalink)  
Antiguo 23/11/2009, 14:15
Avatar de mauro770  
Fecha de Ingreso: mayo-2009
Mensajes: 109
Antigüedad: 14 años, 11 meses
Puntos: 1
ayuda , bucle

Hola que tal, les comento... estaba haciendo un código el cual consta de 5 partes
las 3 primeras son una copia entre sí solo que trabajan con un contenido del array MINIATURA[],(una trabaja con MINIATURA[0],otra con MINIATURA[1] y la otra con MINIATURA[2]) la 4 parte es una función y la 5ta el código XHTML.
Las 3 primeras lo que haces es verificar que las propiedades de las fotos pasadas por el input file sean las correctas, luego las pasa por la función escalar() la cual las redimensiona y luego sigue por su curso normal, las renombra y las mueve de la carpeta que están a otra.
lo que estoy buscando es poder hacer un bucle con las 3 primeras partes para que ese codigo no se repita ( creo que consumiria muchos recursos ).
conviene hacer un bucle, dejarlo asi nomas o conviene adaptarlo como otra funcion.

alguien sabe donde puedo obtener informacion para hacer esto asi de paso leo un poco y aprendo?

aqui dejo el codigo:
Código PHP:
<?php    
$dirbase 
'Directorio interno';
         if (
$HTTP_POST_FILES['MINIATURA']['name'][0] != '') {
            
$nombre_archivo $HTTP_POST_FILES['MINIATURA']['name'][0];
            
$tipo_archivo $HTTP_POST_FILES['MINIATURA']['type'][0];
            
$tamano_archivo $HTTP_POST_FILES['MINIATURA']['size'][0];
            
$archivo pathinfo($nombre_archivo);
            
$archivo $archivo['filename'];
            
//compruebo si las características del archivo son las que deseo
            
$url_mini_no_valida '';
            
$sw '';
            if (
strpos($tipo_archivo"jpg")) $sw $tipo_archivo;
            if (
strpos($tipo_archivo"jpG")) $sw $tipo_archivo;
            if (
strpos($tipo_archivo"jpeg")) $sw $tipo_archivo;
            if (
strpos($tipo_archivo"png")) $sw $tipo_archivo;
            if (
strpos($tipo_archivo"gif")) $sw $tipo_archivo;
            if (
$sw == '') {
               
$msj 'Extensión de archivo no válida: '.$tipo_archivo;
               
$tpl->assign($data);
               
//$tpl->assign('ruta_miniatura', 'http://localhost/phpld22/miniaturas/');
               
$content $tpl->fetch('admin/dir_links_edit.tpl');
               
$tpl->assign('content'$content);
               
//Clean whitespace
               
$tpl->load_filter('output''trimwhitespace');
               
//Make output
               
echo $tpl->fetch('admin/main.tpl');   
               die();
            } else {
            
               if (
move_uploaded_file($HTTP_POST_FILES['MINIATURA']['tmp_name'][0], $dirbase.'temp/'.$nombre_archivo)) {
               echo 
'<script>alert("moveuploadfile")</script>';
                  if (
file_exists($dirbase.'miniaturas/_'.$archivo.'.jpg')) {
                     if (!
unlink($dirbase.'miniaturas/_'.$archivo.'.jpg')) {
                        echo 
"fallo al borrar miniatura anterior";
                        die();
                     }
                  }
                  
$rere getimagesize($dirbase.'temp/'.$nombre_archivo);
                  
escalar($dirbase.'temp/'.$nombre_archivo300300,1);
                  if (!
unlink($dirbase.'temp/'.$nombre_archivo)) {
                     echo 
"fallo al borrar imagen original temporal";
                     
$error 'problema en !unlink<br/>';
                     die();
                  }
                  
rename ($dirbase.'temp/_'.$archivo.'.jpg'$dirbase.'miniaturas/_'.$archivo.'.jpg');
                  
$data['MINIATURA'] = '_'.$archivo.'.jpg';
               } else {
                  echo 
"Ocurrió algún error al subir el fichero. No pudo guardarse.";
               }
            }
         }   
         


             if (
$HTTP_POST_FILES['MINIATURA']['name'][1] != '') {
  
// AHORA TODO LO MISMO Q LO PRIMERO SOLO QUE USANDO   
 //$HTTP_POST_FILES['MINIATURA'][1]           
}
if (
$HTTP_POST_FILES['MINIATURA']['name'][2] != '') {
  
// AHORA TODO LO MISMO Q LO PRIMERO SOLO QUE USANDO   
 //$HTTP_POST_FILES['MINIATURA'][2]           
}
 
?>
<?php 

function escalar($imagen,$ancho,$altura,$nro) {
   
$prefijo_thumb "_";
   
$camino_nombre=explode("/",$imagen);
   
$nombre=end($camino_nombre);
   
$camino=substr($imagen,0,strlen($imagen)-strlen($nombre));
   
$archivo pathinfo($imagen);
   
$extension $archivo['extension'];
   
$nombre_archivo $archivo['filename'];
   
   if (!
file_exists($camino.$prefijo_thumb.$nombre)) {
      if ((
$extension == 'jpeg') || ($extension == 'jpg')) {
         
$img = @imagecreatefromjpeg($camino.$nombre);
      } elseif (
$extension == 'png') {
         
$img = @imagecreatefrompng($camino.$nombre);
      } elseif (
$extension == 'gif') {
         
$img = @imagecreatefromgif($camino.$nombre);
      }
       if (!
$img) { /* Comprobar si ha fallado */
      
         
$img = @imagecreatefromjpeg($dirbase."temp/universo.jpg");   
         
$datos getimagesize($dirbase."temp/universo.jpg") or die("Problemas con $camino$nombre<br>");
         
$anchura $ancho;
         
$thumb imagecreatetruecolor($anchura,$altura);
         
imagecopyresampled ($thumb$img0000$anchura$altura$datos[0], $datos[1]); // calidad
         //imagecopyresized ($thumb, $img, 0, 0, 0, 0, $anchura, $altura, $datos[0], $datos[1]); // rapidez
         
imagejpeg($thumb,$camino.$prefijo_thumb.$nombre);
         
       } else {   
         
$datos getimagesize($camino.$nombre) or die("Problemas con $camino$nombre<br>");
         
$ratio = ($datos[0] / $ancho);
         
$ancho_final 300;
         
$alto_final 230;
         
$escalada imagecreatetruecolor($ancho_final,$alto_final);
         
imagecopyresized($escalada$img0000$ancho_final$alto_final$datos[0], $datos[1]); // calidad
         //imagecopyresized ($thumb, $img, 0, 0, 0, 0, $anchura, $altura, $datos[0], $datos[1]); // rapidez
         
         
         
$thumb imagecreatetruecolor($ancho_final,$alto_final);
         
imagecopyresized ($thumb$escalada0000$ancho$altura$ancho_final$altura); // calidad
         
$ruta_marca 'marca_de_agua.png';
         
$watermark imagecreatefrompng($ruta_marca);
         
imagecopymerge($thumb$watermark15000,15$ancho_final30);
         if(
$nro == 1){
     
$_POST['url0'] = 'http://www.minicio.com.ar/miniaturas/'.$prefijo_thumb.$nombre_archivo.'.jpg';
     }
     if(
$nro == 2){
     
$_POST['url1'] = 'http://www.minicio.com.ar/miniaturas/'.$prefijo_thumb.$nombre_archivo.'.jpg';
     }
     if(
$nro == 3){
     
$_POST['url2'] = 'http://www.minicio.com.ar/miniaturas/'.$prefijo_thumb.$nombre_archivo.'.jpg';
     }
         
imagejpeg($thumb,$camino.$prefijo_thumb.$nombre_archivo.'.jpg');
      }
   }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin t&iacute;tulo</title>
</head>

<body>
<?php if(isset($_POST)){ echo $rere[0].'<br/>'.$rere[1];} ?>
        
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="">
  <label>
  <input type="file" name="MINIATURA[]" id="MINIATURA" />
  <br />
  </label>
  <label>
  <input type="file" name="MINIATURA[]" id="MINIATURA2" />
  <br />
  </label>
  <label>
  <input type="file" name="MINIATURA[]" id="MINIATURA2" />
  </label>
  <p>
    <label>
    <input type="submit" name="enviar" id="enviar" value="Enviar" />
    </label>
  </p>
</form>
<table width="952" height="312" border="1">
  <tr>
    <td height="33" colspan="4">&nbsp;</td>
  </tr>
  <tr>
    <td width="310" height="228"><img src="<?php echo $_POST['url0']; ?>"/></td>
    <td width="310"><img src="<?php echo $_POST['url1']; ?>"/></td>
    <td width="310"><img src="<?php echo $_POST['url2']; ?>"/></td>
  </tr>
</table>
</td>
</body>
</html>

Saludos

Última edición por mauro770; 23/11/2009 a las 14:36
  #2 (permalink)  
Antiguo 23/11/2009, 15:50
Avatar de mauro770  
Fecha de Ingreso: mayo-2009
Mensajes: 109
Antigüedad: 14 años, 11 meses
Puntos: 1
De acuerdo Respuesta: ayuda , bucle

jeje resuelto pongo la solucion por si a alguien le sirve :
Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin t&iacute;tulo</title>
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <label></label>
  <p>
    <label>
    <input type="file" name="campo[]" id="campo[]" />
    </label>
  </p>
  <p>
    <input type="file" name="campo[]" id="campo[]" />
  </p>
  <p>
    <input type="file" name="campo[]" id="campo[]" />
</p>
  <p>
    <label>
    <input type="submit" name="enviar" id="enviar" value="Enviar" />
    </label>
  </p>
  <p>&nbsp;</p>
</form>
<?php
// aqui esta el secreto (en el bucle) 
// primero definimos $i como valor "0" por que el primer arreglo tiene como denominador "0" y luego le pasamos 
//el parametro en el cual debe frenar en este caso 2 que es el 3er campo file con denominacion "2" y luego le 
//pedimos al bucle que $i sea aumentado en 1 cada vez que se realice el bucle , entonces recorrera
//$_FILES['campo']['name'][0] --> 1er campo file
//$_FILES['campo']['name'][1] --> 2do campo file
//$_FILES['campo']['name'][2] --> 3ercampo file
for( $i $i <= $i ++) 
echo 
$_FILES['campo']['name'][$i].'<br>'
?>
</body>
</html>
hice el ejemplo solo haciendo un eco del nombre del archivo para no hacerlo tan extenso . espero q le sirve de ayuda a alguien.

cuando no alles la solucion ... solo sigue buscando


SI ALGUIEN TIENE UNA IDEA CON LA CUAL PODRIA IR MEJOR SIEMPRE ES BIENVENIDA :D
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:10.