Foros del Web » Programando para Internet » PHP »

Problema con Upload CHMOD 777

Estas en el tema de Problema con Upload CHMOD 777 en el foro de PHP en Foros del Web. Antes de nada quiero saludar a todos los miembros de este foro al cuál me acabo de inscribir. Bueno pues tengo un pequeño problema que ...
  #1 (permalink)  
Antiguo 29/07/2008, 12:00
 
Fecha de Ingreso: julio-2008
Mensajes: 5
Antigüedad: 15 años, 9 meses
Puntos: 0
Sonrisa Problema con Upload CHMOD 777

Antes de nada quiero saludar a todos los miembros de este foro al cuál me acabo de inscribir.

Bueno pues tengo un pequeño problema que me imagino que será eso, pequeño, pero debido a mis pocos conocimientos de php pues me estoy agobiando demasiado. Estoy trabajando con una galería de imágenes en flash con administrador de imagenes online, se llama Flash Image Gallery
Código HTML:
http://www.flashimagegallery.com/
y la verdad es que lo estoy usando primero por ser gratuito y segundo por las facilidades para gestionar la propia galería ( para que el propio cliente se la organize).

Bueno pues el quebradero de cabeza lo tengo con los permisos de las imagenes que subo al servidor, por defecto los permisos aparecen en 600 y cuando accedo a través del navegador pues no me permite acceder a dichas imagenes aunque los thumbnails no dan este problema, se cargan bien en la galerí ay son accesibles desde el navegador. He estado revisando los códigos en php que gestionan la galería pero no he encontrado nada ni he visto donde poder añadir algún comando para establecer permisos de chmod a 777.

Os dejo a continuación el código a ver si alguno de vosotr@s ha tenido el mismo problema o es capaz de ver que es lo que faltaría añadir (o restar).

Gracias de antemano.

archivo upload_pics.php
Código:
<?php
//check user
require dirname(__FILE__).'/includes/check_user.php';
require dirname(__FILE__).'/includes/ImageEditor.php';
require dirname(__FILE__).'/includes/functions.php';

//------ exact dimensions for thumbnails used in FIG ------//
$thumb_width = 148;
$thumb_height = 118;

//how thumbs should be processed
// full - a basic thumbnail
// crop - crops thumbnail to fit
$process = $_SESSION['thumbs'];

//ratio of width/height
$thumb_ratio = round($thumb_width/$thumb_height, 2);

$folder = $_POST['folder'];
$name = $_POST['name'];

$pics_xml_add = "";
$attach = $_POST['add'];

//upload pictures
for($x=1; $x<=5; $x++){
	if ($_FILES["file$x"]["size"] > 0) {
		//temp location
		$imgSource = $_FILES["file$x"]["tmp_name"];
		
		//path to gallery folder
		$dir = realpath("../$folder");
		//picture dir vars
		$pic = urldecode(basename($_FILES["file$x"]["name"]));
		//convert spaces to underscores
		$pic = str_replace(" ", "_", $pic);
		//move file 
		if(move_uploaded_file( $imgSource, "$dir/$pic")){
			list($width, $height, $type, $attr) = getimagesize("$dir/$pic");
			//get ratio of width/height
			$ratio = round($width/$height, 2);
			
			if ($process == "crop"){
				//determine the width and height to keep the thumbnail uniform
				//then crop the thumbnail in the center to get our new thumbnail
				if($ratio > $thumb_ratio){
					//picture is too wide so we will need to crop the thumbnails width
					$new_width = ceil(($width*$thumb_width)/$height);
					$new_height = $thumb_height;
					$crop_x = (round($new_width/2))-(round($thumb_width/2));
					$crop_y = 0;
				} elseif($ratio < $thumb_ratio){
					//picture is too high so we will need to crop the thumbnails height
					$new_width = $thumb_width;
					$new_height = ceil(($height*$thumb_height)/$width);
					$crop_x = 0;
					$crop_y = (round($new_height/2))-(round($thumb_height/2));
				} else {
					//the ratio of the image is the same as the thumbnail
					$new_width = $thumb_width;
					$new_height = $thumb_height;
					$crop_x = 0;
					$crop_y = 0;
				}
				
				//time to resize the image and crop it for thumbnail
				$imageEditor = new ImageEditor($pic, $dir . "/");
				//resize
				$imageEditor->resize($new_width, $new_height);
				//crop
				$imageEditor->crop($crop_x, $crop_y, $thumb_width, $thumb_height);
				//save
				$imageEditor->outputFile($pic, $dir . "/thumbs/");
			} else { //make a basic thumbnail
				if($ratio > $thumb_ratio){
					//picture is too wide so we will set the the width to its maximum
					$new_width = $thumb_width;
					$new_height = ceil(($thumb_width*$height)/$width);
				} elseif($ratio < $thumb_ratio){
					//picture is too high so we will set the height to its maximum
					$new_width = ceil(($thumb_height*$width)/$height);
					$new_height = $thumb_height;
				} else {
					//the ratio of the image is the same as the thumbnail
					$new_width = $thumb_width;
					$new_height = $thumb_height;
				}
				
				//time to resize the image and crop it for thumbnail
				$imageEditor = new ImageEditor($pic, $dir . "/");
				//resize
				$imageEditor->resize($new_width, $new_height);
				//save
				$imageEditor->outputFile($pic, $dir . "/thumbs/");
			}
			//create xml for this picture
			$pics_xml_add .= "\t<image location=\"" . $pic . "\" desc=\"" . stripslashes($_POST["desc$x"]) . "\" />\n";
		}
	}
}

//------------- writing new xml ----------------//

//path to xml
$filename = realpath("../$folder/pics.xml");

// make sure xml exists and is writable
if (is_writable($filename)) {
	//open the file for reading and writing
   if (!$handle = fopen($filename, 'r+b')) {
         error("Cannot open file");
         exit;
   }

   //read file
   $contents = fread($handle, filesize($filename));
   
   //rewind file pointer to start and truncate file to zero
   rewind($handle);
   ftruncate($handle, 0);
   
   if ($attach == "start"){
		//attach pictures at beginning of gallery
		$contents = str_replace("<pictures>","",$contents);
		$contents = "<pictures>\n" . $pics_xml_add . $contents;
   } else {
   		//attach pictures at end of gally
		$contents = str_replace("</pictures>","",$contents);
		$contents .= $pics_xml_add . "</pictures>";
   }

   // writing new xml
   if (fwrite($handle, $contents) === FALSE) {
       error("Cannot write to file");
       exit;
   }
   
   fclose($handle);

} else {
   error("pics.xml does not seem to be writable. Check that you have changed its CHMOD settings to 777.");
}

//---------------- done writing new xml --------------//


?>
<html>
<head>
<title><?php echo $name; ?> - Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
p {
	line-height: 1.5em;
}
</style>
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <p align="center"><a href="page_upload_pics.php?name=<?php echo $name; ?>&folder=<?php echo $folder; ?>">Upload More Picture</a></p>
  <p align="center">OR</p>
  <p align="center"><a href="javascript:window.close();">Close this window</a></p>
</body>
</html>
  #2 (permalink)  
Antiguo 29/07/2008, 12:10
Avatar de quinqui  
Fecha de Ingreso: agosto-2004
Ubicación: Chile!
Mensajes: 776
Antigüedad: 19 años, 8 meses
Puntos: 56
Respuesta: Problema con Upload CHMOD 777

Holas miguev y bienvenido :)

Sería bueno que antes de mover tu imagen, verifiques los permisos de escritura de la carpeta de destino con una función como is_writable($folder), de modo de poder modificarlos a 777 de ser el caso.

Si logras modificar los permisos en tiempo de ejecución, recién ahí mueve la imagen temporal a destino. Si no, envía algún mensaje señalando el error.

Ahora, si no tienes permisos para modificar los permisos de la carpeta destino, entonces tendrías que hacer otra cosa. Por ejemplo, y ya que este sistema lo usarían muchos usuarios, tener una sola carpeta madre de destino, ejemplo, "imagenes". Esa carpeta la creas tú manualmente, dándole permisos 777. Dentro de ella, cada vez que haya un nuevo usuario, crear una carpeta para él, también con permisos 777. Esto lo puedes hacer automatizado, pues si la carpeta madre tiene permisos 777, no es necesario corroborarlos. Luego, cuando el usuario quiera subir sus imágenes, lo hará dentro de su carpeta de usuario, la cual tiene permisos 777, por lo cual podrá crear nuevas carpetas y nuevas imágenes sin problemas, en teoría (y recuerda que cada vez que el usuario cree una nueva carpeta en su "cuenta"m tu script debe asignarle permisos 777).

¿Te sirve esto? De pronto no era lo que buscabas xD
__________________
pipus.... vieeeeeji plomius!!!
*quinqui site*
  #3 (permalink)  
Antiguo 29/07/2008, 13:59
 
Fecha de Ingreso: julio-2008
Mensajes: 5
Antigüedad: 15 años, 9 meses
Puntos: 0
De acuerdo Respuesta: Problema con Upload CHMOD 777

Hola quinqui, gracias por tu rápida contestación.

Resulta que la galería se puede organizar en varias categorías en la que cada una tiene su propia carpeta, ahora mismo para las pruebas tengro creada solamente una galería con una única carpeta y he comprobado la opción de establecer a esa sola carpeta los permisos a 777 para que así al añadir los archivos no den problemas de permisos pero resulta que la carpeta ya estaba con los permisos a 777 y al añadir nuevas imagenes estas no mantienen los permisos de la carpeta por lo que al intentar abrirlas me dan fallo.

Tengo que estudiar la opción de verificar los permisos antes de mover el archivo, aunque si te soy sincero no se ni por donde empezar. Lo que más me extraña es que en los thumbnails no de fallo, he estado mirando todo el código pero no he visto nada (tampoco se es lo que estoy buscando exactamente).

Pondría unos enlaces para que se viera mejor el problema pero no me permiten añadir urls hasta pasados 30 días del registro

Bueno voy a seguir a ver si doy con el problema, aunque cualquier ayuda será bien recibida.

Gracias de nuevo quinqui y un saludo.
  #4 (permalink)  
Antiguo 29/07/2008, 14:27
 
Fecha de Ingreso: julio-2008
Mensajes: 5
Antigüedad: 15 años, 9 meses
Puntos: 0
Respuesta: Problema con Upload CHMOD 777

Revisando el código he encontrado los chmod a la hora de crear las galerias, he intentado integrarlo en el php del upload (básicamente haciendo copy&paste :) ) pero no me ha funcionado nada.

Este es el código de los chmod de las entradas de nuevas galerias

Código:
//make new folder and chmod it
mkdir(realpath("../") . '/' . $new_folder, 0777);

//chmod again just to make sure
chmod(realpath("../") . '/' . $new_folder, 0777);

//also make the thumbs folder for this gallery
mkdir(realpath("../") . '/' . $new_folder . '/thumbs', 0777);

//chmod again just to make sure
chmod(realpath("../") . '/' . $new_folder . '/thumbs', 0777);

y este es el codigo doonde yo creo que debería de especificarse el chmode, pero no estoy para nada seguro.

Código:
//upload pictures
for($x=1; $x<=5; $x++){
	if ($_FILES["file$x"]["size"] > 0) {
		//temp location
		$imgSource = $_FILES["file$x"]["tmp_name"];
		
		//path to gallery folder
		$dir = realpath("../$folder");
		//picture dir vars
		$pic = urldecode(basename($_FILES["file$x"]["name"]));
		//convert spaces to underscores
		$pic = str_replace(" ", "_", $pic);
		//move file 
		
		if(move_uploaded_file( $imgSource, "$dir/$pic")){
			list($width, $height, $type, $attr) = getimagesize("$dir/$pic");
			//get ratio of width/height
			$ratio = round($width/$height, 2);
			
			if ($process == "crop"){
				//determine the width and height to keep the thumbnail uniform
				//then crop the thumbnail in the center to get our new thumbnail
				if($ratio > $thumb_ratio){
					//picture is too wide so we will need to crop the thumbnails width
					$new_width = ceil(($width*$thumb_width)/$height);
					$new_height = $thumb_height;
					$crop_x = (round($new_width/2))-(round($thumb_width/2));
					$crop_y = 0;
				} elseif($ratio < $thumb_ratio){
					//picture is too high so we will need to crop the thumbnails height
					$new_width = $thumb_width;
					$new_height = ceil(($height*$thumb_height)/$width);
					$crop_x = 0;
					$crop_y = (round($new_height/2))-(round($thumb_height/2));
				} else {
					//the ratio of the image is the same as the thumbnail
					$new_width = $thumb_width;
					$new_height = $thumb_height;
					$crop_x = 0;
					$crop_y = 0;
				}
				
				//time to resize the image and crop it for thumbnail
				$imageEditor = new ImageEditor($pic, $dir . "/");
				//resize
				$imageEditor->resize($new_width, $new_height);
				//crop
				$imageEditor->crop($crop_x, $crop_y, $thumb_width, $thumb_height);
				//save
				$imageEditor->outputFile($pic, $dir . "/thumbs/");
			} else { //make a basic thumbnail
				if($ratio > $thumb_ratio){
					//picture is too wide so we will set the the width to its maximum
					$new_width = $thumb_width;
					$new_height = ceil(($thumb_width*$height)/$width);
				} elseif($ratio < $thumb_ratio){
					//picture is too high so we will set the height to its maximum
					$new_width = ceil(($thumb_height*$width)/$height);
					$new_height = $thumb_height;
				} else {
					//the ratio of the image is the same as the thumbnail
					$new_width = $thumb_width;
					$new_height = $thumb_height;
				}
				
				//time to resize the image and crop it for thumbnail
				$imageEditor = new ImageEditor($pic, $dir . "/");
				//resize
				$imageEditor->resize($new_width, $new_height);
				//save
				$imageEditor->outputFile($pic, $dir . "/thumbs/");
			}
			//create xml for this picture
			$pics_xml_add .= "\t<image location=\"" . $pic . "\" desc=\"" . stripslashes($_POST["desc$x"]) . "\" />\n";
		}
	}
}

Alguna sugerencia de como poner el mismo de los nombres de la galería para los archivos que se suben???

Siento insitir tanto pero es que es lo último que me falta para terminar una web para un cliente y ya tengo ganas de ponerme con otro proyecto.

Gracias y un saludo.
  #5 (permalink)  
Antiguo 29/07/2008, 14:58
Avatar de quinqui  
Fecha de Ingreso: agosto-2004
Ubicación: Chile!
Mensajes: 776
Antigüedad: 19 años, 8 meses
Puntos: 56
Respuesta: Problema con Upload CHMOD 777

Holas de nuevo

Mira, si el valor de $folder para todas las imágenes a subir es siempre el mismo, debieras hacer la verificación antes de entrar al ciclo. Algo como:

Código PHP:
// la carpeta destino
$folder $_POST['folder'];

// si no existe, intenta crearla
if (!file_exists($folder))
{
  if (!
mkdir($folder0777))
  {
    echo
"No se pudo crear carpeta $folder";
    exit;
  }
}

// si la carpeta no tiene permisos de escritura:
if (!is_writable($folder))
{
  
// intenta crear permisos para carpeta
  
if (!chmod($folder0777))
  {
    echo
"No se pudo cambiar a permisos de escritura en $folder";
    exit;
  }
}

// ahora recien inicias la subida de imagenes
for ($x=1$x<=5$x++)
{
  
// tu codigo

Esa sería una esquematización del cuento.

En todo caso, tu problema a todo esto es que no puedes guardar las imágenes o que una vez guardadas, no las puedes ver en la web? Si fuera así, tienes que fijarte en quién es el usuario propietario de las carpetas, de las imágenes y de tus scripts php. Si el servidor web tiene activado el modo seguro, es probable que no te permita ver imágenes desde tu script, que tiene un usuario propietario, si las imágenes pertenecen a otro usuario propietario... Al menos yo he tenido ese problema y me ha liado bastante. Para solucionarlo, lamentablemente, sólo tuve 2 salidas: o ponerme a subir de nuevo todas las imágenes (borrando las existentes) por ftp, o bien borrar absolutamente todo (scripts, carpetas, imágenes) y subir todo desde cero x_x...
__________________
pipus.... vieeeeeji plomius!!!
*quinqui site*
  #6 (permalink)  
Antiguo 30/07/2008, 02:24
 
Fecha de Ingreso: julio-2008
Mensajes: 5
Antigüedad: 15 años, 9 meses
Puntos: 0
Sonrisa Respuesta: Problema con Upload CHMOD 777

Te agradezco mucho la ayuda que me estas proporcionando.

Te comento, las imágenes si se suben perfectamente al servidor aunque no son accesibles (dichosos permisos), he estado viendo el código que me has proporcionado y eso es justamente lo que necesito pero no para la hora de crear el folder (puse el que incluía el php para que se entendiera mejor el problema). Lo que me imagino que necesito es el chmod a la hora de colocar el archivo en el folder, de todas formas he estado probando eso mismo que tu me has puesto pero susituyendo $folder por $imgSource pero como es lógico, me ha fallado.

¿Cómo podría hacer esto...
Código:
// si la carpeta no tiene permisos de escritura:
if (!is_writable($folder))
{
  // intenta crear permisos para carpeta
  if (!chmod($folder, 0777))
  {
    echo"No se pudo cambiar a permisos de escritura en $folder";
    exit;
  }
}

//
pero aplicandolo a la imagen que subo al servidor y no a la hora de crear la carpeta??

Se que pido mucho pero no se que mas probar, la opción de subir las imagenes por un ftp no me sirve para esta galería ya que tendría que modificar los archivos xml y crear los thumbnails.

No se, intentaré volver a subir todo y revisar lo del servidor en modo seguro y lo de ser el usuario propietario a ver si hay suerte.

De todas formas, muchas gracias por tu ayuda!!!
  #7 (permalink)  
Antiguo 30/07/2008, 08:16
Avatar de quinqui  
Fecha de Ingreso: agosto-2004
Ubicación: Chile!
Mensajes: 776
Antigüedad: 19 años, 8 meses
Puntos: 56
Respuesta: Problema con Upload CHMOD 777

Mira, me puse a revisar el manual de uso de chmod y en efecto, hablan de lo mismo que vimos aquí. Échale una mirada para que le puedas pillar un uso útil para ti. Por cierto, sí se usa con archivos, no sólo con carpetas (yo no sabía eso hasta ahora que lo leí ^^).
__________________
pipus.... vieeeeeji plomius!!!
*quinqui site*
  #8 (permalink)  
Antiguo 31/07/2008, 15:56
 
Fecha de Ingreso: julio-2008
Mensajes: 5
Antigüedad: 15 años, 9 meses
Puntos: 0
Respuesta: Problema con Upload CHMOD 777

Bueno pues este fin de semana aprovecharé y haré pruebas con la documentación que me has facilitado, a ver si hay suerte!!! :)

Ya te contaré.
  #9 (permalink)  
Antiguo 18/06/2011, 20:07
 
Fecha de Ingreso: julio-2009
Mensajes: 3
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Problema con Upload CHMOD 777

hola, yo tambien tengo el mismo problema. Tengo unas imagenes que quiero bajar a un blog, pero el servidor me las carga con otros permisos y no con el 777 que yo quiero , para que se vean, si lo solucionaste podrias enviarme un correo para detallarme como.

Te agradezco pora anticipado la respuesta


[email protected]

edgardo ramos m.
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 14:26.