Nueva pregunta

Pregunta:

Fecha: 03-05-2018 19:29:31 (En Español)

Acualizar foto de perfil[Resuelta]

Saludos, en un sistema que estoy desarrollando, para la sección de manejo de usuarios, al registrarse se establece una foto por defecto para el perfil, para actualizar dicha foto dispongo del siguiente formulario:
<form id="form-idioma" class="curriculum" action="actualizarperfil.php" method="post" enctype="multipart/form-data">
<div class="width-75">
<div id="imagen-curriculum">

<?php

$sql = "SELECT * FROM perfil WHERE usuario ='".$usuario."'";

$stmt = $con->prepare($sql);
$results = $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
foreach ($rows as $row) { ?>

<img class="img-responsive img-thumbnail" id="avatar" src="<?php echo $row->img; ?>" width="80" height="80" /><br />
<?php } ?>
</div>
<div class="width-75" style="margin-left:20px">
<p style="width:100%">
Puedes cambiar de foto las veces que quieras, recuerda que es importante tener tu currículum actualizado y con todos los campos
posibles cumplimentados.
</p>
<input type="file" id="archivo" name="archivo" style="float:left" />
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="800000" />
<input type="hidden" name="usuario" id="usuario" value="<?php echo $usuario; ?>">
<small style="float:left;margin-top:8px;margin-left:13px">(*) el tamaño máximo de la foto son 5MB</small>
</div>
</div>
<div>
<button type="submit" class="btn btn-danger">Establecer Foto de Perfil</button>
</div>
</form>

luego, el archivo que se supone hace la actualización:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
include("conexion.php");

$usuario = "";
if(isset($_SESSION['usuario'])) {
$usuario = $_SESSION['usuario'];
}




$nombre_img = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamano = $_FILES['archivo']['size'];

//Si existe imagen y tiene un tamaño correcto
if (($nombre_img == !NULL) && ($_FILES['archivo']['size'] <= 800000))
{
//indicamos los formatos que permitimos subir a nuestro servidor
if (($_FILES["archivo"]["type"] == "image/gif")
|| ($_FILES["archivo"]["type"] == "image/jpeg")
|| ($_FILES["archivo"]["type"] == "image/jpg")
|| ($_FILES["archivo"]["type"] == "image/png"))

// Ruta donde se guardarán las imágenes que subamos
$directorio = "./img/";
// Muevo la imagen desde el directorio temporal a nuestra ruta indicada anteriormente
move_uploaded_file($_FILES['archivo']['tmp_name'],$directorio.$nombre_img);
$nombre_img = $directorio.$nombre_img;

}


if(isset($_POST['usuario'])) {
$user = $_POST['usuario'];
}


$sql2 = " UPDATE perfil SET img =:nombre_img WHERE usuario =:user";
$stmt2 = $con->prepare($sql2);
$stmt2->bindParam(':nombre_img', $nombre_img, PDO::PARAM_STR);
$stmt2->bindParam(':user', $user, PDO::PARAM_STR);
$stmt2->execute();



?>

<script>
alert('La foto de Perfil ha sido agregada exitosamente');

window.location.href='curriculum.php';
</script>

</body>
<html>
sin embargo, lo ejecuto en el servidor y no hace nada, les agradezco mucho la ayuda de antemano.
Etiquetas: Base de Datos - PHP - PHP Avanzado - Sublime Text Votos: 0 - Respuestas: 3 - Vistas: 17 Compartir en: Google Facebook Twitter LinkedIn Link
 

Respuestas:

  • Fecha: 07-05-2018 12:46:48 Este es un código, creado con Dreamweaver, espero que puedas extraer lo que necesitas del el.

    En este código, puede cambiar tu foto de perfil, a la misma vez de que también puedes cambiar tu contraseña, nombre y apellido en una base de datos que ya tengo creada, cual quier cosa que no entiendas me avisas y te ayudo en lo que pueda

    También, te aviso que no le hagas casos a esa linea de código raro, ya que es imagen en SVG, son imágenes vectorizadas

    <?php require_once('Connections/zaikoorcox.php'); ?>
    <?php error_reporting(0); ?>
    <?php
    //initialize the session
    if (!isset($_SESSION)) {
      session_start();
    }
    
    // ** Logout the current user. **
    $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
    if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
      $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
    }
    
    if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
      //to fully log out a visitor we need to clear the session varialbles
      session_destroy();
      $_SESSION['MM_Username'] = NULL;
      $_SESSION['MM_UserGroup'] = NULL;
      $_SESSION['PrevUrl'] = NULL;
      unset($_SESSION['MM_Username']);
      unset($_SESSION['MM_UserGroup']);
      unset($_SESSION['PrevUrl']);
    	
      $logoutGoTo = "salir.php";
      if ($logoutGoTo) {
        header("Location: $logoutGoTo");
        exit;
      }
    }
    ?>
    <?php
    if (!isset($_SESSION)) {
      session_start();
    }
    $MM_authorizedUsers = "";
    $MM_donotCheckaccess = "true";
    
    // *** Restrict Access To Page: Grant or deny access to this page
    function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
      // For security, start by assuming the visitor is NOT authorized. 
      $isValid = False; 
    
      // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
      // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
      if (!empty($UserName)) { 
        // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
        // Parse the strings into arrays. 
        $arrUsers = Explode(",", $strUsers); 
        $arrGroups = Explode(",", $strGroups); 
        if (in_array($UserName, $arrUsers)) { 
          $isValid = true; 
        } 
        // Or, you may restrict access to only certain users based on their username. 
        if (in_array($UserGroup, $arrGroups)) { 
          $isValid = true; 
        } 
        if (($strUsers == "") && true) { 
          $isValid = true; 
        } 
      } 
      return $isValid; 
    }
    
    $MM_restrictGoTo = "index.php";
    if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
      $MM_qsChar = "?";
      $MM_referrer = $_SERVER['PHP_SELF'];
      if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
      if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
      $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
      $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
      header("Location: ". $MM_restrictGoTo); 
      exit;
    }
    ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
    {
      if (PHP_VERSION < 6) {
        $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_update"])) && ($_POST["MM_update"] == "form1")) {
    	if($_POST['sexo']==1){$sexo="Mujer";}else{$sexo="Hombre";}
    	$fecha = $_POST['anio']."-".$_POST['mes']."-".$_POST['dia'];
    	mkdir("archivos/".$_POST['correo']);
    		$nombrefoto=$_FILES['foto']['name'];
    	move_uploaded_file($_FILES['foto']['tmp_name'],"archivos/".$_POST['correo']."/".$nombrefoto);
    	
      $updateSQL = sprintf("UPDATE usuarios SET nombre=%s, apellido=%s, correo=%s, contrasenia=%s, sexo=%s, fechanac=%s, foto=%s, estado=%s, tcreacion=%s WHERE usuarios=%s",
                           GetSQLValueString($_POST['nombre'], "text"),
                           GetSQLValueString($_POST['apellido'], "text"),
                           GetSQLValueString($_POST['correo'], "text"),
                           GetSQLValueString($_POST['contrasenia'], "text"),
                           GetSQLValueString($_POST['sexo'], "text"),
                           GetSQLValueString($_POST['fechanac'], "date"),
                           GetSQLValueString($nombrefoto, "text"),
                           GetSQLValueString($_POST['estado'], "text"),
                           GetSQLValueString($_POST['tcreacion'], "date"),
                           GetSQLValueString($_POST['usuarios'], "int"));
    
      mysql_select_db($database_zaikoorcox, $zaikoorcox);
      $Result1 = mysql_query($updateSQL, $zaikoorcox) or die(mysql_error());
    
      $updateGoTo = "editar.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
        $updateGoTo .= $_SERVER['QUERY_STRING'];
      }
      
    }
    
    $colname_myusuario = "-1";
    if (isset($_SESSION['MM_Username'])) {
      $colname_myusuario = $_SESSION['MM_Username'];
    }
    mysql_select_db($database_zaikoorcox, $zaikoorcox);
    $query_myusuario = sprintf("SELECT * FROM usuarios WHERE correo = %s", GetSQLValueString($colname_myusuario, "text"));
    $myusuario = mysql_query($query_myusuario, $zaikoorcox) or die(mysql_error());
    $row_myusuario = mysql_fetch_assoc($myusuario);
    $totalRows_myusuario = mysql_num_rows($myusuario);
    ?>
    <!doctype html>
    <html lang="en">
      <head>
        <title>Cambiar foto de perfil</title>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <link rel="shortcut icon" href="images/favicon.png" />
      </head>
      <body>
          
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
      </body>
    </html>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html><!-- InstanceBegin template="/Templates/plantillazaikoor.dwt.php" codeOutsideHTMLIsLocked="false" -->
    	<head>
    	<!-- InstanceBeginEditable name="doctitle" -->
    	<title>Zaikoor</title>
    	<meta name="description" content="Designed and developed by Codify Design Studio - codifydesign.com" />
    	<!-- InstanceEndEditable -->
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
    <style type="text/css">a:link{text-decoration:none;}</style>
    		
    		<!-- InstanceBeginEditable name="head" -->
    		<!-- InstanceEndEditable -->
    	</head>
    	<body>
    	
    		<div class="bannerArea">
    			<div class="container">
    				<div class="bannernav"><!-- InstanceBeginEditable name="login" -->    <table height="50"><tr><td><a href="profile.php?=usuario.id=<?php echo $row_myusuario['usuarios']; ?>"><img src="archivos/<?php echo $row_myusuario['correo']; ?>/<?php echo $row_myusuario['foto']; ?>"  id="foto_perfil" title="Perfil" width="50" height="50" /></a></td><td><span class="nombreencabezado"><a href="profile.php"><?php echo $row_myusuario['nombre']; ?> <?php echo $row_myusuario['apellido']; ?></a></span><br />
                  <span class="salirencabezado"><a href="<?php echo $logoutAction ?>">Salir</a></span></td></tr></table><!-- InstanceEndEditable --></div>
    				<div class="toplogo"><a href="inicio.php"> 
    
    
    </svg></a></div>
    				<div style="clear:both;"></div>
    			</div>
    		</div>
    		<div class="topnavigationArea">
    			<div class="container"> 
    				<div class="topnavigationgroup"><!-- InstanceBeginEditable name="menu" -->
                    
    				<table height="40"><tr><td>
                    
                    
                    </td></tr></table>
    				
    				
    				<!-- InstanceEndEditable -->
    					
    				</div>
    				<div style="clear:both;"></div>
    			</div>
    		</div>
    		<div class="contentArea">
    			<div class="container"><!-- InstanceBeginEditable name="content" -->
    				<div class="contentleft">
                    <div class="completa_datos">
    					<h1 align="center"><?php echo $row_myusuario['nombre']; ?>, controla tus datos</h1>
                      <div align="center" class="sexoindex">Si cambias tu Nombre, Apellido o Contrase&ntilde;a. Debes actualizar tu foto de perfil</div>
                      <hr>
    
                        <form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1" enctype="multipart/form-data">
                          <table width="300" height="100" align="center">
                            <tr valign="baseline">
                             
                              <td><input type="text" class="form-control" name="nombre" value="<?php echo htmlentities($row_myusuario['nombre'], ENT_COMPAT, ''); ?>" size="22" /></td>
                            </tr>
                            <tr valign="baseline">
                              
                              <td><input type="text" class="form-control" name="apellido" value="<?php echo htmlentities($row_myusuario['apellido'], ENT_COMPAT, ''); ?>" size="22" /></td>
                            </tr>
                            <tr valign="baseline">
                              
                              <td><input type="password" class="form-control" name="contrasenia" value="<?php echo htmlentities($row_myusuario['contrasenia'], ENT_COMPAT, ''); ?>" size="22" /></td>
                            </tr>
                            <tr valign="baseline">
                              
                              <td><input class="form-control" type="file" name="foto" size="22" /><br></td>
                            </tr>
                            <tr valign="baseline">
                              <td nowrap="nowrap" class="btn btn-info" align="right"><a href="inicio.php">Volver<a/></td>
                              <td align="center"><input class="btn btn-primary" type="submit" value="Guardar" /></td>
                            </tr>
                          </table>
                          <input type="hidden" name="correo" value="<?php echo htmlentities($row_myusuario['correo'], ENT_COMPAT, ''); ?>" />
                          <input type="hidden" name="sexo" value="<?php echo htmlentities($row_myusuario['sexo'], ENT_COMPAT, ''); ?>" />
                          <input type="hidden" name="fechanac" value="<?php echo htmlentities($row_myusuario['fechanac'], ENT_COMPAT, ''); ?>" />
                          <input type="hidden" name="estado" value="<?php echo htmlentities($row_myusuario['estado'], ENT_COMPAT, ''); ?>" />
                          <input type="hidden" name="tcreacion" value="<?php echo htmlentities($row_myusuario['tcreacion'], ENT_COMPAT, ''); ?>" />
                          <input type="hidden" name="MM_update" value="form1" />
                          <input type="hidden" name="usuarios" value="<?php echo $row_myusuario['usuarios']; ?>" />
                        </form>
                        <p>&nbsp;</p>
                    </div>
    				</div>
    			<!-- InstanceEndEditable --><!-- InstanceBeginEditable name="sidebar" -->
    			<div class="contentright">
    				<h2>.</h2>
    			</div>
    			<!-- InstanceEndEditable -->
    			<div style="clear:both;"></div>
    			</div>
    		</div>
    		<div class="footerArea">
    			<div class="container"> 
    				<div class="copyright">&copy; 2018 Zaikoor.</div>
    			</div>
    		</div>
    		
    		
    	</body>
    <!-- InstanceEnd --></html>
    <?php
    mysql_free_result($myusuario);
    ?>
    
      Votos: 1 - Link respuesta
     
  • Fecha: 14-05-2018 12:30:42 Hola,
    Primero te sugiero que leas este articulo.
    De segundo en el código no veo ningún error, entonces te pregunto, que es lo que no hace, subir la imagen y actualiza en la base de datos la ruta?.
    Porque si es así, puede que no tengas permisos de carpeta para que el sistema suba el archivo.

    <?
    $nombre = $file["name"];
    $extension = explode(".", $nombre);
    $ext = $extension[1];
    $tipo = $file["type"];
    $rfoto = $file["tmp_name"];
    $size = $file["size"];
    $destino = "uploads/avatars/";
    $name = $code.".".$ext;
    
    if ($tipo != 'image/jpg' && $tipo != 'image/jpeg' && $tipo != 'image/png' && $tipo != 'image/gif'){
    	// Tipo de imagen invalido.
    	$respuesta["success"] = 0;
    	$respuesta["error"] = 1;
    
    	echo json_encode($respuesta);
    	exit(0);
    }else{
    	if(is_uploaded_file($rfoto)){
    		$destino = $destino.$name;
    		copy($rfoto, $destino);
    	}else{
    		// No hay imagen
    		$respuesta["success"] = 0;
    		$respuesta["error"] = 2;
    
    		echo json_encode($respuesta);
    		exit(0);
    	}
    }
    ?>
    

    Te expongo un poco de mi código para subir imagenes, tal vez puedas guiarte un poco,
    Saludos.
    Cualquier duda aquí estamos.
    @QueCodigo
      Votos: 2 - Link respuesta
     
  • Fecha: 14-05-2018 13:58:52 Hola, correcto, actualiza la ruta pero no subía el archivo al servidor, ya lo solucioné muchas gracias por la ayuda, me sirvió de mucho: aquí está el código funcional:
    <!DOCTYPE HTML>
    <html>
    <head></head>
    <body>
    <?php
    include("conexion.php");
    include("db.php");

    $usuario = "";
    if(isset($_SESSION['usuario'])) {
    $usuario = $_SESSION['usuario'];
    }




    if(isset($_POST['btnsave']))
    {




    $id = $_POST['id'];
    $stmt_edit = $DB_con->prepare('SELECT * FROM perfil WHERE id =:uid');
    $stmt_edit->execute(array(':uid'=>$id));
    $edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
    extract($edit_row);



    $username = $_POST['usuario'];// user name
    // user email

    $imgFile = $_FILES['user_image']['name'];
    $tmp_dir = $_FILES['user_image']['tmp_name'];
    $imgSize = $_FILES['user_image']['size'];

    if($imgFile)
    {

    $upload_dir ='img/'; // upload directory
    $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
    $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
    $userpic = rand(1000,1000000).".".$imgExt;
    if(in_array($imgExt, $valid_extensions))
    {
    if($imgSize < 80000000)
    {

    unlink($upload_dir.$edit_row['userPic']);

    @move_uploaded_file($tmp_dir,$upload_dir.$userpic);
    }
    else
    {
    $errMSG = "El tamaño de la imagen debe ser inferior a 5MB";
    }
    }
    else
    {
    $errMSG = "El tipo de archivo no es permitido, inténtalo nuevamente.";
    }
    }

    else
    {
    // if no image selected the old image remain as it is.
    $userpic = $edit_row['userPic']; // old image from database
    }


    // if no error occured, continue ....
    if(!isset($errMSG))
    {


    // CODIGO QUE GUARDA EN LA TABLA

    // CODIGO QUE GUARDA EN LA TABLA



    $stmt = $DB_con->prepare('UPDATE perfil
    SET userPic=:upic
    WHERE id=:uid');
    $stmt->bindParam(':upic',$userpic);
    $stmt->bindParam(':uid',$id);

    if($stmt->execute()){
    ?>
    <script>
    alert('Foto Actualizada exitosamente');
    window.location.href='curriculum.php';
    </script>
    <?php
    }
    else{
    $errMSG = "No se pudo actualizar la imagen !";
    }

    }


    }

    ?>

    </body>
    <html>
      Votos: 0 - Link respuesta
     
Para participar activamente de la comunidad primero debes autenticarte, ingresa al sistema.Iniciar Sesión
 
frjcbbae garagebible.com