php使用curl模拟post传输文件的实例代码

2024-11-01实例代码
212

文件发送的代码如下:
<?
$url = 'http://127.0.0.1/fujian/jieshou.php'; // 目标URL
$filePath2 = iconv("utf-8","gb2312",'D:/MYOA/webroot/fujian/1/副本.txt'); // 文件路
$filePath1 = iconv("utf-8","gb2312",'D:/MYOA/webroot/fujian/1/1.txt'); // 文件路径径
 
$cfile1 = curl_file_create($filePath1);
$cfile2 = curl_file_create($filePath2);
$data = array('file1' => $cfile1,'file2' => $cfile2,'aa'=>'bbbb');
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
 
if(curl_errno($ch)){
    echo 'Error:' . curl_error($ch);
}
else{
    echo 'Response:' . $response;
}
 
curl_close($ch);
 
?>
接口文件代码如下,名称为jiekou.php
<?
 
//$postData = file_get_contents('php://input');
$aa=$_REQUEST["aa"];
$jintiantxt=date("Y-m-d").".txt";
$myfile = fopen($jintiantxt, "a") or die("Unable to open file!");//w
$txt =date("Y-m-d H:i:s")."\r\n".$aa."\r\n";
fwrite($myfile, $txt);
 
fclose($myfile);
 
/*
if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
    $tmpName = $_FILES['file']['tmp_name'];
    $name = basename($_FILES['file']['name']);
    $destination = "./2/{$name}";
 
    if (move_uploaded_file($tmpName, $destination)) {
        echo "File uploaded successfully to: {$destination}";
    } else {
        echo "Failed to move uploaded file.";
    }
} else {
    echo "No file uploaded or error occurred.";
}
*/
$save_dir="D:/MYOA/webroot/fujian/2/";
foreach ($_FILES as $key => $file) {
    if ($file["error"] > 0) {
        echo "错误: " . $file["error"] . "<br />";
    } else {
        echo "文件名: " . $file["name"] . "<br />";
        echo "类型: " . $file["type"] . "<br />";
        echo "大小: " . ($file["size"] / 1024) . " Kb<br />";
        echo "临时文件位置: " . $file["tmp_name"];
   	    // windows下路径有问题时进行处理(这个似乎是错的)
	    // $_FILES[$key]["tmp_name"] = str_replace("\\", "//", $file["tmp_name"]);
        // 保存文件
        if (file_exists($save_dir . $file["name"])) {
            echo $file["name"] . " 已存在. ";
        } else {
            move_uploaded_file($file["tmp_name"], $save_dir . $file["name"]);
            echo "存储到: " . $save_dir . $file["name"];
        }
    }
}
 
?>
 
The End
文件传输

相关推荐