Páginas (2): 1 2   
HSSWebs   3 Sep, 2012, 6:09 pm
#1
Bueno me pille este código bastante simple para subir imágenes:

<?php
$status = "";
if ($_POST["action"] == "upload")
{
	// obtenemos los datos del archivo
	$tamano = $_FILES["archivo"]['size'];
	$tipo = $_FILES["archivo"]['type'];
	$archivo = $_FILES["archivo"]['name'];
	$prefijo = substr(md5(uniqid(rand())),0,6);
	if ($archivo != "")
	{
		if ($tipo == "image/gif" || $tipo == "image/jpeg" || $tipo == "image/jpg")
		{
			$destino = "uploads/".$prefijo."_".$archivo;
			if (copy($_FILES['archivo']['tmp_name'],$destino))
			{
				$status = "Archivo subido: <b>".$archivo."</b>";
			}
			else
			{
				$status = "Error al subir el archivo";
			}
		}
		else
		{
			$status = "Error: solo se permite GIF o JPG";
		}
	}
	else
	{
		$status = "Error al subir archivo";
	}
}
?>

Aquí el formulario de subida:

<form action="upload.php" method="post" enctype="multipart/form-data">
<td class="text">
<input name="archivo" type="file" class="casilla" id="archivo" size="35" />
<input name="enviar" type="submit" class="boton" id="enviar" value="Upload File" />
<input name="action" type="hidden" value="upload" />
</form>

Como puedo agregarlo mas seguridad e integración con JS (Ajax) ?

Puede parecer mucho, pero lo necesito >< Gracias de antemano.
Última modificación: 3 Sep, 2012, 7:20 pm por V1K1NGO.
Edson Ordaz   3 Sep, 2012, 8:47 pm
#2
bueno le faltan cosas en seguridad como por ejemplo
if(!is_uploaded_file($_FILES['archivo']['tmp_name']))
{
	echo 'Error al subir la imagen';
	return false;
}

respecto a validar la extension seria mucho mejor hacerlo asi
if(!preg_match("#^(gif|jpg|jpeg|jpe|bmp|png)$#i", strtolower(mb_substr(strrchr($_FILES["archivo"]['name'];, "."), 1))))
{
	echo 'error en la extension';
	return false;
}

en particular en ves de copiar la imagen yo haria esto
$mover = @move_uploaded_file($_FILES['archivo']['tmp_name'], $destino."/".$prefijo."_".$archivo);
if(!$mover)
{
	echo 'no se a podidoca cargar la imagen';
	return false;
}

verificaria si la imagen tiene errores al cargarse de esta manera y si es asi eliminarla
if($_FILES["archivo"]['error'])
{
	@unlink($destino);
	echo 'error';
	return false;
}

y bueno para subirlo por ajax seria mucho mas sencillo...
solo poner en tu cabezera esto:
Cita:<script language="javascript">
$(document).ready(function() {

$('#form, #fat, #miformulario').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('#resultado').html(data);
}
})

return false;
});
})
</script>
No te olvides de poner al formulario name="miformulario" y id="miformulario"

y donde quieras que se muestre el resultado en ajax pon arriba del formulario o donde quieras
Cita:<div id="resultado"></div>
y al mandar el formulario se envia por ajax y actualiza eso.. otra cosa en upload.php en vez de regresar el dato como lo haces osea asi:
if(blablabla)
{
	$status = XXXX
}

if(blablabla)
{
	$status = XXX
}
return $status

haslo asi:
if(blablabla)
{
	echo 'TU MENSAJE';
	return false;
}

if(blablabla)
{
	echo 'TU MENSAJE';
	return false;
}

con eso donde muestre algun error o algo parara y regresara por ajax el mensaje Wink espeor te sirva..
saludos!
Edson Ordaz   3 Sep, 2012, 8:49 pm
#3
PD: Otra cosa que olvide si quieres mostrar error con ajax aslo asi

error: function(data) {
$('#error').html(data);
}
HSSWebs   4 Sep, 2012, 4:18 am
#4
Logre hacer casi todo lo que me dijiste, lo de verificar si la imagen tiene error al cargarse no supe donde ponerlo & tampoco lo del AJAX, te dejo el código completo aquí:


<?php
define("IN_MYBB", 1);
require_once "project/global.php";

$status = "";
if ($_POST["action"] == "upload")
{
	// obtenemos los datos del archivo
	$tamano   = $_FILES["archivo"]['size'];
	$tipo	  = $_FILES["archivo"]['type'];
	$archivo  = $_FILES["archivo"]['name'];
	$prefijo  = substr(md5(uniqid(rand())),0,16);
	
	if(!is_uploaded_file($_FILES['archivo']['tmp_name']))
	{
		echo 'Error al subir la imagen';
		return false;
	}
	else
	{
		if(!preg_match("#^(gif|jpg|jpeg|jpe|bmp|png)$#i", strtolower(mb_substr(strrchr($_FILES["archivo"]['name'], "."), 1))))
		{
			echo 'Archivo con extensión no valida.';
			return false;
		}
		else
		{
			$ext = substr(strrchr($archivo, '.'), 1);
			$path = "_" . $prefijo . "." . $ext;
			$destino = "files/" . $path;
			
			$moveimg = @move_uploaded_file($_FILES['archivo']['tmp_name'], $destino);
			if(!$moveimg)
			{
				echo 'No se a podido cargar la imagen.';
				return false;
			}
			else
			{
				$insertarray = array(
					'name' 		=> $archivo, 
					'path' 		=> $path, 
					'type' 		=> $tipo, 
					'size' 		=> $tamano,
					'regupload' => TIME_NOW
				);
				$db->insert_query("imgupload", $insertarray);			
				$status = "Archivo subido: <b>".$archivo."</b>";
			}
		}
	}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP upload - unijimpe</title>
<link href="estilo.css" rel="stylesheet" type="text/css" />
<script language="javascript">
$(document).ready(function()
{
	$('#imgupl').submit(function()
	{
		$.ajax({
			type: 'POST',
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(data)
			{
				$('#resultado').html(data);
			}
		})
		return false;
	}); 
}) 
</script>
</head>
<body>
<table width="413" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="413" height="40" class="titulo">PHP upload - unijimpe </td>
  </tr>
  <tr>
    <td class="text">Por favor seleccione el archivo a subir:</td>
  </tr>
  <tr>
  <form action="upload.php" name="imgupl" id="imgupl" method="post" enctype="multipart/form-data">
    <td class="text">
      <input name="archivo" type="file" class="casilla" id="archivo" size="35" />
      <input name="enviar" type="submit" class="boton" id="enviar" value="Upload File" />
	  <input name="action" type="hidden" value="upload" />	  </td>
	</form>
  </tr>
  <tr>
    <td class="text" style="color:#990000"><div id="resultado"></div></td>
  </tr>
  <tr>
    <td height="30" class="subtitulo">Listado de Archivos Subidos </td>
  </tr>
  <tr>
    <td class="infsub">
	<?php 
	$getimages = $db->simple_select('imgupload', '*', '', array('order_by' => 'regupload', 'order_dir'=>'ASC'));
	echo "<ul>";
	while($image = $db->fetch_array($getimages))
	{
		$user = get_user($image['uid']);
		echo "<li><a href=\"files/" . $image['path'] . "\" class=\"linkli\">" . $image['path'] . "</a> | " . $user['username'] . "</li>\n";
	}
	echo "</ul>";
	?>	</td>
  </tr>
</table>
</body>
</html>

PD: El código JS que haz puesto es con jquery o prototype? Porque ninguno de los dos me funciona..
Última modificación: 4 Sep, 2012, 4:40 am por V1K1NGO.
Edson Ordaz   4 Sep, 2012, 8:04 am
#5
yo lo haria asi mira no lo testie ni nada pero debe funcionar :p (olvide el link de un script para q funcione el ajax lo siento)


Ahora yo separe el formulario del upload quiero decir que el formulario esta en un archivo independiente por ejemplo index.php

<?php
define("IN_MYBB", 1);
require_once "project/global.php";
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP upload - unijimpe</title>
<link href="estilo.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(document).ready(function()
{
    $('#imgupl').submit(function() {
    {
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data)
            {
                $('#resultado').html(data);
            }
        })
        return false;
    }); 
}) 
</script>

</head>
<body>
<table width="413" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="413" height="40" class="titulo">PHP upload - unijimpe </td>
  </tr>
  <tr>
    <td class="text">Por favor seleccione el archivo a subir:</td>
  </tr>
  <tr>
  <form action="upload.php" name="imgupl" id="imgupl" method="post" enctype="multipart/form-data">
    <td class="text">
      <input name="archivo" type="file" class="casilla" id="archivo" size="35" />
      <input name="enviar" type="submit" class="boton" id="enviar" value="Upload File" />
      <input name="action" type="hidden" value="upload" />      </td>
    </form>
  </tr>
  <tr>
    <td class="text" style="color:#990000"><div id="resultado"></div></td>
  </tr>
  <tr>
    <td height="30" class="subtitulo">Listado de Archivos Subidos </td>
  </tr>
  <tr>
    <td class="infsub">
    <?php 
    $getimages = $db->simple_select('imgupload', '*', '', array('order_by' => 'regupload', 'order_dir'=>'ASC'));
    echo "<ul>";
    while($image = $db->fetch_array($getimages))
    {
        $user = get_user($image['uid']);
        echo "<li><a href=\"files/" . $image['path'] . "\" class=\"linkli\">" . $image['path'] . "</a> | " . $user['username'] . "</li>\n";
    }
    echo "</ul>";
    ?>    </td>
  </tr>
</table>
</body>
</html> 

y el upload.php seria asi:
<?php
define("IN_MYBB", 1);
require_once "project/global.php";

	$tamano   = $_FILES["archivo"]['size'];
	$tipo      = $_FILES["archivo"]['type'];
	$archivo  = $_FILES["archivo"]['name'];
    $prefijo  = substr(md5(uniqid(rand())),0,16);
    
    if(!is_uploaded_file($_FILES['archivo']['tmp_name']))
    {
        echo 'Error al subir la imagen';
        return false;
    }
	if(!preg_match("#^(gif|jpg|jpeg|jpe|bmp|png)$#i", strtolower(mb_substr(strrchr($_FILES["archivo"]['name'], "."), 1))))
	{
		echo 'Archivo con extensión no valida.';
		return false;
	}
	$ext = substr(strrchr($archivo, '.'), 1);
	$path = "_" . $prefijo . "." . $ext;
	$destino = "files/" . $path;
	if(!$moveimg)
	{
		echo 'No se a podido cargar la imagen.';
		return false;
	}
	if($_FILES["archivo"]['error'])
	{
		@unlink($destino);
		echo 'error';
		return false;
	} 
	$insertarray = array(
		'name'         => $archivo, 
		'path'         => $path, 
		'type'         => $tipo, 
		'size'         => $tamano,
		'regupload' => TIME_NOW
	);
	$db->insert_query("imgupload", $insertarray);            
	echo "Archivo subido: <b>".$archivo."</b>";
	return false;
	
?>
Última modificación: 4 Sep, 2012, 8:05 am por Pomelete.
HSSWebs   4 Sep, 2012, 8:12 am
#6
Queda igual, la imagen se sube, pero el Ajax no funciona..
Solo devuelve esto
echo "Archivo subido: <b>".$archivo."</b>";
Edson Ordaz   4 Sep, 2012, 8:54 am
#7
puedes ponerme el link porfavor.. quiero ver como funciona...
HSSWebs   4 Sep, 2012, 8:55 am
#8
Lo tengo solo en mi PC, si quieres después lo subo por hay, pero ya te digo lo del ajax no funciona, recarga la pagina completa.
Edson Ordaz   4 Sep, 2012, 9:08 am
#9
ok dame unos minutos lo hago en localhost :p
Edson Ordaz   4 Sep, 2012, 9:17 am
#10
Última modificación: 4 Sep, 2012, 9:17 am por Pomelete.
Páginas (2): 1 2   
  
Powered By MyBB, © 2002-2025 MyBB Group.
Made with by Curves UI.