2016-03-08

Created page with "===Make sure uploads are enabled in PHP==="

New page

<languages/>

MediaWiki supports uploading and integration of media files.

This page describes the technical aspects of this feature, see {{ll|Manual:Image administration}} and [[Help:Images]] for general usage information.

Starting from MediaWiki version 1.1, uploads are initially disabled by default, due to security considerations.

Uploads can be enabled via a configuration setting, although it is recommended that you check certain prerequisites first.

==Prerequisites==

===Make sure uploads are enabled in PHP===

The following needs to be set in ''php.ini'' (which may be located somewhere like ''/etc/php/php.ini'', ''/etc/php4/php.ini'', ''/etc/php5/cli/php.ini'' & ''/etc/php5/apache2/php.ini'' (openSUSE 11.2), ''/usr/local/lib/php.ini'' or on Win32 ''C:\Windows\php.ini''):

<syntaxhighlight lang="bash">

file_uploads = On

</syntaxhighlight>

If this is not set, PHP scripts cannot use the upload functions, and MediaWiki's uploads will not be enabled.

If the ''open_basedir'' directive is set, it must include both the destination upload folder in your MediaWiki installation ("{$IP}/images") and the 'upload_tmp_dir' folder (default system folder if not set).

The addition of the 'upload_tmp_dir' can avoid messages like ''"Could not find file "/var/tmp/php31aWnF"'' (where in this example the 'upload_tmp_dir' is '/var/tmp').

Read more about PHP file uploads at [http://www.php.net/features.file-upload File upload basics] and in particular [http://www.php.net/manual/en/function.move-uploaded-file.php move_uploaded_file].

Note: The formal value for the variable is a [[wikipedia:Boolean_algebra_(logic) | boolean]] expression.

PHP treats each string not recognised as a False value as true, hence the often used "on" value yields the same result.

===Check for Windows and IIS users===

Set <tt>%SystemRoot%\TEMP</tt> to have permissions for the Internet Guest Account (<tt>IUSR</tt>_MachineName, or <tt>IUSR</tt> for IIS 7+): Read, write and execute;

===Check directory security===

The upload directory needs to be configured so that it is not possible for an [[Talk:Configuring_file_uploads#End_User|end user]] to upload and execute other scripts, which could then exploit access to your web directory and damage your wiki or web site.

Set the <tt>/images</tt> folder (or the <tt>/uploads</tt> folder in previous versions) to have permission "755":

*''User'' can read, write and execute;

*''Group'' can read and execute;

*''World'' can read and execute.

If using [[safe_mode]], make sure the directory is owned by the user used for running the php script (that is, the apache user or, in case of suphp, the script owner).

<syntaxhighlight lang="bash">

sudo chown -R www-data:www-data images/

</syntaxhighlight>

If using CentOS 6 or Mageia the owner:group in the chown command should be "apache:apache" instead of "www-data:www-data".

If using [[SELinux]], make sure to adjust the ACLs accordingly (see there).

If using [[suphp]], make sure the umask is set to 0022 (or less) in /etc/suphp.conf.

* '''Restrict directory listing on images folder'''

If you don't want a public user to list your images folder, an option is to set this up in your apache configuration:

<syntaxhighlight lang="apache">

<Directory /var/www/wiki/images>

Options -Indexes

</Directory>

</syntaxhighlight>

=== Check .htaccess file ===

The <tt>images</tt> directory in the MediaWiki installation folder contains an .htaccess file with some configurations on it.

The goal of this file is to make the upload folder more secure, and if you place your upload directory somewhere else, it's recommended to also copy the .htaccess file to the new location, or apply that configuration on the server directly.

However, some of those configurations may cause conflicts or errors, depending on how the server is configured.

Some things to take into account:

* If the server doesn't allow to set or override directives in .htaccess files, accessing any file under that folder may result in a generic "HTTP 500 error". If that's the case, you should comment-out the lines, and apply those directives directly on the server configuration files. The directives that are most likely causing the problems are <code>AddType</code> —which prevents HTML and PHP files from being served as HTML—, and <code>php_admin_flag</code> —which would prevent PHP files from being parsed and executed on the server as such.

* Before MediaWiki 1.27, if you have a custom 404 handler to generate thumbnails with the {{ll|Manual:thumb.php|thumb.php}} script, the rewrite rules in this .htaccess file may disable previous rules, because it lacks the <code>RewriteOptions inherit</code> option ({{phabricator|T67220}}).

==Setting uploads on/off==

{{MW 1.5|and after}}

{{clear}}

In MediaWiki version 1.5 and later, the attribute to be set resides in ''[[LocalSettings.php]]'' and {{wg|EnableUploads}} is set as follows:

<syntaxhighlight lang="php">

$wgEnableUploads = true; # Enable uploads

</syntaxhighlight>

This enables uploads, as one might expect.

To disable them, set the attribute to false:

<syntaxhighlight lang="php">

$wgEnableUploads = false; # Disable uploads

</syntaxhighlight>

{{MW 1.4|and before}}

{{clear}}

In older versions of the software, the attribute to be set resides in ''[[LocalSettings.php]]'', but is backwards, i.e. {{wg|DisableUploads}}.

The default is as shown:

<syntaxhighlight lang="php">

$wgDisableUploads = true; # Disable uploads

</syntaxhighlight>

Invert the value to enable uploads:

<syntaxhighlight lang="php">

$wgDisableUploads = false; # Enable uploads

</syntaxhighlight>

==Using a central repository==

[[InstantCommons]] is a feature, enabled with a configuration change, which gives you immediate access to the millions of free (freely licensed) files in Wikimedia Commons.

== Upload permissions ==

Per default, all registered users can upload files.

To restrict this, you have to change [[Manual:$wgGroupPermissions|$wgGroupPermissions]]:

* To prevent normal users from uploading files: <br /><tt>$wgGroupPermissions['user']['upload'] = false;</tt>

* To create a special group called "uploadaccess", and allow members of that group to upload files: <br /><tt>$wgGroupPermissions['uploadaccess']['upload'] = true;</tt>

* To allow "autoconfirmed" (non-newbie) users to upload files: <br /><tt>$wgGroupPermissions['autoconfirmed']['upload'] = true;</tt>

The right to replace existing files is handled by an extra permission, called <tt>reupload</tt>:

* To prevent normal users from overriding existing files: <br /><tt>$wgGroupPermissions['user']['reupload'] = false;</tt>

* To allow "autoconfirmed" (non-newbie) users to replace existing files: <br /><tt>$wgGroupPermissions['autoconfirmed']['reupload'] = true;</tt>

If a ForeignFileRepo is set, the right to replace those files locally is handled by an special permission, called <tt>reupload-shared</tt>:

* To prevent normal users from overriding filerepo files locally: <br /><tt>$wgGroupPermissions['user']['reupload-shared'] = false;</tt>

* To allow "autoconfirmed" (non-newbie) users to replace filerepo files locally: <br /><tt>$wgGroupPermissions['autoconfirmed']['reupload-shared'] = true;</tt>

See '''[[Manual:User rights]]''' for details on user rights, and [[Manual:Preventing access]] for more information about restricting access.

== Configuring file types ==

You can add [[Manual:$wgFileExtensions|$wgFileExtensions]] in [[LocalSettings.php]] to allow uploads of other desired file types.

For example, you can change the $wgFileExtensions line to look something like

<source lang="php">

$wgFileExtensions = array( 'png', 'gif', 'jpg', 'jpeg', 'doc',

'xls', 'mpp', 'pdf', 'ppt', 'tiff', 'bmp', 'docx', 'xlsx',

'pptx', 'ps', 'odt', 'ods', 'odp', 'odg'

);</source>

or

<source lang="php">

$wgFileExtensions = array_merge( $wgFileExtensions,

array( 'doc', 'xls', 'mpp', 'pdf', 'ppt', 'xlsx', 'jpg',

'tiff', 'odt', 'odg', 'ods', 'odp'

)

);</source>

or

<source lang="php">

# Add new types to the existing list from DefaultSettings.php

$wgFileExtensions[] = 'docx';

$wgFileExtensions[] = 'xls';

$wgFileExtensions[] = 'pdf';

$wgFileExtensions[] = 'mpp';

$wgFileExtensions[] = 'odt';

$wgFileExtensions[] = 'ods';

</source>

However, certain file extensions are blacklisted ([[Manual:$wgFileBlacklist|$wgFileBlacklist]]) and cannot be uploaded even if added to $wgFileExtensions.

To upload files with blacklisted extensions, you must modify the blacklist.

For instance, to allow users to upload executables:

<source lang="php">

$wgFileExtensions[] = 'exe';

$wgFileBlacklist = array_diff( $wgFileBlacklist, array ('exe') );

</source>

In addition, [[Manual:$wgMimeTypeBlacklist|$wgMimeTypeBlacklist]] prevents certain file types based on [[Manual:Mime type detection|MIME type]]; .zip files, for example, are prohibited based on MIME type (MediaWiki version 1.14 up to 1.17).

You can also set [[Manual:$wgStrictFileExtensions|$wgStrictFileExtensions]]

<source lang="php">

$wgStrictFileExtensions = false;

</source>

to allow most types of file to be uploaded. However, blacklisted filetypes and MIME types will still not be permitted.

{{warning|Setting $wgStrictFileExtensions to false, or altering $wgFileBlacklist could result in either you or your users being exposed to security risks.}}

If you are getting the error "The file is corrupt or has an incorrect extension", make sure [[Manual:Mime type detection|mime type detection]] is working properly.

If you decide to allow any kind of file, make sure your mime detection is working and think about enabling virus scans for uploads.

To enable '''zip''' extension (tested in MediaWiki v1.19.23) the following will be necessary in the [[LocalSettings.php]] file:

<source lang="php">

$wgFileExtensions[] = 'zip';

// $wgTrustedMediaFormats[] = 'ARCHIVE';

$wgTrustedMediaFormats[] = 'application/zip';

</source>

== Logon ==

By default anonymous uploads are not allowed.

You must register and logon before the upload file option appears in the toolbox.

== Thumbnailing ==

For information about automatic rendering/thumbnailing of images, see ''[[Manual:Image_thumbnailing]]''.

For problems with thumbnailing, see ''[[Manual:Errors_and_Symptoms#Image_Thumbnails_not_working_and.2For_appearing|Image Thumbnails not working and/or appearing]]''.

{{MW 1.11|and after}}

{{clear}}

If the file is not visual (like an Image or Video) a fileicon is used instead.

These are generated by the <code>iconThumb()</code> function in the File class in the FileRepo group.

Icons stored in "<code>$wgStyleDirectory/common/images/icons/</code>" in a "<code>fileicon-$extension.png</code>"-format.

== Set maximum size for file uploads ==

[[File:Post max size and upload max filesize.jpg|{{dir|{{pagelang}}|left|right}}|100px|thumb|post_max_size and upload_max_filesize in php.ini]]

By default, the configuration code in '''php.ini''' limits the size of files to be uploaded to 2 megabytes (and the maximum size of a post operation to 8 megabytes).

To allow uploading of larger files, edit these parameters in php.ini:

* ''post_max_size'',<ref name="post">[http://de2.php.net/manual/en/ini.core.php#ini.post-max-size post-max-size], PHP Core Manual.</ref> 8 megabytes large by default

* ''upload_max_filesize'',<ref name="upload">[http://de2.php.net/manual/en/ini.core.php#ini.upload-max-filesize upload-max-filesize], PHP Core Manual.</ref> 2 megabytes large by default

This may require root access to the server.

(If you are on a shared host, contact your server administrator.)

'''For Ubuntu:'''

php.ini can be found at this location. <code>/etc/php5/apache2/php.ini</code>{{-}}

; Locating the php.ini file

[[File:Where php.ini is found.png|200px|thumb|{{dir|{{pagelang}}|left|right}}|Typical location in which php.ini may be found.]]

The location of the php.ini file varies on the distribution you are using.

(Try "locate php.ini" or "php -i" to find the location of your config file.)

<ref>For an example of where the php.ini file is, see [http://www.kavoir.com/2009/06/where-is-phpini-located.html Where is php.ini located?].</ref>

It is important to change the php.ini file in the apache2 folder.

For example, there may be a core default php.ini at /etc/php5/cli/php.ini as well as one at /etc/php5/apache2/php.ini.

If you are using mod_php (most common), it is the php.ini file in /etc/php5/apache2 that is important to change.

For php-fastcgi, edit /etc/php5/cgi/php.ini.

;Multiple websites hosted on a server

If you have more than one website hosted on a server and want to change only for Mediawiki, insert into your '''/etc/apache2/sites-enabled/your_wiki_site.com''' inside <Virtual Host>:

<source lang="apache">

php_value upload_max_filesize 100M

php_value post_max_size 100M

</source>

Both above settings also work in a '''.htaccess''' file if your site uses mod_php.

If your site uses PHP >= 5.3 and allows it, you can place php.ini directives in [http://php.net/manual/en/configuration.file.per-user.php .user.ini files] instead.

;web server limits

Your web server may impose further limits on the size of files allowed for upload.

For Apache, one of the relevant settings is ''LimitRequestBody''.

<ref name="limitrequestbody">[http://httpd.apache.org/docs/1.3/mod/core.html#limitrequestbody LimitRequestBody], Apache manual</ref> For Nginx, ''client_max_body_size'' is the relevant setting.<ref name="client_max_body_size">[http://wiki.nginx.org/NginxHttpCoreModule#client_max_body_size client_max_body_size], Nginx manual</ref> For Lighttpd, ''server.max-request-size'' is what may need modification.<ref name="server.max-request-size">[http://redmine.lighttpd.net/wiki/lighttpd/server.max-request-sizeDetails server.max-request-size], Lighthttpd manual</ref>

{{TNT|Note}} You may need to restart Apache or IIS after altering your PHP or web server configuration.

(sudo /etc/init.d/apache2 restart in Linux, for example.)

{{TNT|Note}} You may also need to restart '''php5-fpm''' after altering your PHP (or ngingx server?) configuration.

(sudo /etc/init.d/php5-fpm restart in Linux, for example.)

;uploading too large of files warning

MediaWiki itself issues a warning if you try to upload files larger than what is specified by [[Manual:$wgUploadSizeWarning|$wgUploadSizeWarning]] option.

This is independent of the hard limit imposed by PHP.

MediaWiki also has a [[Manual:$wgMaxUploadSize|$wgMaxUploadSize]] option, but that is currently not enforced for normal uploads (when uploading a local file).

The only way of restricting the upload size is through the use of modifying the php configuration.

; temporary upload limits

Temporary changes to upload limits (when using multiple wikis on a farm, for example) can be altered by adding the lines:

<source lang="php">

ini_set( 'post_max_size', '50M' );

ini_set( 'upload_max_filesize', '50M' );

</source>

to the MediaWiki LocalSettings.php configuration file for each wiki.

In this example the PHP limit is set at 50 Mb.

Note that these settings will not override the maximum settings set above (since the core php.ini and apache2 php.ini files set the absolute maximum).

This method sets maximums that are less than the absolute maximum.

;IIS7 upload limit

{{TNT|Note}} By default, '''IIS7'''<ref>IIS7 is a new revision (version 7.0) of the [[wikipedia:Internet Information Services|Internet Information Services]] that is part of Windows Vista and the next Windows Server version.</ref> on Windows 2008 allows only 30MB to be uploaded via a web application.

Larger files will return a 404 error after the upload.

If you have this problem, you can solve it by increasing the maximum file size by adding the following code to <system.webServer> in the web.config file:

<security>

<requestFiltering>

<requestLimits maxAllowedContentLength="50000000" />

</requestFiltering>

</security>

With the above maxAllowedContentLength, users can upload files that are 50,000,000 bytes (50 MB) in size.

This setting will work immediately without restarting IIS services.

The web.config file is located in the root directory of your web site.

'''To allow uploading files up to 2G''':

'''add''' the following lines to LocalSettings.php:

<source lang="php">

$wgUploadSizeWarning = 2147483647;

$wgMaxUploadSize = 2147483647;

</source>

Also, '''modify''' the following lines in PHP.INI:

<source lang="php">

memory_limit = 2048M (this line may not be necessary)

post_max_size = 2048M

upload_max_filesize = 2048M

</source>

In the IIS web.config file, override the value of maxRequestLength.

For example, the following entry in web.config allows files that are less than or equal to 2 gigabytes (GB) to be uploaded:

<httpRuntime maxRequestLength="2097151" executionTimeout="18000"/>

With IIS 7, you also need to configure it to allow large uploads.

This is found by clicking “Request Filtering > Edit Feature Settings” in the IIS section in the middle of the window.

Set the ”Maximum allowed content length (Bytes)” field to 2147482624.

If you don’t see "Request Filtering" in the IIS section, it needs enabled via Internet Information Services > World Wide Web Services > Security in the "Turn Windows features on or off" area in Control Panel.

If the above tip does not enable large uploads, then open a command prompt and execute this command as well:

%windir%\system32\inetsrv\appcmd set config -section:requestFiltering -requestLimits.maxAllowedContentLength: 2147482624

== Allowing Java JAR Uploads ==

By default, MediaWiki will scan all uploads that appear to be ZIP archives and reject any that contain Java .class files.

This is a security measure to prevent users uploading a malicious Java applet.

'''For non-public sites only''', use the following to disable this check:

<source lang="php">$wgAllowJavaUploads = true;</source>

This setting can be used as a work around for allowing mimetypes to be accepted indiscriminately.

For example, if you attempt to upload a .doc file created by Word 2007, no matter the ext list you provide and mimetype checking you invoke or prohibit, you will receive the message:

:''The file is a corrupt or otherwise unreadable ZIP file. It cannot be properly checked for security.''

.doc files saved by Word 2007 (and possibly later versions) contain a small embedded ZIP archive storing metadata that is not representable in the binary .doc format as used by earlier versions of Word.

This embedded ZIP data confuses the Java archive scanner, causing the .doc file to be rejected.

Files in the newer .docx file format are valid ZIP archives in their entirety, and can be uploaded successfully without setting {{ll|Manual:$wgAllowJavaUploads|$wgAllowJavaUploads}}.

== Uploading directly from a URL ("Sideloading") ==

If you want to allow a user to directly upload files from a URL, instead of from a file on their local computer, set <tt>[[Manual:$wgAllowCopyUploads|$wgAllowCopyUploads]] = true</tt>.

By default, upload by URL are only possible using the [[API:Upload|API]] (or extensions such as [[Extension:UploadWizard|UploadWizard]]).

To make the option usable from Special:Upload, you need to set [[Manual:$wgCopyUploadsFromSpecialUpload|$wgCopyUploadsFromSpecialUpload]] to true as well.

On the upload form, you will then see an additional field for the URL, below the usual filename field.

The URL field is greyed out per default, but can be activated by activating the radiobutton (checkbox) to the left of the field.

In order to use this feature, users must have the [[Manual:$wgGroupPermissions|user right]] <tt>upload_by_url</tt>.

This right was granted to sysops by default until MediaWiki 1.20 but it now needs to be granted explicitly.

To allow this to normal users, set

<source lang="PHP">

$wgGroupPermissions['user']['upload_by_url'] = true;

</source>

Keep in mind that allowing uploads directly from an arbitrary location on the web makes it easier to upload random, unwanted material, and it might be misunderstood as an invitation to upload anything that people might come across on the web.

{{TNT|Note}} PHP's cURL support must be enabled to support this feature. Configure your PHP when installing using the ''--with-curl'' option.

{{TNT|Note}} If your server is accessing internet through a proxy then <tt>[[Manual:$wgHTTPProxy|$wgHTTPProxy]]</tt> needs to be set accordingly. Either you supply it directly or, if your server supplies the environment variable "http_proxy" see your phpinfo(), then you could use the following code in your LocalSettings.php:

<source lang="PHP">

/*

* Proxy to use for CURL requests.

*/

if ( isset( $_ENV['http_proxy'] )) $wgHTTPProxy = $_ENV['http_proxy'];

</source>

== Undeleting images ==

Undeleting images is possible as an option since MediaWiki 1.8, and enabled by default since MediaWiki 1.11.

Prior to MediaWiki 1.11, you can enable undeletion of images by setting [[Manual:$wgSaveDeletedFiles|$wgSaveDeletedFiles]] = true.

Since version 1.11, the behavior is controlled by [[Manual:$wgFileStore|$wgFileStore]], and deleted files are per default stored in [[Manual:$wgUploadDirectory|$wgUploadDirectory]]/deleted.

Since version 1.17, $wgFileStore has been deprecated and {{ll|Manual:$wgDeletedDirectory|$wgDeletedDirectory}} should be used instead.

==Mass uploading==

A number of tools are available for uploading multiple files in one go rather than each file separately:

{{TNT|Bulk Uploading}}

== Upload directory ==

Whenever an image is uploaded, several things are created:

# An article in the file namespace with the name of the file, e.g. File:MyPicture.png. This page is stored and can be edited like any other page.

# The file itself is stored into the folder on the file system, which is configured in {{wg|UploadDirectory}} or into one if its subfolders (see below).

# If necessary and thumbnailing is available, thumbnailed versions of the file will be created when necessary (such as for the usage on the file description page. These are stored in the thumb directory of the image directory, in a separate directory for each main file.

If [[Manual:$wgHashedUploadDirectory|$wgHashedUploadDirectory]] is enabled (by default), MediaWiki creates several subdirectories in the images directory.

If <tt>$wgHashedUploadDirectory</tt> is set to <tt>true</tt>, uploaded files will be distributed into sub-directories of $wgUploadDirectory based on the first two characters of the md5 hash of the filename. (e.g. $IP/images/a/ab/foo.jpg)

Creation of such subdirectories is handled automatically.

This is used to avoid having too many files in one folder because some filesystems don't perform well with large numbers of files in one folder.

If you only maintain a small wiki with few uploaded images, you could turn this off by setting <tt>$wgHashedUploadDirectory = false</tt>, all images are uploaded in $wgUploadDirectory itself. (e.g. $IP/images/foo.jpg)

== Multiwiki sites ==

* Make sure you've changed the site location in LocalSettings.php from, e.g. /var/lib/mediawiki to wherever your installation is, and created a writeable images directory (most of the rest can be symlinked).

Not doing so will mysteriously break image uploads.

== Known problems on Windows ==

Running MediaWiki on Windows server has some restrictions in allowed filenames, due to a PHP bug.

PHP can't handle filenames with non-ascii characters on it correctly, and MediaWiki will refuse to upload files containing such characters to prevent broken uploads ({{phabricator|T3780}}), with the message ''{{int:windows-nonascii-filename}}''.

== Known problems with database names having non-alphanumeric characters ==

{{tracked|T46066}}

If <kbd>[[Manual:$wgDBname|$wgDBname]]</kbd> contains non-alphanumeric characters, uploads may fail with errors like <samp>Could not create directory "mwstore://local-backend/local-public/<path>".</samp>.

This is caused by an internal check for valid container name for file backend, but it's constructed using <kbd>$wgDBname</kbd>.

Since MediaWiki 1.26, it allows uploads when <kbd>$wgDBname</kbd> contains dots.

== See also ==

* [[Manual:Security#Upload_security|Security section Upload security]]

* [[Manual:Configuration settings#Uploads]] for a list of all configuration variables related to file uploads

* [[:Category:Upload variables]] - similar list as a category (ordered alphabetically)

* [[Blank_page#You_see_a_Blank_Page|You see a blank page]] when trying to upload a file

* [[Manual:Disabling file lock manager]] in case it's problematic in your installation

== References ==

<references />

[[Category:MediaWiki configuration{{translation}}|{{PAGENAME}}]]

[[Category:Upload{{translation}}|{{PAGENAME}}]]

Show more