PHP中如何用通配符%匹配FTP文件名前缀并实现告警?
How to Match FTP Files with Wildcards (e.g.,
temp%) in PHP Hey there! The issue with your current code is that file_exists() works for local files only—it can't check files on an FTP server directly. Plus, it doesn't support wildcard patterns like temp%. Let's fix this using PHP's FTP extension functions to handle the server-side file check and wildcard matching.
Here's the step-by-step solution:
- Fetch the full list of files from your FTP directory using
ftp_nlist(). - Filter the list to find files that start with
temp(matching yourtemp%wildcard). - If no matching files exist, trigger your email sending logic.
Updated Code Example
// Login with username and password $conn_id = ftp_connect('your-ftp-server-address'); // Don't forget to define your FTP server! $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // Check if login was successful first if (!$login_result) { die("FTP login failed!"); } // Define your wildcard pattern (looking for files starting with "temp") $targetPrefix = 'temp'; // Get full list of files in the current FTP directory $ftpFiles = ftp_nlist($conn_id, '.'); // Filter files to find those starting with "temp" // Option 1: For PHP 8.0+ using str_starts_with() $matchingFiles = array_filter($ftpFiles, function($file) use ($targetPrefix) { return str_starts_with(basename($file), $targetPrefix); }); // Option 2: For older PHP versions using substr() // $matchingFiles = array_filter($ftpFiles, function($file) use ($targetPrefix) { // return substr(basename($file), 0, strlen($targetPrefix)) === $targetPrefix; // }); // Check if no matching files were found if (empty($matchingFiles)) { // Send your email here $htmlbody = "<head> ..."; // ... rest of your email sending code echo "No files starting with 'temp' found—email sent!"; } else { echo "Found matching files: " . implode(', ', $matchingFiles); } // Close the FTP connection ftp_close($conn_id);
Key Notes:
- Always validate your FTP connection/login before proceeding—added a check for
$login_resultto avoid errors. ftp_nlist()returns full paths (or filenames, depending on server setup), so we usebasename()to get just the filename part for matching.- The
array_filter()with a callback lets us precisely match files starting with your target prefix, which mimics thetemp%wildcard behavior.
内容的提问来源于stack exchange,提问作者Meena
相关产品推荐
相关产品推荐

