Foros del Web » Programando para Internet » PHP »

Problema con upload de archivo

Estas en el tema de Problema con upload de archivo en el foro de PHP en Foros del Web. Hola amigos, tengo el siguiente codigo para subir un archivo a través de un form: Código PHP:    // Upload    $path  =  "$site_dir/fotos/" ;    ...
  #1 (permalink)  
Antiguo 10/11/2003, 09:08
 
Fecha de Ingreso: abril-2002
Ubicación: Argentina
Mensajes: 96
Antigüedad: 22 años
Puntos: 0
Problema con upload de archivo

Hola amigos, tengo el siguiente codigo para subir un archivo a través de un form:
Código PHP:
  // Upload
  
$path "$site_dir/fotos/";
  
$max_size 512000;
  if (
is_uploaded_file($userfile)) {
  if (
$userfile_size>$max_size) { echo "Foto demasiado grande!<br>\n"; exit; }
  if ((
$userfile_type=="image/x-png") || ($userfile_type=="image/pjpeg") || ($userfile_type=="image/jpeg")) {
  if (
file_exists($path $userfile_name)) { echo "<p align=\"center\">Una imagen con este nombre ya se encuentra en el servidor, por favor renombrela y vuelvala a subir!</p><br>\n";$escape=1; }

  if(
$escape!=1){
  
$res move_uploaded_file($userfile$path $userfile_name);
  
// crear thumbnail
  
if (file_exists("$site_dir/fotos/" "thumb_$userfile_name"))
    {
         
unlink("$site_dir/images/thumb_$userfile_name");
        
$thumb=new thumbnail("$site_dir/fotos/$userfile_name");
        
$thumb->size_auto(75);
        
$thumb->jpeg_quality(75);
        
$thumb->save("$site_dir/fotos/thumb_$userfile_name"$gd_version);
      } else {
      
$thumb=new thumbnail("$site_dir/fotos/$userfile_name");
        
$thumb->size_auto(75);
        
$thumb->jpeg_quality(75);
        
$thumb->save("$site_dir/fotos/thumb_$userfile_name"$gd_version);
  }
  }
  if(
$escape=1){$res="continue";}

  
// Resultde de la salida
  
if (!$res) {
  echo 
"<p align=\"center\">Fallo al subir imagen!<br><br><a href=\"javascript:history.back()\">Intentelo nuevamente</a></p>\n"; exit; }
    } else { echo 
"<p align=\"center\">Extension de Archivo no permitida.<br><br><a href=\"javascript:history.back()\">Intentelo nuevamente</a></p>\n"; exit; } 
Pero obtengo el siguiente error:
Código:
Warning: move_uploaded_file(): SAFE MODE Restriction in effect. The script whose uid is 649 is not allowed to access / owned by uid 0 in cargar.php on line 86

Warning: imagecreatefromjpeg(/fotos/279741-001.jpg): failed to open stream: No such file or directory in makethumb.txt on line 36

Warning: imagecreate(): Invalid image dimensions in makethumb.txt on line 105

Warning: imagejpeg(): supplied argument is not a valid Image resource in makethumb.txt on line 110
No logro saber cual es el problema
Podría orientarme?
Gracias
Saludos
__________________
Sergio
  #2 (permalink)  
Antiguo 10/11/2003, 09:23
Ex Colaborador
 
Fecha de Ingreso: junio-2002
Mensajes: 9.091
Antigüedad: 21 años, 10 meses
Puntos: 16
Hola,

Haz un echo $path; . O mejor, un echo $site_dir; . Y asegurate de que el usuario de PHP tiene permisos en ese directorio.

Saludos.
__________________
Josemi

Aprendiz de mucho, maestro de poco.
  #3 (permalink)  
Antiguo 10/11/2003, 09:31
 
Fecha de Ingreso: noviembre-2003
Mensajes: 21
Antigüedad: 20 años, 5 meses
Puntos: 0
tu php está en "safe mode", o sea no puede usar todos los funciones de tu ordenador para evitar ataques de hackers etcétera. sin embargo parece que tu script trata de abrir el fichero / (raíz del sistema del ficheros) ("The script whose uid is 649 is not allowed to access / owned by uid 0")... debes dar salida a todas las cadenas que estás uzando, sobre todo $path . $userfile_name - quizá eso pueda ayudarte a encontrar el problema... también tienes que leer el manual en http://www.php.net/manual/es/features.file-upload.php porque es mejor usar $_FILES["userfile"] .
saludos
  #4 (permalink)  
Antiguo 10/11/2003, 13:55
Avatar de nuevo  
Fecha de Ingreso: mayo-2003
Ubicación: Spain
Mensajes: 2.009
Antigüedad: 20 años, 11 meses
Puntos: 2
yo usaria una classe para lo que pretendes... y mas aun, no hace falta ni gd pero bueno... aqui te dejo algo que te puede servir de orientacion...

fichero formulario
Código PHP:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.testo {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 10px;
}
.titulo {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
    font-weight: bolder;
    color:#FFFFFF;
}
.eu {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 11px;
}

-->
</style>
</head>

<body>
<table align="CENTER" width="500" border="0">
  <tr>
    <td bgcolor="000099" colspan="2"><div align="center" class="titulo">Sube Tu Imagen / Banner</div></td>
  </tr>

  <tr>
    <td height="10" colspan="2">
<div align="left" class="eu">
</CENTER>
    </td>
  </tr>
  <tr>
    <td height="10" colspan="2"><div align="center">
<?php
include_once("class.upload.inc.php");
    if ( 
$send == "ok" && $_FILES[fichero]['name'] ){// del formulario sacamos el boton ok, comienza la classe upload

        
$upload = new upload();

        if (
$upload -> putFile ("fichero")) {

            
$imagen $upload->file_name;

        }
    }

?>
      </div></td>
  </tr>
  <form action="<?php $PHP_SELF?>" method="post" enctype="multipart/form-data"> <tr>
    <td colspan="2">
        <p align="center">
          <input name="fichero" type="file" class="testo">
        </p>
      </td>
  </tr>
  <tr>
    <td colspan="2"> <p align="center">
        <input name="Submit" type="submit" value="Subir Fichero" class="testo">
        <input name="send" type="hidden" value="ok">
      </p></td>
  </tr></form>
</table>
</body>
</html>
--------------------
__________________
3w.valenciadjs.com
3w.laislatv.com

Última edición por nuevo; 10/11/2003 a las 14:14
  #5 (permalink)  
Antiguo 10/11/2003, 14:15
Avatar de nuevo  
Fecha de Ingreso: mayo-2003
Ubicación: Spain
Mensajes: 2.009
Antigüedad: 20 años, 11 meses
Puntos: 2
... como no cabe lo meto en otro

fichero classe: class.upload.inc.php

Código PHP:
<?php
class upload
{
    
// class variable
    
    
var $file_permitted;        // array MIME type of the permetted file
    
var $archive_dir;        // upload directory    
    
var $max_filesize;        // max size of file upload
    
    // constructor 
    // input:   $max_fil   = max size of file upload                    default -> 300 kbyte
    //            $file_perm = array with mime/type of files to upload    default -> jpg, png, gif
    //            $arc_dir   = destination dir of the upload file            default -> ditectory corrente
    
    
function upload $file_perm $max_fil 300000$arc_dir ".." )
    {
        if ( empty (
$file_perm) ) $file_perm = array ("image/pjpeg","image/x-png","image/jpeg","image/png");
        
        
$this->file_permitted $file_perm// set mime/type of files to upload
        
        
$this->max_filesize $max_fil// set max size of file upload
        
        
$this->archive_dir $arc_dir;  // set destination dir of the upload file
    
}
    
    
// upload method
    // input: $file    = name of the FILE filed on the FORM
    
    
function putFile $file )
    {
        
$userfile_type strtok $_FILES[$file]['type'], ";"); // clear file type:  MIME TYPE
        
$userfile_name $_FILES[$file]['name']; // set the original file name
        
$userfile_size $_FILES[$file]['size']; // set the file uploaded dimension
        
$userfile $_FILES[$file]['tmp_name'];  // file uploaded in the temp dir
        
        
$error "This file type is not permitted: $userfile_type<br>"// set the error message
        
        // if the file is in the list of MIME TYPE permetted
        // set the error to empty string
        
        
$file_permitted $this->file_permitted;
        
        foreach ( 
$file_permitted as $permitted )
        {
            if ( 
$userfile_type == $permitted $error "";
        }
        
        
// if filesize is <= 0 or  > $max_filesize
        // set the error message
        
if ( ($userfile_size <= 0) || ($userfile_size $this->max_filesize) ) $error "File size error: $userfile_size Kb.<br>";
        
        
// if no error occured, start coping file
        
if ( $error == "" )
        {

            
$filename basename ($userfile_name); // extract file name

            
if (!empty ($this->archive_dir) ) 
                
$destination $this->archive_dir."/".$filename// full destination path to images dir
            
else 
                
$destination $filename// full destination path to images dir

            // check id a fale eith the same name exist
            // if exist, add a random number to the file name
            
if ( file_exists($destination) )
            {
                
srand((double)microtime()*1000000); // random number inizializzation
                
$filename rand(0,20000).$filename// add number to file name
                
if (!empty ($this->archive_dir) ) 
                    
$destination $this->archive_dir."/".$filename// full destination path to images dir
                
else 
                    
$destination $filename// full destination path to images dir
            
}

            
// Do some additional checks
            
if(!is_uploaded_file($userfile)) die ("File $userfile_name is not uploaded correctly.");
      
            
// copy file to temp dir to destination fir and removee the temp file
      
            
if ( !@move_uploaded_file ($userfile,$destination) ) die ("Impossible to copy $userfile_name from $userfile to destination directory.");

            return 
$destination// return the full path of the file on file system of the server 
        
}
        else
        {
            echo 
$error;
            return 
false;
        }

    }
    

    
// check to see what version (if any) of the gd libraries are installed
    
function chkgd2()
    {
        
$testGD get_extension_funcs("gd"); // Grab function list
        
if (!$testGD
        { 
            echo 
"GD not even installed."
            return 
false
        }
        else
        {
            
ob_start(); // Turn on output buffering
            
phpinfo(8); // Output in the output buffer the content of phpinfo
            
$grab ob_get_contents(); // Grab the buffer
            
ob_end_clean(); // Clean (erase) the output buffer and turn off output buffering 
            
            
$version strpos  ($grab,"2.0 or higher"); // search for string '2.0 or higher'
            
if ( $version ) return "gd2"// if find the string return gd2
            
else return "gd"// else return "gd"
        
}
    }    
    
    
// resize method
    
    
function resize_jpeg$image_file_path$new_image_file_path$max_width=480$max_height=1600 )
    {

        
$return_val 1;

        
// create new image

        
if(eregi("\.png$",$image_file_path)) // if is a png
        
{
            
$return_val = ( ($img ImageCreateFromPNG $image_file_path )) && $return_val == ) ? "1" "0";
        }

        if(
eregi("\.(jpg|jpeg)$",$image_file_path)) // if is a jpg
        
{
            
$return_val = ( ($img ImageCreateFromJPEG $image_file_path )) && $return_val == ) ? "1" "0";
        }

        
$FullImage_width imagesx ($img);    // original width
        
$FullImage_height imagesy ($img);    // original width

        // now we check for over-sized images and pare them down
        // to the dimensions we need for display purposes
        
$ratio =  ( $FullImage_width $max_width ) ? (real)($max_width $FullImage_width) : ;
        
$new_width = ((int)($FullImage_width $ratio));    //full-size width
        
$new_height = ((int)($FullImage_height $ratio));    //full-size height

        //check for images that are still too high
        
$ratio =  ( $new_height $max_height ) ? (real)($max_height $new_height) : ;
        
$new_width = ((int)($new_width $ratio));    //mid-size width
        
$new_height = ((int)($new_height $ratio));    //mid-size height

        // --Start Full Creation, Copying--
        // now, before we get silly and 'resize' an image that doesn't need it...
        
if ( $new_width == $FullImage_width && $new_height == $FullImage_height copy $image_file_path$new_image_file_path );
    
        
// check to see if gd2+ libraries are compiled with php
        
        
$gd_version = ( $this->chkgd2() );
        
        if ( 
$gd_version == "gd2" 
        {        
            
$full_id =  ImageCreateTrueColor $new_width $new_height ); //Crea un'immagine
            
ImageCopyResampled $full_id$img0,0,0,0$new_width$new_height$FullImage_width$FullImage_height );
        }
        elseif ( 
$gd_version == "gd" )
        {        
            
$full_id ImageCreate $new_width $new_height ); //Crea un'immagine
            
ImageCopyResized $full_id$img0,0,0,0$new_width$new_height$FullImage_width$FullImage_height );
        }
        
        else 
"GD Image Library is not installed.";
        
        if(
eregi("\.(jpg|jpeg)$",$image_file_path))
        {
            
$return_val = ( $full ImageJPEG$full_id$new_image_file_path80 ) && $return_val == ) ? "1" "0";
        }

        if(
eregi("\.png$",$image_file_path))
        {
            
$return_val = ( $full ImagePNG$full_id$new_image_file_path ) && $return_val == ) ? "1" "0";
        }

        
ImageDestroy$full_id );

        
// --End Creation, Copying--

        
return ($return_val) ? TRUE FALSE ;

    }
    
    
// thumbnail creation
    // input:   $image_path = path to image to resize
    //            $path         = destination dir of the thumbnails
    //            $larghezza  = thumbnails witdh                             default -> 80 pixel
    //            $altezza      = thumbnails height                         default -> 80 pixel
    //             $pre_name   = pre file string for thumbs                default -> "thumb_"
            
    
function miniatura $image_path$path$larghezza=80$altezza=80$pre_name="thumb_" )
    {
        if ( (
eregi("\.png$"$image_path) || eregi("\.(jpg|jpeg)$"$image_path)) && $image_path )
        {
            
$image_name basename $image_path );
            
            if (!empty (
$path) ) 
                
$thumb_path $path."/".$pre_name.$image_name// complete path to thumbnail dir
            
else 
                
$thumb_path $pre_name.$image_name// complete path to thumbnail dir
            
            
if ( $this->resize_jpeg($image_path$thumb_path$larghezza$altezza) ) return $thumb_path;
            else return 
"Errore nella creazione della miniatura<BR>";
        }
        elseif (
$image_path) return "Impossibile creare la Miniatura da questo tipo di file<BR>";
        elseif (
$send && $image_path) return "<font face=\"Verdana\" size=\"2\" color=\"red\"><b>Errore nel caricamento dell''immagine $cont</b></font><br>";    
    }
    
    function 
splitFilePath $completePath "null/null" ) {
        
        
$filePath = array ( path=>""filename=>"" ) ;
        
$tok strtok($completePath,"/");
        
        while (
$tok) {
            
$file_name $tok;
            
$tok strtok("/");
        } 
// end while
        
        
$path str_replace $file_name""$completePath );
        
$filePath[path] = $path
        
$filePath[filename] = $file_name
        
        return 
$filePath;
    }        
}
?>
venga, un saludo para ti! byeee


pd: haz una carpeta /images donde esten los ficheros y dale permisos 777

rpd: no es la mejor classe que puedes encontrar, pero... la idea ya la tienes... lo digo pq usar ese codigo... no esq este mal... ni mucho menos... pero las classes son otra cosa
__________________
3w.valenciadjs.com
3w.laislatv.com
  #6 (permalink)  
Antiguo 10/11/2003, 15:56
 
Fecha de Ingreso: abril-2002
Ubicación: Argentina
Mensajes: 96
Antigüedad: 22 años
Puntos: 0
Gracias por sus repuestas, el problema de subir las imagenes lo solucioné, después de dar muchas vueltas estaba apuntando mal la ruta
Ahora mi problema se presenta cuando quiero modificar el registro de la base de datos para poder modificar la imagen.
El form de modificacion de datos es el siguiente:
Código PHP:
$row mysql_fetch_array($link);
$el_jugador=$row[Id_jugador];
$foto_actual=$row[foto];
$nacio_el=cambiaf_a_normal($row[fecha_nacimiento]);
print(
"<form name='form1' method='post' action='player_update.php' enctype='multipart/form-data'>
  <table width='90%' border='0' cellspacing='1' cellpadding='0' bgcolor='#000000' align='center'>
    <tr> 
      <td colspan='2' class='form_stitulo'>Datos personales</td>
    </tr>
    <tr> 
      <td class='form_txt'>Nombre completo</td>
      <td class='form_txt'>
        <input type='text' name='nombre' value='$row[nombre_completo]'>
      </td>
    </tr>
    <tr> 
      <td class='form_txt'>Fecha de nacimiento</td>
      <td class='form_txt'>
        <input type='text' name='nac_fecha' size='20' value=$nacio_el>
        (conservar el formato de la fecha dd/mm/yyyy)</td>
    </tr>
    <tr> 
      <td class='form_txt'>Pa&iacute;s</td>
      <td class='form_txt'>"
);
    echo 
"<select name='pais'> ";
    
$oldpais_id=$row[Id_pais];
         
$db mysql_connect("localhost""futbol""sql677soccer");
        
mysql_select_db("jugadoresdefutbolonline_com_-_players",$db);
        
$result6 mysql_query("SELECT desc_pais,Id_pais FROM players_pais ORDER BY desc_pais ASC"$db);
        while (
$myrow6 mysql_fetch_array($result6)) {
        echo 
"<option value='$myrow6[Id_pais]' ";
    if(
$oldpais_id==$myrow6[Id_pais]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow6[desc_pais]";
      echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Ciudad</td>
      <td class='form_txt'>
        <input type='text' name='ciudad' value='$row[ciudad]'>
      </td>
    </tr>
    <tr> 
      <td class='form_txt'>Estado civil</td>
      <td class='form_txt'>"
);
         echo 
"<select name='e_civil'> ";
    
$old_ecivil_id=$row[Id_ecivil];
        
$result mysql_query("SELECT desc_ecivil,Id_ecivil FROM players_estado_civil ORDER BY desc_ecivil ASC"$db);
        while (
$myrow mysql_fetch_array($result)) {

    echo 
"<option value='$myrow[Id_ecivil]' ";
    if(
$old_ecivil_id==$myrow[Id_ecivil]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow[desc_ecivil]";
      echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Estudios cursados</td>
      <td class='form_txt'>"
);
        echo 
"<select name='estudios'> ";
    
$old_estudios_id=$row[Id_estudios];
        
$result1 mysql_query("SELECT desc_estudios,Id_estudios FROM players_estudios ORDER BY desc_estudios ASC"$db);
        while (
$myrow1 mysql_fetch_array($result1)) {
    echo 
"<option value='$myrow1[Id_estudios]' ";
    if(
$old_estudios_id==$myrow1[Id_estudios]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow1[desc_estudios]";
      echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Posee pasaporte comunitario?</td>
      <td class='form_txt'>"
);
    
$old_pasaporte=$row[pasaporte];
    echo 
"<input type=\"radio\" name=\"pasaporte\" value=\"Si\" ";if($old_pasaporte=="Si"){echo "checked";}echo">";
    echo 
"Si";
    echo 
"<input type=\"radio\" name=\"pasaporte\" value=\"No\" ";if($old_pasaporte=="No"){echo "checked";}echo">";
    echo 
"No";
$la_foto=$row[foto];
print (
"</tr>
    <tr> 
      <td class='form_txt'>Estatura</td>
      <td class='form_txt'>
        <input type='text' name='estatura' value='$row[estatura]'>
        (en cent&iacute;metros)</td>
    </tr>
    <tr> 
      <td class='form_txt'>Peso</td>
      <td class='form_txt'>
        <input type='text' name='peso' value='$row[peso]'>
        (en kilogramos)</td>
    </tr>
    <tr> 
      <td class='form_txt'>Fotograf&iacute;a</td>
      <td class='form_txt'><img src='../fotos/$la_foto'></td>
    </tr>
    <tr> 
      <td class='form_txt'>Borrar Fotograf&iacute;a</td>
      <td class='form_txt'>
        <input type='radio' name='image_function' value='del'>
        (Este casillero debe ser SELECCIONADO para borrar la foto existente)</td>
    </tr>
    <tr> 
      <td class='form_txt'>Subir nueva Fotograf&iacute;a</td>
      <td class='form_txt'>
        <input type='radio' name='image_function' value='up'>
        (Este casillero debe ser SELECCIONADO para cambiar la foto existente) 
      </td>
    </tr>
    <tr> 
      <td class='form_txt'>Conservar Fotograf&iacute;a actual</td>
      <td class='form_txt'>
        <input type='radio' name='image_function' value='' checked>
        (Este casillero debe ser SELECCIONADO para conservar la foto existente) 
      </td>
    </tr>
    <tr> 
      <td class='form_txt'>Fotograf&iacute;a</td>
      <td class='form_txt'>
        <input type='file' name='userfile'>
        solo archivos jpg, jpeg &amp; png </td>
    </tr>
    <tr> 
      <td colspan='2' class='form_stitulo'>Datos profesionales</td>
    </tr>
    <tr> 
      <td class='form_txt'>Tipo de jugador</td>
      <td class='form_txt'>"
);
        echo 
"<select name='tipo_jugador'> ";
    
$old_tipo_id=$row[Id_tipo];
        
$result2 mysql_query("SELECT desc_tipo,Id_tipo FROM players_tipo ORDER BY desc_tipo ASC"$db);
        while (
$myrow2 mysql_fetch_array($result2)) {
    echo 
"<option value='$myrow2[Id_tipo]' ";
    if(
$old_tipo_id==$myrow2[Id_tipo]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow2[desc_tipo]";
      echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Profesional desde</td>
      <td class='form_txt'>
        <input type='text' name='prof_desde' value='$row[profesional_desde]'>
        (colocar a&ntilde;o con 4 cifras, ej. 1970)</td>
    </tr>
    <tr> 
      <td class='form_txt'>Categor&iacute;a</td>
      <td class='form_txt'>"
);
        echo 
"<select name='categoria'> ";
    
$old_cat_id=$row[Id_categoria];
        
$result3 mysql_query("SELECT desc_categoria,Id_categoria FROM players_categoria ORDER BY desc_categoria ASC"$db);
        while (
$myrow3 mysql_fetch_array($result3)) {
    echo 
"<option value='$myrow3[Id_categoria]' ";
    if(
$old_cat_id==$myrow3[Id_categoria]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow3[desc_categoria]";
      echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Puesto</td>
      <td class='form_txt'>"
);
        echo 
"<select name='puesto'> ";
    
$old_puesto_id=$row[Id_puesto];
        
$result4 mysql_query("SELECT desc_puesto,Id_puesto FROM players_puesto ORDER BY desc_puesto ASC"$db);
        while (
$myrow4 mysql_fetch_array($result4)) {
    echo 
"<option value='$myrow4[Id_puesto]' ";
    if(
$old_puesto_id==$myrow4[Id_puesto]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow4[desc_puesto]";
    echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Vinculaci&oacute;n actual</td>
      <td class='form_txt'>"
);
        echo 
"<select name='vinculacion'> ";
    
$old_vinculo_id=$row[Id_vinculo];
        
$result5 mysql_query("SELECT desc_vinculo,Id_vinculo FROM players_vinculo ORDER BY desc_vinculo ASC"$db);
        while (
$myrow5 mysql_fetch_array($result5)) {
    echo 
"<option value='$myrow5[Id_vinculo]' ";
    if(
$old_vinculo_id==$myrow5[Id_vinculo]){
      echo 
"selected";}
    echo
">";
    echo 
"$myrow5[desc_vinculo]";
      echo
"</option>";}
        echo 
"</SELECT> ";
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Est&aacute; libre?</td>
      <td class='form_txt'>"
);
    
$old_libre=$row[libre];
    echo 
"<input type=\"radio\" name=\"libre\" value=\"Si\" ";if($old_libre=="Si"){echo "checked";}echo">";
    echo 
"Si";
    echo 
"<input type=\"radio\" name=\"libre\" value=\"No\" ";if($old_libre=="No"){echo "checked";}echo">";
    echo 
"No";
$vence_el=cambiaf_a_normal($row[vto_ctto]);
print (
"</td>
    </tr>
    <tr> 
      <td class='form_txt'>Vencimiento del contrato actual</td>
      <td class='form_txt'>
        <input type='text' name='vctto_ano' size='20' value=$vence_el>
        (conservar el formato de la fecha dd/mm/yyyy)</td>
    </tr>
    <tr> 
      <td class='form_txt'>Partidos jugados profesionalmente</td>
      <td class='form_txt'>
        <input type='text' name='partidos' value='$row[partidos_jugados]'>
      </td>
    </tr>
    <tr> 
      <td class='form_txt' colspan='2'>Caracter&iacute;sticas principales<br>
        <textarea name='caracteristicas' cols='60' rows='5' value='$row[caracteristicas]'></textarea>
      </td>
    </tr>
    <tr> 
      <td class='form_txt'>&nbsp;</td>
      <td class='form_txt'>
        <div align='center'>
          <input type='submit' name='Submit' value='Enviar &gt;&gt;&gt;'>
        </div>
      </td>
    </tr>
  </table>
</form>
<p>&nbsp;</p>
</body>
</html>"
); 
continúa....
__________________
Sergio
  #7 (permalink)  
Antiguo 10/11/2003, 16:02
 
Fecha de Ingreso: abril-2002
Ubicación: Argentina
Mensajes: 96
Antigüedad: 22 años
Puntos: 0
Este es el código del procesador del form:
Código PHP:
include ("funciones.php");
include (
"makethumb.txt");

# recogemos en una variable el nombre de BASE DE DATOS
$base="mi_base";

# recogemos en una variable el nombre de la TABLA
$tabla="mi_tabla";

# recoger y adaptar las variables pasadas desde el formulario
$jugador=$el_jugador;
$dbimage=$foto_actual;
$v1=$nombre;
$v2=$nac_fecha;
$v3=$pais;
$v4=$ciudad;
$v5=$e_civil;
$v6=$estudios;
$v7=$pasaporte;
$v8=$estatura;
$v9=$peso;
$v10=$image_function;
$v11=$userfile;
$v12=$tipo_jugador;
$v13=$prof_desde;
$v14=$categoria;
$v15=$puesto;
$v16=$vinculacion;
$v17=$libre;
$v18=$vctto_ano;
$v19=$partidos;
$v20=$caracteristicas;

# establecemos la conexion con el servidor
$conexion=mysql_connect("localhost","user","pass");
#asiganamos la conexión a una base de datos determinada
mysql_select_db($base,$conexion);

# MODIFICAMOS EL REGISTRO

mysql_query("UPDATE $tabla SET nombre_completo='$v1',fecha_nacimiento='$v2',Id_pais='$v3',ciudad='$v4',Id_ecivil='$v5',Id_estudios='$v6',pasaporte='$v7',estatura='$v8',peso='$v9',Id_tipo='$v12',profesional_desde='$v13',Id_categoria='$v14',Id_puesto='$v15',Id_vinculo='$v16',libre='$v17',vto_ctto='$v18',partidos_jugados='$v19',caracteristicas='$v20',ultima_actualizacion=NOW() WHERE (Id_jugador='$jugador')",$conexion);

#comprobamos el resultado de la insercion
# el error CERO significa NO ERROR
# el error 1062 significa Clave duplicada
if (mysql_errno($conexion)==0){echo "<p align='center'>Registro modificado exitosamente</p>";
             }else{
        if (
mysql_errno($conexion)==1062){echo "<h2>No ha podido modificarse el registro<br>Ya existe un campo con este DNI</h2>";
            }else{
            
$numerror=mysql_errno($conexion);
            
$descrerror=mysql_error($conexion);
            echo 
"Se ha producido un error nº $numerror que corresponde a: $descrerror  <br>";
        }

}

# COMPROBAMOS LA IMAGEN
    
if ($image_function=="del"){
        if (
$dbimage !== "nofoto.jpg"){
       
// make sure image is not in use twice+
       
$image_dupe mysql_query("select * from players_datos where foto='$dbimage'");
       
$image_total mysql_num_rows($image_dupe);
       if(
$image_total==1){
            if (
file_exists("/home/virtual/site142/fst/var/www/html/fotos/$dbimage")){
              
unlink("/home/virtual/site142/fst/var/www/html/fotos/$dbimage");
            if (
file_exists("/home/virtual/site142/fst/var/www/html/fotos/thumb_$dbimage")){
              
unlink("/home/virtual/site142/fst/var/www/html/fotos/thumb_$dbimage");}
        }
    
// end if image total !==1
        
}
        
$dbimage "nofoto.jpg";
        
$sql_update "update players_datos set foto='$dbimage' where Id_jugador='$jugador'";
        
$result mysql_query ($sql_update);}
    }

        
// Upload
        
if ($image_function=="up"){
        
$path "/home/virtual/site142/fst/var/www/html/fotos/";
        
$max_size 512000;

        if (
$dbimage!=="nofoto.jpg")
            {
            
$image_dupe mysql_query("select * from players_datos where foto='$dbimage'");
            
$image_total mysql_num_rows($image_dupe);
            if(
$image_total==1){
            if (
file_exists("/home/virtual/site142/fst/var/www/html/fotos/$dbimage")){
            
unlink("/home/virtual/site142/fst/var/www/html/fotos/$dbimage");
            if (
file_exists("/home/virtual/site142/fst/var/www/html/fotos/thumb_$dbimage")){
            
unlink("/home/virtual/site142/fst/var/www/html/fotos/thumb_$dbimage");}
            }
            }
// end if image total !==1
        
}

        if (
is_uploaded_file($userfile)) {
          if (
$userfile_size>$max_size) { echo "<p align=\"center\">Foto demasiado grande!</p>\n"; exit; }
          if ((
$userfile_type=="image/x-png") || ($userfile_type=="image/pjpeg") || ($userfile_type=="image/jpeg")) {
          if (
file_exists("/home/virtual/site142/fst/var/www/html/fotos/$userfile_name")) { echo "<p align=\"center\">Una imagen con este nombre ya se encuentra en el servidor, por favor renombrela y vuelvala a subir!</p><br>\n";$escape=1; }
          if(
$escape!=1){
          
$res move_uploaded_file($userfile$path $userfile_name);
        
// create thumbnail
          
if (file_exists("/home/virtual/site142/fst/var/www/html/fotos/"."thumb_$userfile_name"))
            {
                
unlink("/home/virtual/site142/fst/var/www/html/fotos/thumb_$userfile_name");
                
$thumb=new thumbnail("/home/virtual/site142/fst/var/www/html/fotos/$userfile_name");
                
$thumb->size_auto(75);
                
$thumb->jpeg_quality(75);
                
$thumb->save("/home/virtual/site142/fst/var/www/html/fotos/thumb_$userfile_name"$gd_version);
            } else {
                
$thumb=new thumbnail("/home/virtual/site142/fst/var/www/html/fotos/$userfile_name");
                
$thumb->size_auto(75);
                
$thumb->jpeg_quality(75);
                
$thumb->save("/home/virtual/site142/fst/var/www/html/fotos/thumb_$userfile_name"$gd_version);
            }
        }
        if(
$escape=1){$res="continue";}

        
// Resultant output

        
if (!$res) {
        echo 
"<p align=\"center\">Fallo al subir imagen!<br><br><a href=\"javascript:history.back()\">Intentelo nuevamente</a></p>\n"; exit; }
        } else { echo 
"<p align=\"center\">Extension de Archivo no permitida.<br><br><a href=\"javascript:history.back()\">Intentelo nuevamente</a></p>\n"; exit; }

        if (empty(
$userfile_name))
            {
            
$userfile_name="nofoto.jpg";
            }
        
$sql_update "update players_datos set foto='$userfile_name' where Id_jugador='$jugador'";
        
$result mysql_query ($sql_update);
        }
        }

    
//$sql_select = "update players_datos set foto='$dbimage' where Id_jugador='$jugador'";
    //$result = mysql_query($sql_select);
        //while ($row = mysql_fetch_array($result))
            //{
            //$userfile_name = $row["foto"];
            //}

# cerramos la conexion
mysql_close(); 
El problema ahora está en que cuando subo una nueva imagen o quiero borrar el registro en la BD de la existente, el script me sube la nueva imagen pero no me modifica el registro en la base de datos....
Estoy desorientado con esto...
Agradeceré sus respuestas, por favor... que no lo puedo terminar!!!!
Gracias... Totales
Saludos
__________________
Sergio
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 18:14.