如何从PHP的$_POST变量对象中获取上传图片文件名
Hey there! Let's break down how to get that filename you need. The value you're receiving via $_POST['upload-picture'] is a JSON-formatted string, so our first step is to convert it into a PHP array we can work with. Here's a step-by-step solution:
Step 1: Parse the JSON string
Use PHP's json_decode() function to turn the JSON string into an associative array. Adding true as the second parameter ensures we get an array instead of an object, which is often easier to handle for simple data like this:
$uploadData = json_decode($_POST['upload-picture'], true);
Step 2: Access the file path
Your JSON is an array containing one object, so we'll target the first element ([0]) and then the file key to get the full path:
$filePath = $uploadData[0]['file'];
Step 3: Extract the filename
PHP has a built-in function basename() that perfectly handles extracting the filename from a file path. It will ignore everything before the final slash and return just the filename:
$fileName = basename($filePath);
Full Working Example
To make sure we handle edge cases (like invalid JSON or missing data), here's a complete, safe code snippet:
// Retrieve the JSON string from POST $jsonInput = $_POST['upload-picture']; // Parse the JSON into an associative array $uploadArray = json_decode($jsonInput, true); // Validate the parsed data if ($uploadArray && is_array($uploadArray) && isset($uploadArray[0]['file'])) { $fullPath = $uploadArray[0]['file']; $fileName = basename($fullPath); // Use the filename as needed echo "Uploaded filename: " . $fileName; // Outputs: desert.jpg } else { // Handle invalid or missing data echo "Error: Invalid upload data received."; }
This should reliably pull out desert.jpg from your input string. The validation checks help prevent errors if the POST data is ever missing or formatted incorrectly.
内容的提问来源于stack exchange,提问作者Mgs Work

