PHP中ftp_put函数无法成功上传图片文件的技术求助
Looking at your code, there are a few critical issues preventing your image from uploading successfully. Let’s break them down and fix each one step by step:
1. Mixed-Up ftp_put Parameter Order
The ftp_put() function requires parameters in this exact order:ftp_put($connectionId, remote_file_path, local_file_path, transfer_mode)
You’ve swapped the local temp file ($tmp) and remote filename ($filename) positions—this is the biggest reason your upload is failing. The function is trying to read a file from your FTP server that doesn’t exist, and write to your local temp directory instead.
2. Wrong Transfer Mode for Images
You’re using FTP_ASCII mode, which is designed for text files. Images are binary data, so using ASCII will corrupt the file during transfer. You need FTP_BINARY instead to preserve the image’s integrity.
3. Missing Critical Error Checks
You don’t verify if the FTP login succeeded, or if the initial file upload to your server’s temporary directory worked. Adding these checks will help you pinpoint exactly where things go wrong.
4. Invalid Remote Path Handling
Your $namesql uses a full URL, but ftp_put needs a server-side file path (absolute or relative to your FTP root directory). You also need to ensure you’re uploading to the correct directory on the FTP host.
Corrected Full Code
<?php // Only run code if form was submitted and file uploaded without errors if (isset($_POST['btn']) && $_FILES['cover']['error'] === UPLOAD_ERR_OK) { $name = $_FILES['cover']['name']; $tmp = $_FILES['cover']['tmp_name']; // Double-check it's a valid image (more reliable than MIME type alone) $image_properties = getimagesize($tmp); if (!$image_properties) { echo "The uploaded file is not a valid image."; exit; } $ftpHost = '*****'; $ftpUsername = '*****'; $ftpPassword = '*****'; // Connect to FTP server $connId = ftp_connect($ftpHost) or die("Couldn't connect to $ftpHost"); // Verify login success $ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword); if (!$ftpLogin) { die("Failed to log in to FTP server with provided credentials."); } // Enable passive mode (required for most modern FTP servers to bypass firewalls) ftp_pasv($connId, true); // Generate unique filename to avoid overwrites $filename = md5($name . microtime()) . substr($name, -4, 4); // Define your target FTP directory (adjust this to match your server's actual path) $remoteDirectory = "/7d97481b1fe66f4b51db90da7e794d9f/"; $remoteFilePath = $remoteDirectory . $filename; // Upload with correct parameter order and binary mode if (ftp_put($connId, $remoteFilePath, $tmp, FTP_BINARY)) { // Build the public URL for the uploaded image $imageUrl = "https://************.com" . $remoteDirectory . $filename; echo "File transfer successful - $name"; echo "<img src='$imageUrl' alt='melipic' width='240px'>"; } else { echo "There was an error while uploading $name"; } // Clean up the FTP connection ftp_close($connId); } elseif (isset($_POST['btn'])) { // Show error if initial file upload to server temp dir failed echo "Failed to upload file to server. Error code: " . $_FILES['cover']['error']; } ?> <form role="form" action="" method="post" enctype="multipart/form-data"> <div class="form-group"> <label style="float:right;" for="exampleInputEmail1">cover profile</label> <input name="cover" type="file" class="form-control" id="exampleInputEmail1"> </div> <button name="btn" type="submit" class="btn btn-shadow btn-success">submit</button> </form>
Key Improvements Explained:
- Parameter Order Fix: Swapped
$tmpand$remoteFilePathinftp_put()to match the required syntax. - Binary Mode: Changed
FTP_ASCIItoFTP_BINARYto ensure image data isn’t corrupted during transfer. - Passive Mode: Enabled
ftp_pasv()—most servers require this to allow uploads through network firewalls. - Error Handling: Added checks for file upload errors, FTP login success, and valid image verification.
- Correct Paths: Used a server-side directory path for FTP uploads, and built the public image URL properly for display.
内容的提问来源于stack exchange,提问作者emanuel

