Unity3D(C#)向PHP服务器指定文件夹上传文本文件的实现需求
Alright, let's put together this targeted file upload system for your Unity project and PHP server. You already have a basic module that turns strings into text files, so we'll extend that to support uploading to a specified folder—with the server automatically creating the folder if it doesn't exist. Here's how to do it:
First, we'll modify your existing string-to-text-file module to include uploading to a specified folder. We'll use UnityWebRequest to send a multipart form request, which lets us send both the folder name and the text file data in one go.
Here's the updated client code:
using UnityEngine; using UnityEngine.Networking; using System.IO; public class FileUploader : MonoBehaviour { // Replace this with your actual server PHP endpoint URL [SerializeField] private string uploadUrl = "http://your-server-domain.com/upload.php"; // Call this method to upload your text content to a target folder public void UploadTextToFolder(string textContent, string targetFolder, string fileName) { // Create a temporary text file from your string (you might already have this logic) string tempFilePath = Path.Combine(Application.temporaryCachePath, fileName); File.WriteAllText(tempFilePath, textContent); // Start the async upload coroutine StartCoroutine(UploadFileCoroutine(tempFilePath, targetFolder, fileName)); } private IEnumerator UploadFileCoroutine(string filePath, string targetFolder, string fileName) { // Package the folder name and file into a form WWWForm formData = new WWWForm(); formData.AddField("target_folder", targetFolder); formData.AddBinaryData("uploaded_file", File.ReadAllBytes(filePath), fileName, "text/plain"); using (UnityWebRequest webRequest = UnityWebRequest.Post(uploadUrl, formData)) { yield return webRequest.SendWebRequest(); // Handle server response if (webRequest.result != UnityWebRequest.Result.Success) { Debug.LogError($"Upload failed: {webRequest.error}"); } else { Debug.Log($"Upload successful! Server says: {webRequest.downloadHandler.text}"); // Clean up the temporary file to avoid clutter File.Delete(filePath); } } } }
Quick Notes for Unity Side:
- We use
WWWFormto bundle both the target folder name and file data—this makes it easy for the PHP server to access both values. - The temporary file is stored in Unity's cache directory and deleted right after upload.
- Don't forget to replace
uploadUrlwith your actual server endpoint.
On the server side, we need to handle three core tasks: retrieve the target folder, create it if it doesn't exist, and safely store the uploaded file. We'll also add security checks to avoid common vulnerabilities.
Here's the complete upload.php code:
<?php // Enable error reporting for debugging (turn this off in production!) error_reporting(E_ALL); ini_set('display_errors', 1); // Define the base directory where all upload folders will live // Make sure this folder has write permissions for your web server $baseUploadDir = './uploads/'; // Check if we received the required data from the client if (!isset($_POST['target_folder']) || !isset($_FILES['uploaded_file'])) { echo json_encode(['status' => 'error', 'message' => 'Missing required parameters']); exit; } $targetFolder = $_POST['target_folder']; $uploadedFile = $_FILES['uploaded_file']; // Sanitize the folder name to block path traversal attacks (e.g., ../../malicious-folder) $safeFolderName = preg_replace('/[^a-zA-Z0-9_\-]/', '', $targetFolder); $fullTargetDir = $baseUploadDir . $safeFolderName . '/'; // Step 1: Create the target folder if it doesn't exist if (!is_dir($fullTargetDir)) { // Create folder with 0755 permissions (read/write for owner, read-only for others) if (!mkdir($fullTargetDir, 0755, true)) { echo json_encode(['status' => 'error', 'message' => 'Failed to create target folder']); exit; } } // Step 2: Validate the uploaded file if ($uploadedFile['error'] !== UPLOAD_ERR_OK) { $errorMap = [ UPLOAD_ERR_INI_SIZE => 'File is too big (exceeds server upload limit)', UPLOAD_ERR_FORM_SIZE => 'File is too big (exceeds client-side limit)', UPLOAD_ERR_PARTIAL => 'File was only partially uploaded', UPLOAD_ERR_NO_FILE => 'No file was sent', UPLOAD_ERR_NO_TMP_DIR => 'Server is missing a temporary storage folder', UPLOAD_ERR_CANT_WRITE => 'Server can\'t write the file to disk', UPLOAD_ERR_EXTENSION => 'File upload was stopped by a server extension' ]; $errorMsg = $errorMap[$uploadedFile['error']] ?? 'Unknown upload error'; echo json_encode(['status' => 'error', 'message' => $errorMsg]); exit; } // Step 3: Move the uploaded file to its target folder $targetFilePath = $fullTargetDir . basename($uploadedFile['name']); if (move_uploaded_file($uploadedFile['tmp_name'], $targetFilePath)) { echo json_encode(['status' => 'success', 'message' => 'File uploaded successfully', 'file_path' => $targetFilePath]); } else { echo json_encode(['status' => 'error', 'message' => 'Failed to move the uploaded file']); } ?>
Quick Notes for PHP Side:
- Security: We sanitize the folder name to prevent attackers from uploading files to unintended directories.
- Permissions: The
mkdircall usestruefor recursive creation, so parent folders will be created if needed. Ensure your web server has write access to theuploads/directory (runchmod 755 uploads/orchown www-data:www-data uploads/depending on your server setup). - Error Handling: We return JSON responses so the Unity client can easily parse success/error states.
Final Setup Steps:
- Create the base
uploads/directory on your server and set proper write permissions. - Test the system by calling
UploadTextToFolder("Hello World!", "Folder1", "test.txt")from your Unity code. You should seeFolder1created insideuploads/withtest.txtinside it.
内容的提问来源于stack exchange,提问作者Filip

