chown
-
This function’s solution assumes a Unix-like operating system.
The
chownfunction in PHP will change the owner of a file to a different user ID, assuming the PHP process has sufficient privileges to do so.PHP
chown('/path/to/foobar', 501);
Ruby’s
File.chownclass method is used to accomplish the same task.Ruby
File.chown(501, nil, '/path/to/foobar')
The first argument of
File.chownis the user, the second is the group, and the third is the file. Above, the group is set tonil. This will leave the group unchanged.Changing the Owner by User Name
One nice feature of PHP’s
chownis that the$userargument is mixed. It can accept either a user ID or a user name.PHP
chown('/path/to/foobar', 'herbert');
File.chownfrom Ruby is not as flexible. It only accepts numeric IDs. To change the user by name, we must first perform a lookup to get the user ID from the name.The
Etcmodule from the Ruby Standard Library contains a methodgetpwnamthat returns aStructof information about a user by name, which includes the user ID. We can use this lookup the user ID and then pass it toFile.chown.Ruby
require 'etc' uid = Etc.getpwnam('herbert').uid File.chown(uid, nil, '/path/to/foobar')
Changing the Owner with FileUtils
An alternative to using
FileandEtcto change the owner of a file is to useFileUtils, also from the Ruby Standard Library.FileUtils.chowncan change the owner by either user ID or name.Ruby
require 'fileutils' # equivalent FileUtils.chown(501, nil, '/path/to/foobar') FileUtils.chown('herbert', nil, '/path/to/foobar')
The first argument of
FileUtils.chownis the user, the second is the group, and the third is the file. Above, the group is set tonil. This will leave the group unchanged.Another useful method is
FileUtils.chown_R, whose usage is the same but will recursively change all files in a given path.see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

