【发布时间】:2026-01-27 04:55:01
【问题描述】:
到目前为止,我一直在尝试使用 php 通过 twitter api 更新 twitter 个人资料 bg 图像......但没有成功
网上有很多例子,包括这个:
Updating Twitter background via API
还有这个
Twitter background upload with API and multi form data
根本不起作用,大多数人在没有实际测试代码的情况下抛出答案。
我发现直接将图片提交到twitter.com thr html表单,它会工作:
<form action="http://twitter.com/account/update_profile_background_image.xml" enctype="multipart/form-data" method="post">
File: <input type="file" name="image" /><br/>
<input type="submit" value="upload bg">
</form>
(尽管浏览器会提示您输入 twitter 帐户的用户名和密码)
但是,如果我想使用 php 进行相同的过程,它会失败
<?php
if( isset($_POST["submit"]) ) {
$target_path = "";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
// "The file ". basename( $_FILES['myfile']['name']). " has been uploaded<br/>";
} else{
// "There was an error uploading the file, please try again!<br/>";
}
$ch = curl_init('http://twitter.com/account/update_profile_background_image.xml');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, $_POST['name'] . ':' . $_POST['pass']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode(file_get_contents($target_path))));
$rsp = curl_exec($ch);
echo "<pre>" . str_replace("<", "<", $rsp) . "</pre>";
}
?>
<form enctype="multipart/form-data" method="post">
<input type="hidden" name="submit" value="1"/>
name:<input type="text" name="name" value=""/><br/>
pass:<input type="password" name="pass" value=""/><br/>
File: <input type="file" name="myfile" /><br/>
<input type="submit" value="upload bg">
</form>
这段代码的奇怪之处在于..它成功返回了 twitter XML,没有更新了个人资料背景图像。所以最后还是失败了。
非常感谢您阅读本文。如果您能提供帮助,那就太好了。请在抛出答案之前先测试您的代码,非常感谢。
【问题讨论】:
-
“大多数人在没有实际测试代码的情况下抛出答案”这里的大多数人抛出的答案应该有助于将提问者指向正确的方向。由于您链接到的两个答案都被接受,这表明发布者对答案指向的方向感到满意。
-
为什么要手动构建 HTTP auth 标头?尝试使用 CURLOPT_HTTPAUTH 和 CURLOPT_USERPWD,如下例所示:higherpass.com/php/Tutorials/Using-Curl-To-Query-Remote-Servers/…
-
很多时候,接受的答案!=正确的方向。
-
谢谢很多本,我已经更新了代码
-
我已经尝试了几乎所有的 cURL 来让它上传,但无法让它工作。即使使用 shell 命令。