PHP使用cURL上传和发送文件

时间:2015-02-20 20:00:21

标签: php wordpress post curl filesystems

我正在尝试将文件上传到WordPress安装,然后将其与其他表单字段中的其他数据一起发送到Lever's API

我可以很好地将数据发送到端点,但文件上传却没有那么多。以下确实上传到wp-content / uploads,但我认为问题出在下一行move_uploaded_file或我在$data数组中传递的位置。


<form enctype="multipart/form-data" method="post" action="<?php echo get_template_directory_uri(); ?>/jobForm.php">
    <input type="file" name="resume">
    <button type="submit">Submit</button>
</form>

<?php
// URL
$url = "https://api.lever.co/v0/postings/XXXX/XXXXXX";

$name = $_POST["name"];
$email = $_POST["email"];
$urls = $_POST["urls"];

$target = "/www/wp-content/uploads/" . basename($_FILES["resume"]["name"]);

move_uploaded_file($_FILES["resume"]["tmp_name"], $target);

// data
$data = array(
    "name" => $name,
    "email" => $email,
    "urls" => $urls,
    "resume" => @$_FILES["resume"]
);

// initiate curl instance, set options, and post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // url
curl_setopt($ch, CURLOPT_POST, true);                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // full data to post                                              
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return results as a string instead of outputting directly                                                             

echo $data["resume"];
// $output 
$output = curl_exec($ch);  
var_dump($output);

// close curl resource to free up system resources 
curl_close($ch);
?>

我尝试将$target变量用于"resume" $data值,但这似乎也不起作用。你可能会说,我不确定这是哪里出错的(我是我的元素中的前端开发人员:D)。

回显$data["resume"]给出一个数组,而回显$target给出文件的位置+名称,如预期的那样。我想我不确定什么我需要在$data数组中传递...有什么想法我在这里做错了什么?如果有帮助,我在提交时不会收到Lever的错误。事实上,它返回200 OK消息并且发布很好,只是没有简历字段!

1 个答案:

答案 0 :(得分:1)

你可以这样做

$localFile = $_FILES[$fileKey]['tmp_name']; 

$fp = fopen($localFile, 'r');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'someurl' . $strFileName); //$strFileName is obvious
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);

if (curl_errno($ch)) {

    $msg = curl_error($ch);
}
else {

    $msg = 'File uploaded successfully.';
}

curl_close ($ch);

$return = array('msg' => $msg);

echo json_encode($return);