|
|
chmod (PHP 3, PHP 4, PHP 5) chmod -- Изменяет режим доступа к файлу или каталогу Описаниеbool chmod ( string filename, int mode )
Осуществляет попытку изменения режима доступа файла или каталога,
переданного в параметре filename на режим,
переданный в параметре mode.
Обратите внимание, что значение параметра mode
не переводится автоматически в восьмеричную систему счисления,
поэтому строки (такие, как, например, "g+w") не будут работать
должным образом. Чтобы удостовериться в том, что режим
был установлен верно, предваряйте значение, передаваемое
в параметре mode, нулем (0):
Значение параметра mode состоит
из трех восьмеричных чисел, определяющих уровень доступа
для владельца файла, для группы, в которую входит владелец,
и для других пользователей, соответственно. Число, определяющее
уровень пользователя, может быть вычислено путем суммирования
значений, определяющих права: 1 - доступ на выполнение, 2 -
доступ на запись, 4 - доступ на чтение. Более подробно
о системе прав в системах Unix вы можете узнать с помощью
команд 'man 1 chmod' and 'man 2 chmod'.
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Замечание:
Текущим пользователем является пользователь, от имени
которого выполняется PHP. Возможно, что этот пользователь
будет отличаться от пользователя, под именем которого
вы получаете доступ к командной оболочке или учетной записи FTP.
Замечание: Эта функция не применима для
работы с удаленными файлами, поскольку
файл должен быть доступен через файловую систему сервера.
Замечание:
Когда безопасный режим включён, PHP проверяет имеет ли файл или директория,
с которой вы работаете, такой же UID, как и выполняемый скрипт.
Кроме того, вы не можете устанавливать SUID, SGID и "липкие" биты.
См.также описание функций chown() и
chgrp().
zual__ at gogo dot mn
31-Oct-2007 05:53
greate ftp newfolder=dir;
chmod --dir change 777;
<?php
$ftp_server='server';
$conn_id = ftp_connect("$ftp_server");
ftp_login($conn_id, user, password);
ftp_mkdir($conn_id, dir/dir);
ftp_site($conn_id, 'CHMOD 777, dir/dir');
ftp_close($conn_id);
?>
til_roque at yahoo dot com
10-Oct-2007 08:03
Problem:
you are trying to circumvent SAFE_MODE setting that prevents you from using chmod() on files you uploaded via a regular ftp client, because php may run as user 'nobody', which is not the user from your ftp session.
using ini_set() won't work
using ftp_chmod() won't work either
Solution:
copy file to some temorary directory.
delete original file altogether.
copy temporary file back to original location.
do the chmod()
martin at aarhof dot eu
17-Aug-2007 07:15
Just for those peoples can't remeber the codes 777 and so on I just created a small class :-)
<?php
class Chmod
{
private $dir;
private $modes = array('owner' => 0 , 'group' => 0 , 'public' => 0);
public function setOwnermodes($read,$write,$execute) {
$this->modes['owner'] = $this->setMode($read,$write,$execute);
}
public function setGroupmodes($read,$write,$execute) {
$this->modes['group'] = $this->setMode($read,$write,$execute);
}
public function setPublicmodes($read,$write,$execute) {
$this->modes['public'] = $this->setMode($read,$write,$execute);
}
public function getMode() {
return 0 . $this->modes['owner'] . $this->modes['group'] . $this->modes['public'];
}
private function setMode($r,$w,$e) {
$mode = 0;
if($r) $mode+=4;
if($w) $mode+=2;
if($e) $mode+=1;
return $mode;
}
}
$test = new Chmod;
$test->setOwnermodes(true,true,true);
$test->setGroupmodes(true,true,true);
$test->setPublicmodes(true,true,true);
chmod($dir , $test->getMode());
?>
Ambriel_Angel at www dot ambriels dot net/entry
25-Mar-2007 07:00
<?php
error_reporting(E_ERROR | E_PARSE);
function getmod($filename) {
$val = 0;
$perms = fileperms($filename);
$val += (($perms & 0x0100) ? 0x0100 : 0x0000); $val += (($perms & 0x0080) ? 0x0080 : 0x0000); $val += (($perms & 0x0040) ? 0x0040 : 0x0000); $val += (($perms & 0x0020) ? 0x0020 : 0x0000); $val += (($perms & 0x0010) ? 0x0010 : 0x0000); $val += (($perms & 0x0008) ? 0x0008 : 0x0000); $val += (($perms & 0x0004) ? 0x0004 : 0x0000); $val += (($perms & 0x0002) ? 0x0002 : 0x0000); $val += (($perms & 0x0001) ? 0x0001 : 0x0000); $val += (($perms & 0x40000) ? 0x40000 : 0x0000); $val += (($perms & 0x80000) ? 0x80000 : 0x0000); $val += (($perms & 0x100000) ? 0x100000 : 0x0000); $val += (($perms & 0x0800) ? 0x0800 : 0x0000); $val += (($perms & 0x0400) ? 0x0400 : 0x0000); $val += (($perms & 0x0200) ? 0x0200 : 0x0000); return $val;
}
function hasmod($perms, $permission) {
return (($perms & $permission) == $permission);
}
function pathlock($dir, $listall = false, $testrun = true) {
echo "START @ " . date("F j, Y, h:i:s A") . "<br><br>";
echo ($testrun ? '**Test Run Activated (no changes will be made).**<br><br>' : '**Live Run Activated.**<br><br>');
echo $dir . " is our directory.<br><br>\n";
echo "[...IN PROGRESS...]<br><br>";
$file_list = '';
$stack[] = $dir;
while ($stack) {
$current_dir = array_pop($stack);
if ($dh = opendir($current_dir)) {
while (($file = readdir($dh)) !== false) {
if ($file !== '.' AND $file !== '..') {
$current_file = "{$current_dir}/{$file}";
if (is_dir($current_file)) {
$mode = getmod($current_file); $HasPubRead = hasmod($mode,4);
if ($HasPubRead || $listall) { $ch = true;
$take = 0;
if ($HasPubRead) {
$take = 4; if (!$testrun) {
$ch = chmod($current_file, $mode-$take);
}
}
echo $current_file . ",current=" . decoct($mode) .
(($mode!==$mode-$take) ? ",new=" . decoct($mode-$take) : '') .
($ch ? '' : ',FAILED') . "<br>\n";
} $stack[] = $current_file;
} } } } } echo "<br>COMPLETE @ " . date("F j, Y, h:i:s A") . "<br>\n";
return;
} pathlock($_SERVER["DOCUMENT_ROOT"],false,true); ?>
redeyeleader
10-Feb-2007 08:05
Here's a version that works with PHP 5.x - I use this to watermark images on a shared server.
<?php
$ftpUserName = 'username';
$ftpUserPass = 'userpass';
$ftpServer = 'ftp.example.com';
$ftpConn = ftp_connect($ftpServer);
if (!$ftpConn) {
die("Unable to connect to $ftpServer");
}
if (@ftp_login($conn_id, $ftpUserName, $ftpUserPass)) {
echo "Connected as $ftpUserName @ $ftpServer";
}
else {
echo "Couldn't connect as $ftpUserName";
ftp_close($ftpConn);
die("Closed connection to $ftpServer");
}
echo ftp_chmod($ftpConn, 0666, $ftpFilename) ? "CHMOD successful!" : 'Error';
echo ftp_chmod($ftpConn, 0644, $ftpFilename) ? "CHMOD successful!" : 'Error';
ftp_close($conn_id);
?>
hodgman at ali dot com dot au
17-Jan-2007 09:06
My PHP script refused to delete read-only files (which is probably a good thing), but I couldnt find out how to fix this on windows.
The solution is simple, i just replaced
<?php @unlink( $entry ); ?>
with:
<?php
@chmod( $entry, 0777 );
@unlink( $entry );
?>
chmod isnt supposed to work on windows, but 0777 seems to clear the read only flag, and 0444 seems to set the read only flag.
info at web-in-time dot eu
04-Jan-2007 01:11
As you might have noticed there is a minor bug in webmaster at danopia dot 5gigs dot com's code:
You have to set $ftp_root variable outside the function chmod_open() and have to set it as global within the chmod_file() function.
With these patches the code really works fine. THX!
Ben
webmaster at danopia dot 5gigs dot com
02-Jan-2007 06:20
Thanks for your code, "imoldgreg at o2 dot co dot uk". I am using it for an instalation script that has to CHMOD a bunch of files. I have found it faster to use the same connectino for each, as shown below.
<?php
function chmod_open()
{
$ftp_user_name = 'chmod@XXXXXXXXX.com';
$ftp_user_pass = 'XXXXXXXXXX';
$ftp_root = '/';
$ftp_server = 'localhost';
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
return $conn_id;
}
function chmod_file($conn_id, $permissions, $path)
{
if (ftp_site($conn_id, 'CHMOD ' . $permissions . ' ' . $ftp_root . $path) !== false)
{
return TRUE;
}
else
{
return FALSE;
}
}
function chmod_close($conn_id)
{
ftp_close($conn_id);
}
$conn_id = chmod_open();
echo chmod_file($conn_id, 777, 'master/cache/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/files/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/store/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 766, 'master/config.php') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/images/avatars/upload/') ? 'CHMODed successfully!' : 'Error';
chmod_close($conn_id);
?>
Here, the same FTP connection is used for each CHMOD command, making the execute time lower. This is essential for me, since my script is also copying a bunch of files.
imoldgreg at o2 dot co dot uk
30-Nov-2006 05:32
an update to 'neil at 11 out of 10's code for changing mode using FTP.
changes: proper array added within the function (better for those of us who only need to connect to one ftp server) so only the mode and directory name need to be passed.
the octal added, for completeness and predictable stability.
function changemode($xcite)
{
$ftp_details = array(
ftp_user_name => 'username',
ftp_user_pass => 'password',
ftp_user_root => '/public_html/',
ftp_server => 'ftp.something.org'
);
$path = "public";
$mod = intval($xcite, 8);
// extract ftp details (array keys as variable names)
extract ($ftp_details);
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to chmod $path directory
if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false) {
$success=TRUE;
}
else {
$success=FALSE;
}
// close the connection
ftp_close($conn_id);
return $success;
}
then call it where required, an example:
changemode(777, directory);
if (@copy("$tempname", "$fullfilename")) $done = "yes";
changemode(755, directory);
for those of you, like me, who were looking for a way to make an 'un-hackable' uploader, here's the closest i got, now for a field test, good luck!
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
|
|