Ver Mensaje Individual
  #5 (permalink)  
Antiguo 28/02/2011, 02:42
michaelvanhout
 
Fecha de Ingreso: noviembre-2010
Ubicación: Telde, Gran Canaria
Mensajes: 15
Antigüedad: 13 años, 5 meses
Puntos: 0
Respuesta: formulario complicado

gracias compañeros, pero esto lo tengo puesto. Me funciona en parte. Todos los datos llegan al procesar.php. El problema que tengo es que tengo que subir el archivo a una carpeta y darle un nombre aleatoreo. No me registra el nombre aaleatorio ni el nombre orginal en bbdd. Si sube el archivo a carpete con nombre orginal.
Este proceso tengo que hacer con 2 files(1 imagen,1 pdf). Aqui teneis el codigo de mi ultimo intento (solo con imagen para subir). en bbdd hay un col que se llama alea, donde guardar nombre aleatoreo.

<?php require_once('../Connections/enchufe.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO productos (cat, subcat, id_producto, fabricante, modelo, descripcion, precio, imagen, archivo, fecha_alta, id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
GetSQLValueString($_POST['cat'], "text"),
GetSQLValueString($_POST['subcat'], "text"),
GetSQLValueString($_POST['id_producto'], "text"),
GetSQLValueString($_POST['fabricante'], "text"),
GetSQLValueString($_POST['modelo'], "text"),
GetSQLValueString($_POST['descripcion'], "text"),
GetSQLValueString($_POST['precio'], "double"),

GetSQLValueString($_POST['imagen'], "text"),
GetSQLValueString($_POST['archivo'], "text"),
GetSQLValueString($_POST['fecha_alta'], "date"),
GetSQLValueString($_POST['id'], "int"));

mysql_select_db($database_enchufe, $enchufe);
$Result1 = mysql_query($insertSQL, $enchufe) or die(mysql_error());

$insertGoTo = "insertar.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_enchufe, $enchufe);
$query_Recordset1 = "SELECT * FROM productos";
$Recordset1 = mysql_query($query_Recordset1, $enchufe) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>

<?php
// proceso imagen
$temp = $_FILES['imagen']['tmp_name']; // tmp name (no se puede cambiar el nombre nos devuelve la ubicación temporal del archivo.
$imagen= $_FILES['imagen']['name']; // nombre original del archivo
$tamanoBytes = $_FILES['imagen']['size']; // En bytes
$tipoFile = $_FILES['imagen']['type'];



// VALIDAR PESO DEL ARCHIVO. LIMITAR SUBIDA POR PESO
// LIMITAMOS A 300KB
$kiloBytes = $tamanoBytes/1024; // esto nos da la cantidad de kb
if($kiloBytes > 300){
echo "El archivo supera los 300 KB <br/>";
exit;
sleep(2);

}


// VALIDAR POR TIPO DE ARCHIVO.

if($tipoFile == "image/jpeg" || $tipoFile == "image/gif" || $tipoFile == "image/png"){
echo "Es el tipo esperado <br/>";
// GUARDAMOS EL ARCHIVO EN UNA CARPETA
}
else{
echo "Archivo no válido";
exit;
}



switch ($tipoFile)
{
case 'image/jpeg':
$ext = ".jpg";
break;

case 'image/gif':
$ext = ".gif";
break;

case 'image/png':
$ext = ".png";
break;
}



echo "Esta es la exte: " .$ext ."<br/>";

// VALOR ALEATORIO CON EL QUE SE ALMACENARÁ EL ARCHIVO
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw xyz1234567890";
$cad = "";
for($i=0;$i<18;$i++) {
$cad .= substr($str,rand(0,62),1);
}


// Reemplazar en caso de nombre compuestos los espacios por guión bajo
$alea1 = str_replace(" ","_",$alea1);

$alea1 = $cad.$ext;
echo "Alea: " .$alea1 ."<br/>";

copy($temp,$alea1);
// $fecha = date("y-m-d");

// Ahora guardamos el archvo en una base de datos.

$sql ="insert into productos values (null,'$imagen','$alea1')";
$conecta = mysql_select_db($bd,$con); // conecta a la base de datos
$result = mysql_query($sql);

// Podemos recuperar el último id guardado mediante
//echo "MYSQL: " .mysql_insert_id($con);


// Indicamos el directorio donde se guardará el archivo
$dir = "productos/";
move_uploaded_file ($temp,"$dir/$alea1");


echo "El archivo tienen como nombre: " .$name ."<br/>";
echo "El archivo en el servidor es temporal, como: " .$temp ."<br/>";
echo "El tamaño del archivo es: " .$tamanoBytes ."<br />";
echo "El tipo del archivo es: " .$tipoFile ."<br/>";
echo "El peso en KB es de: " .round($kiloBytes,2) ."Kb <br/>";
?>
<img src="<?php echo "img/".$alea1; ?>" />
<?php
mysql_free_result($Recordset1);
?>