Of course. Let's break down dede/media_add.php.

This is a core file in the DedeCMS (织梦内容管理系统) system. Its primary function is to handle the backend process of uploading a new file (an image, a document, a video, etc.) into the system's media library.
High-Level Summary
dede/media_add.php is the server-side script that acts as the processing endpoint for the media upload form. When a user in the DedeCMS admin panel clicks "Upload" in the media manager, this file receives the uploaded file, validates it, processes it, and saves it to the server's designated upload directory. Finally, it records the file's details in the database.
Step-by-Step Workflow
Here is a typical execution flow for this script:
-
Authentication Check: The very first thing the script does is verify that the person accessing it is a logged-in administrator. It checks for a valid session. If not, it redirects to the login page. This is a critical security measure.
(图片来源网络,侵删) -
Receive Upload Data: The script checks if the request was made using the
POSTmethod and if a file was indeed submitted via an HTML form (usually with an input like<input type="file">). -
Configuration Loading: It loads essential DedeCMS configuration settings from
../config.php. This includes:- The base path for uploads (
cfg_medias_dir). - Allowed file types and their MIME types.
- Maximum upload file size.
- Security settings.
- The base path for uploads (
-
File Validation: This is a crucial security step. The script performs several checks on the uploaded file:
- File Size: Is the file size within the configured
upload_max_filesizelimit? - File Type: Does the file's extension (e.g.,
.jpg,.png,.zip) match an allowed type in the configuration? - MIME Type: Does the file's reported MIME type (e.g.,
image/jpeg) match an allowed type? This helps prevent malicious files with disguised extensions. - Upload Error: It checks the PHP
$_FILES['...']['error']code to see if the upload failed for any reason (e.g., partial upload, no temp file).
- File Size: Is the file size within the configured
-
Sanitize Filename: To prevent security issues (like path traversal attacks), the script takes the original filename and sanitizes it. This usually involves removing or replacing special characters, spaces, and non-ASCII characters.
(图片来源网络,侵删) -
Generate Path and Destination: The script constructs the final path where the file will be saved on the server. This path is typically a combination of the configured media directory and a subdirectory based on the current year and month (e.g.,
/uploads/media/2025/10/). This helps organize files and avoid hitting filesystem limits in a single directory. -
Move the File: If all checks pass, the script uses PHP's
move_uploaded_file()function to move the temporary file from its PHP upload location to the final, permanent destination on the server. -
Database Insertion: After the file is successfully saved, the script inserts a new record into the
#@_uploads(ordede_uploads) database table. This record contains important metadata about the file, such as:arcurl: The full URL to the uploaded file.filename: The sanitized filename.filepath: The server path to the file.filesize: The size of the file in bytes.mimetype: The MIME type of the file.uptime: A timestamp of when the file was uploaded.
-
Return Result: The script generates a response, usually in JavaScript format, to inform the front-end of the admin panel whether the upload was successful or not. If successful, it might return the new file's ID and URL for the media manager to use.
Code Structure (Pseudocode)
Here's a simplified representation of what the code inside media_add.php looks like:
<?php
// 1. Authentication and Includes
require_once(dirname(__FILE__)."/config.php");
CheckPurview('media_manage'); // Check if user has permission to manage media
// 2. Check if a file was actually posted
if (empty($_FILES['file']['name'])) {
// Show error: No file selected
}
// 3. Get configuration values
$cfg_medias_dir = $cfg_medias_dir; // e.g., "/uploads/media/"
$allow_types = array('image/jpeg', 'image/png', 'application/zip'); // etc.
$max_size = $cfg_medias_maxsize; // e.g., 2097152 (2MB)
// 4. Validate the uploaded file
if ($_FILES['file']['size'] > $max_size) {
// Show error: File too large
}
if (!in_array($_FILES['file']['type'], $allow_types)) {
// Show error: File type not allowed
}
// 5. Sanitize the filename
$filename = preg_replace("/[^a-zA-Z0-9\._-]/", "", $_FILES['file']['name']);
// 6. Generate the destination path
// e.g., /uploads/media/2025/10/
$year_month = date('Ym');
$target_dir = $cfg_medias_dir . $year_month . "/";
if (!is_dir($target_dir)) {
mkdir($target_dir, 0777, true); // Create directory if it doesn't exist
}
$target_path = $target_dir . $filename;
// 7. Move the file
if (!move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
// Show error: Failed to save file
}
// 8. Insert record into the database
$dsql->Execute("INSERT INTO `#@_uploads` (arcurl, filename, filepath, filesize, mimetype, uptime) VALUES
('". $cfg_medias_dir . $year_month . "/" . $filename ."', '". $filename ."', '". $target_path ."', '". $_FILES['file']['size'] ."', '". $_FILES['file']['type'] ."', '". time() ."')");
// 9. Return success message to the admin panel
echo "<script>alert('Upload successful!'); window.location.href='media_main.php';</script>";
exit();
?>
Common Uses & Purpose
- Adding Images to Articles: When an editor uses the image uploader within the article editor, it's a simplified version of this process.
- Building a Media Library: This is the primary way the central media library is populated with documents, PDFs, videos, and other assets that can be reused across the site.
- File Management: It provides a controlled and secure way for administrators to add files to the website without needing to use FTP.
Security Considerations
This file is a frequent target for attacks if not properly secured. Key security aspects include:
- Authentication: The initial
CheckPurviewcheck is vital. Without it, anyone could upload files. - Input Validation: Strict checks on file type, size, and content (via MIME type) are essential to prevent uploading of malicious scripts (e.g., a PHP web shell).
- Filename Sanitization: The code must sanitize filenames to prevent directory traversal (e.g.,
../../../etc/passwd). - Directory Permissions: The upload directory should have strict permissions (e.g.,
755) to prevent unauthorized execution of uploaded files if, for some reason, a script gets through.
In summary, dede/media_add.php is a fundamental backend handler responsible for the secure and organized addition of new media files to a DedeCMS website.
