Foros del Web » Programando para Internet » PHP »

Renombrar una imagen

Estas en el tema de Renombrar una imagen en el foro de PHP en Foros del Web. Hola; hace tiempo empece a tratar un tema que quiero retomar http://www.forosdelweb.com/f18/subir...brarla-703085/ Este es el codigo que tengo actualmente Código PHP: <?php  require_once( 'Connections/compramos.php' );  ...
  #1 (permalink)  
Antiguo 08/07/2009, 15:30
 
Fecha de Ingreso: febrero-2008
Mensajes: 675
Antigüedad: 16 años, 2 meses
Puntos: 5
Renombrar una imagen

Hola;
hace tiempo empece a tratar un tema que quiero retomar http://www.forosdelweb.com/f18/subir...brarla-703085/
Este es el codigo que tengo actualmente
Código PHP:
<?php require_once('Connections/compramos.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']);
}
// $len es la longitud que deseas que tenga el nuevo nombre
function random_name($len) {
    
$chars 'abcdefghijklmnopqrstuvwxyz0123456789';
    
$name '';
    for (
$i 0$i $len; ++$i)
        
$name .= substr($chars, (mt_rand() &#37; strlen($chars)), 1);
    
return $name;
}
 
// Asegurate de agregar la extension correcta
$nuevo_nombre random_name(15) . '.jpg';

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "insertar")) {
  
$insertSQL sprintf("INSERT INTO productos (nombre, categoria, descripcion, imagen, usuario, pdf) VALUES (%s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['Nombre'], "text"),
                       
GetSQLValueString($_POST['categoria'], "int"),
                       
GetSQLValueString($_POST['descripcion'], "text"),
                       
GetSQLValueString("archivos/" $nuevo_nombre"text"),
                       
GetSQLValueString($_POST['usuario'], "text"),
                       
GetSQLValueString($_POST['pdf'], "text"));

  
move_uploaded_file($_FILES['imagen']['tmp_name'], $nuevo_nombre)
  
$Result1 mysql_query($insertSQL$compramos) or die(mysql_error());

  
$insertGoTo "productos.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
?>
<!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" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Documento sin t&iacute;tulo</title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>

<body>
<div id="mainContent">
  <form action="<?php echo $editFormAction?>" method="POST" enctype="multipart/form-data" name="insertar" id="insertar">
          <table width="950" border="0">
            <tr>
              <td width="90"><div align="right">Nombre</div></td>
              <td width="8">&nbsp;</td>
              <td width="383"><label>
                <input type="text" name="Nombre" id="Nombre" />
              </label></td>
              <td width="451">&nbsp;</td>
            </tr>
            <tr>
              <td><div align="right">Categoría</div></td>
              <td>&nbsp;</td>
              <td><label>
                <select name="categoria" id="categoria">
                  <?php
do {  
?>
                  <option value="<?php echo $row_categoria['id_categoria']?>"<?php if (!(strcmp($row_categoria['id_categoria'], $row_categoria['id_categoria']))) {echo "selected=\"selected\"";} ?>><?php echo $row_categoria['categoria']?></option>
                  <?php
} while ($row_categoria mysql_fetch_assoc($categoria));
  
$rows mysql_num_rows($categoria);
  if(
$rows 0) {
      
mysql_data_seek($categoria0);
      
$row_categoria mysql_fetch_assoc($categoria);
  }
?>
              </select>
              </label></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td><div align="right">Descripción</div></td>
              <td>&nbsp;</td>
              <td><label>
                <textarea name="descripcion" id="descripcion" cols="45" rows="5"></textarea>
              </label></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td><div align="right">Imagen</div></td>
              <td>&nbsp;</td>
              <td><label>
                <input type="file" name="imagen" id="imagen" />
              </label></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td align="right">PDF</td>
              <td>&nbsp;</td>
              <td><input type="file" name="pdf" id="pdf" /></td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td><div align="right">
                <input name="usuario" type="hidden" id="usuario" value="<?php echo $row_categoria['id_categoria']; ?>" />
              </div></td>
              <td>&nbsp;</td>
              <td><label>
                <input name="button" type="submit" class="boton" id="button" value="Enviar" />
              </label></td>
              <td>&nbsp;</td>
            </tr>
          </table>
          <input type="hidden" name="MM_insert" value="insertar" />
  </form>
        <h1>&nbsp;</h1>
<!-- end #mainContent --></div>
</body>
</html>
me saca una pagina en blanco, sin errores y sin nada, y la conexion a la base de datos esta bien, ya que si quito el codigo que sube la imagen, muestra el formulario e inserta correctamente.
Un saludo
  #2 (permalink)  
Antiguo 08/07/2009, 15:42
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Renombrar una imagen

Cita:
Iniciado por visona
move_uploaded_file($_FILES['imagen']['tmp_name'], $nuevo_nombre)
A esa linea le falta colocar al final punto y coma ; ... sin embargo, no es la forma mas optima para realizar el proceso, sino antes de insertar los datos:

Código php:
Ver original
  1. if(!move_uploaded_file($_FILES['imagen']['tmp_name'], $nuevo_nombre)) {
  2.     echo 'No se pudo mover el archivo subido a su destino final, codigo de error: ' . $_FILES['imagen']['error'];
  3.     exit; // Detenemos el script para no insertar datos cuando hay errores.
  4. }
__________________
- León, Guanajuato
- GV-Foto
  #3 (permalink)  
Antiguo 09/07/2009, 06:07
 
Fecha de Ingreso: febrero-2008
Mensajes: 675
Antigüedad: 16 años, 2 meses
Puntos: 5
Respuesta: Renombrar una imagen

Nada que me aparece la pagina en blanco. este es el codigo que tengo puesto ahora, solo me sale pantalla en blanco cuando coloco tu codigo.

Código PHP:
<?php require_once('Connections/compramos.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;
}
}

// $len es la longitud que deseas que tenga el nuevo nombre
function random_name($len) {
    
$chars 'abcdefghijklmnopqrstuvwxyz0123456789';
    
$name '';
    for (
$i 0$i $len; ++$i)
        
$name .= substr($chars, (mt_rand() &#37; strlen($chars)), 1);
    
return $name;
}
 
// Asegurate de agregar la extension correcta
$nuevo_nombre random_name(15) . '.jpg';
if(!
move_uploaded_file($_FILES['imagen']['tmp_name'], $nuevo_nombre)); {
    echo 
'No se pudo mover el archivo subido a su destino final, codigo de error: ' $_FILES['imagen']['error'];
    exit; 
// Detenemos el script para no insertar datos cuando hay errores.
}


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

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "envio")) {
  
$insertSQL sprintf("INSERT INTO productos (nombre, descripcion, imagen) VALUES (%s, %s, %s)",
                       
GetSQLValueString($_POST['nombre'], "text"),
                       
GetSQLValueString($_POST['descripcion'], "text"),
                       
GetSQLValueString("archivos/" $nuevo_nombre"text"));

  
mysql_select_db($database_compramos$compramos);
  
$Result1 mysql_query($insertSQL$compramos) or die(mysql_error());

  
$insertGoTo "pruebaenvio.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
?><!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" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Documento sin t&iacute;tulo</title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>

<body>
<form action="<?php echo $editFormAction?>" method="POST" enctype="multipart/form-data" name="envio" id="envio">
  <label>
  <input type="text" name="nombre" id="nombre" />
  </label>
  <p>
    <label>
    <textarea name="descripcion" id="descripcion" cols="45" rows="5"></textarea>
    </label>
  </p>
  <p>
    <label>
    <input type="file" name="imagen" id="imagen" />
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="button" id="button" value="Enviar" />
    </label>
  </p>
  <input type="hidden" name="MM_insert" value="envio" />
</form>
</body>
</html>
Un saludo y gracias


Cita:
Iniciado por Triby Ver Mensaje
A esa linea le falta colocar al final punto y coma ; ... sin embargo, no es la forma mas optima para realizar el proceso, sino antes de insertar los datos:

Código php:
Ver original
  1. if(!move_uploaded_file($_FILES['imagen']['tmp_name'], $nuevo_nombre)) {
  2.     echo 'No se pudo mover el archivo subido a su destino final, codigo de error: ' . $_FILES['imagen']['error'];
  3.     exit; // Detenemos el script para no insertar datos cuando hay errores.
  4. }
  #4 (permalink)  
Antiguo 09/07/2009, 17:37
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Renombrar una imagen

Ok, antes de intentar mover el archivo revisa si hubo errores:

Código php:
Ver original
  1. $estado = $_FILES['imagen']['error'];
  2. if($estado !== 0)
  3.     die('Hubo un error al subir el archivo, codigo: ' . $estado);
  4.  
  5. // Tambien puedes echarle un ojo a lo que estas recibiendo en FILES
  6. echo '<pre>';
  7. var_dump($_FILES);
  8. echo '</pre>';
__________________
- León, Guanajuato
- GV-Foto
  #5 (permalink)  
Antiguo 14/07/2009, 08:08
 
Fecha de Ingreso: febrero-2008
Mensajes: 675
Antigüedad: 16 años, 2 meses
Puntos: 5
Respuesta: Renombrar una imagen

Tryby, el problema esta en que no me sale nada si pongo el codigo que te pongo si quires te paso por privado los datos de conexion a base de datos MySql.
Un saludo y gracias


Cita:
Iniciado por Triby Ver Mensaje
Ok, antes de intentar mover el archivo revisa si hubo errores:

Código php:
Ver original
  1. $estado = $_FILES['imagen']['error'];
  2. if($estado !== 0)
  3.     die('Hubo un error al subir el archivo, codigo: ' . $estado);
  4.  
  5. // Tambien puedes echarle un ojo a lo que estas recibiendo en FILES
  6. echo '<pre>';
  7. var_dump($_FILES);
  8. echo '</pre>';
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 20:22.