You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Fetch the full list of files from your FTP directory using ftp_nlist().
  2. Filter the list to find files that start with temp (matching your temp% wildcard).
  3. 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_result to avoid errors.
  • ftp_nlist() returns full paths (or filenames, depending on server setup), so we use basename() 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 the temp% wildcard behavior.

内容的提问来源于stack exchange,提问作者Meena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:01:41