|
|
 |
chmod (PHP 3, PHP 4, PHP 5) chmod -- Cambia permisos de un archivo Descripciónint chmod ( string nombre_archivo, int modo )
Trata de cambiar los permisos del archivo especificado por
nombre_archivo a los permisos dados por
modo.
Note que modo no es asumido de forma
automática como un valor octal. Para asegurar que se hace la
operación esperada necesitas anteponer un cero (0) como prefijo
del parámetro modo:
El parámetro modo consiste de tres
componentes de valor octal que especifican las restricciones de acceso
para el propietario, el grupo de usuarios al que pertenece el
propietario del archivo, y todo el mundo, e ese orden. Uno de los
componentes puede ser calculado al agregarle los permisos necesarios
para ese usuario en especifico, El número 1 significa que tiene
permisos de ejecución, el número 2 significa que puede
modificar el contenido del archivo, el número 4 significa que
puede leer el contenido del archivo. Agrege estos valores para
especificar los permisos necesrios. También se puede leer
más acerca de los modos en sistemas Unix con los comandos
'man 1 chmod' y 'man 2 chmod'.
Devuelve TRUE si todo se
llevó a cabo correctamente, FALSE en caso
de fallo.
Nota:
El usuario actual es con el cual PHP se ejecuta. Es probable que
no sea el mismo usuario que usa para accesos FTP o por shell.
Nota: Esta funcion no funcionara con
ficheros remotos ya que
el fichero a examinar tiene que estar disponible desde el sistema de
ficheros del servidor.
Nota:
Cuando safe mode está activado, PHP checa si los archivos o
directorios con lo que quiere trabajar tienen la misma identificación
de usuario (UID) (propietario) que el que está ejecutando el
script. Además no puede cambiar el SUID, SGID y los sticky bits.
Ver también chown() y
chgrp().
Chris (AT) deVidal (DOT) tv
23-Aug-2006 09:44
As noted in a previous post, to use a four-digit chmod (e.g. 1777), you must add a zero to the beginning (01777).
I also discovered this with sgid on directories (02770).
By the way, sgid on dirs is a fantastic way to ensure the group "sticks" on all newly create files and directories created inside that one. That way all members of a particular group can edit files without using 777 permissions.
To use sgid on directories, use 02XXX (where XXX is the normal permissions e.g. 770 (best security) or 775 (OK) or 777 (terrible security) or 771 (world users can traverse the directory to get to a subdirectory where they have rights)).
TenThousandDollarOffer.com
NeoSmart Technologies
25-Jul-2006 03:08
The program mentioned below (CHMOD-Win) has been rewritten since, and CHMOD-Win version 3.0 is available for download at http://neosmart.net/dl.php?id=4
It is a conversion utility for CHMOD on Windows and ACL on Linux, comes in handy for installing commercial scripts or defining security policies.
neil at 11 out of 10
11-Apr-2006 12:20
If you get a warning like chmod(): Operation not permitted in /home/folder/public_html/admin/includefiles/fileupload.php on line 24
You can use the ftp_site() function to send a CHMOD command through.
<?php
$ftp_details['ftp_user_name'] = $row['username'];
$ftp_details['ftp_user_pass'] = $row['password'];
$ftp_details['ftp_root'] = '/public_html/';
$ftp_details['ftp_server'] = 'ftp'.$_SERVER['HTTP_HOST'];
function chmod_11oo10($path, $mod, $ftp_details)
{
extract ($ftp_details);
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false) {
$success=TRUE;
}
else {
$success=FALSE;
}
ftp_close($conn_id);
return $success;
}
?>
The key thing to remember is that the document root and the ftp root are not the same.
e.g. document root may be "/home/folder/public_html/"
but the ftp root might be "/public_html/"
Hope this helps someone. You might need this solution if you are on a shared server.
memp
22-Aug-2005 03:04
If you are storing your mode in a variable like
$mode = 0755;
you will run into the inevitable octal mode problem. An easy way around that is to use the octdec() function.
chmod("some_filename.ext", octdec($mode));
alex at feidesign dot com
01-Apr-2005 04:20
If you cannot chmod files/directories with PHP because of safe_mode restrictions, but you can use FTP to chmod them, simply use PHP's FTP-functions (eg. ftp_chmod or ftp_site) instead. Not as efficient, but works.
info at rvgate dot nl
02-Feb-2005 05:12
When using ftp_rawlist, in order to get the chmod number from the attributes, i use this code:
<?php
function chmodnum($mode) {
$realmode = "";
$legal = array("","w","r","x","-");
$attarray = preg_split("//",$mode);
for($i=0;$i<count($attarray);$i++){
if($key = array_search($attarray[$i],$legal)){
$realmode .= $legal[$key];
}
}
$mode = str_pad($realmode,9,'-');
$trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');
$mode = strtr($mode,$trans);
$newmode = '';
$newmode .= $mode[0]+$mode[1]+$mode[2];
$newmode .= $mode[3]+$mode[4]+$mode[5];
$newmode .= $mode[6]+$mode[7]+$mode[8];
return $newmode;
}
?>
some examples:
drwxr-xr-x => 755
drwxr-xr-x => 755
dr-xr-xr-x => 555
drwxr-xr-x => 755
drwxr-xr-x => 755
drwxr-xr-x => 755
drwxr-xr-x => 755
drwxrwxrwt => 776
drwxr-xr-x => 755
drwxr-xr-x => 755
lrwxrwxrwx => 777
used some of already posted code...
haasje at welmers dot net
27-Nov-2004 12:09
For recursive chmod'ing see the function below.
Only really usefull when chmod'ing a tree containing directories only, jet, since you don't want an executable bit on a regular file. Who completes the function so it's accepting strings like "g+w", and it's as usefull as unix "chmod -R" ? ;-)
<?php
function chmod_R($path, $filemode) {
if (!is_dir($path))
return chmod($path, $filemode);
$dh = opendir($path);
while ($file = readdir($dh)) {
if($file != '.' && $file != '..') {
$fullpath = $path.'/'.$file;
if(!is_dir($fullpath)) {
if (!chmod($fullpath, $filemode))
return FALSE;
} else {
if (!chmod_R($fullpath, $filemode))
return FALSE;
}
}
}
closedir($dh);
if(chmod($path, $filemode))
return TRUE;
else
return FALSE;
}
?>
PerfectWeb
22-Nov-2004 07:58
As noted by others below... 1) you cannot pass a string to chmod() as the mode, and 2) decimals work as well as octals for the mode.
If you need to come up with the mode on the fly (maybe based on user input) and want to use something like:
$mode = '0'.$owner.$group.$public;
you can use your $mode (which is a string) with chmod like this:
<?php
$mode = '0'.$owner.$group.$public;
$mode_dec = octdec($mode); chmod($filename, $mode_dec);
?>
fernando at gym-group dot com
12-Nov-2004 07:10
about chmod,
Problably you have a local server to simulate your scripts before upload them to the server. No matter if you use Apache under windows or IIS , a chmod instruction like chmod($filename,O777) may not work because windows does not handle that kind of permission's format.
So being in your local server, if you have a only read file and you try to erase, it will show that you dont have permissions even when you have already executed your chmod instrucction correctly. Just up the script it must work well in your internet server if it is a linux machine
sobre chmod,
Probablemente usas un servidor local para probar tus scripts antes de subirlos al servidor en internet. No importa si usas Apache bajo windows o IIS, una instruccion como chmod(nombre_archivo,O777) podrá no trabajar por que windows no maneja esa estructura para definir los permisos.
Estando en tu servidor local, si tienes un archivo de solo lectura y tratas de borrarlo, se mostrará un error diciendo que no tienes permisos aún despúes de haber ejecutado chmod correctamente. Sube tu script, si tu servidor es una máquina linux, el script trabajará sin problemas en internet.
Fernando Yepes C.
Oliver Hankeln
01-Jul-2004 08:21
Well, you don't need octals.
You need a value that can easily computed and remembered if printed in octal.
511 (decimal) is the same as 777 (octal).
So it's the same wether you write
chmod("foo",511)
or
chmod("foo",0777)
The latter is just better readable.
raven_25041980 at yahoo dot com
24-May-2004 10:45
If you have a mode as a string, chmod will insanely mess up your permissions. Instead of using
<?php
@chmod($file_or_dir_name, $mode);
?>
use
<?php
@chmod(file_or_dir_name, intval($mode, 8));
?>
where 8 -> the base to convert into. You need octals, baby, for chmod...
More on intval here: http://www.php.net/manual/en/function.intval.php
agrenier at assertex dot com
02-Apr-2004 05:17
If you find that chmod does not work on your file and that a new file cannot be created, first try to chmod the directory where the file is being created to 0666/0777. Then PHP should be able to write/append files with mode 0644.
agrenier at assertex dot com
02-Apr-2004 05:11
This function will chmod a $filename before writing to it if:
1 - It exists
2 - It is not writeable
3 - PHP has permission to chmod files
If PHP can't chmod, then the script will end. Otherwise it will attempt to write to a new file.
<?php
function file_write($filename, $flag, &$content) {
if (file_exists($filename)) {
if (!is_writable($filename)) {
if (!chmod($filename, 0666)) {
echo "Cannot change the mode of file ($filename)";
exit;
};
}
}
if (!$fp = @fopen($filename, $flag)) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($fp, $content) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
if (!fclose($fp)) {
echo "Cannot close file ($filename)";
exit;
}
}
?>
Jazeps Basko
27-Jan-2004 07:37
To convert 'rwxr-xr--' to a number representation of chmod, i use this:
<?php
function chmodnum($mode) {
$mode = str_pad($mode,9,'-');
$trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');
$mode = strtr($mode,$trans);
$newmode = '';
$newmode .= $mode[0]+$mode[1]+$mode[2];
$newmode .= $mode[3]+$mode[4]+$mode[5];
$newmode .= $mode[6]+$mode[7]+$mode[8];
return $newmode;
}
?>
pmichaud at pobox dot com
19-Apr-2003 03:45
In the previous post, stickybit avenger writes:
Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value...
Note that in order to set the sticky bit on a file one must use '01777' (oct) and not '1777' (dec) as the parameter to chmod:
<?php
chmod("file",01777); chmod("file",1777); ?>
Rule of thumb: always prefix octal mode values with a zero.
sticky bit avenger
12-Mar-2003 03:30
Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value. Do NOT do this if you don't have root privileges. When 'sticky bit' is set ONLY the fileuser can delete it afterwards, typically 'httpd' or something like that in case of an upload-script for example. I was unaware of this and actually had to make a script for deleting these files as I could not do this from ftp/ssh even though I did have read/write/execute access to both files and folders. Use simply '0777' or similiar.
Half-Dead at nospam dot com
08-Nov-2002 02:42
[Editor's note:
That is due the fact Win32 systems treat premissions. You do not really have any other levels but read-only.
Maxim]
On WinME with apache chmod also works to a certain limit.
What happens is that apparently only the first number is counted, so 0666 (read-write) is the same as 0777, 0644, 0600, etc, and 0444 (read-only) is the same as 477, 400, etc.
..didn't test 0500 series
FF7Cayn at gmx dot de
27-Oct-2001 05:09
It does work on Windows.
I use Win 98 with the Sambar Server.
The only chmods allowed are the 775 and 666 mod. 775 for non-writeable and 666 for writeable. The only thing is that the usergroups doesn't work.
Note: the 0 at the start doesn't work with windows. use only the decimal kind.
Have fun :)
jon at zend dot com
15-Oct-2001 08:37
if 'mode' is held in a variable and is and octal value you need to convert it to decimal before passing it to the function:
chmod ($filename, octdec($mode))
gnettles2 at home dot com
24-Aug-2001 11:20
Usually when you're trying to write to af file, you'll need to chmod the file to something like 666 or 755. You can use a command to chmod the file for you, which is especially useful when you're making a script where you're setting it up so that your users don't have to peform a bunch of actions to setup the script. When i wrote my news program script, I only had two files. install.php and config.php. All you had to do was chmod install.php to 666 and open it up in a web browser and answer a few questions. The script itself setup the rest of the files and chmodded them for you.
| |
| | Citas célebres | La mayoría de los pavos saben mejor al día siguiente. El de mi madre sabía mejor el día anterior. Rita Rudner Humorista estadounidense (n. 1956) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Animales | | Vaca económica | - ¿Es verdad que la vaca que compró en la feria de ganado le ha salido muy económica?
- Muchísimo, desde que la compré no ha querido comer nada... | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|