我正在本地Windows 8开发机器上构建一个站点(使用wamp)。我有一个PHP脚本,假设它从我的服务器上的一个目录中获取图像文件,并将它们上传到基于WordPress的网站。当我在目录中有一个文件时,一切都很好。当我修改代码从目录上传多个文件时,只上传了一个图像,我得到一个错误:file_get_content(/path/to/directory/): failed ot open stream. Permission denied in /path/to/script/
这是我收到的错误图像https://i.stack.imgur.com/b6vnF.jpg
以下是适用于目录中一个文件的代码:
global $post;
$rpcurl = get_bloginfo('url') . "/xmlrpc.php";
$username = 'admin';
$password = 'admin';
$blogid = $post->ID; //Post ID
$post_idn = get_post_meta($post->ID, 'VIN', true);
$post_dir = dirname( get_template_directory() ) . "/" . $post_idn;
$file = file_get_contents( $post_dir . "/file.jpg");
$filetype = "image/jpeg";
$filename = "remote_filename.jpg";
xmlrpc_set_type($file,'base64'); // <-- required!
$params = array($blogid,$username,$password,
array('name'=>$filename,'type'=>$filetype,'bits'=>$file,'overwrite'=>false));
$request = xmlrpc_encode_request('wp.uploadFile',$params);
function go($request,$rpcurl){
$ch = curl_init();
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_URL,$rpcurl);
curl_setopt($ch,CURLOPT_POSTFIELDS,$request );
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
}
$result = go($request,$rpcurl);
print_r($result);
以下是假设上载多个图像的代码。
$rpcurl = get_bloginfo('url') . "/xmlrpc.php";
echo $rpcurl;
$username = 'admin';
$password = 'admin';
$blogid = $post->ID; //Post ID
echo $blogid;
$post_idn = get_post_meta($post->ID, 'VIN', true);
echo "<h1>" . $post_idn ."</h1>";
$post_dir = dirname( get_template_directory() ) . "/" . $post_idn;
$fileslist = scandir($post_dir);
foreach ($fileslist as $file) {
$file = file_get_contents( $post_dir . "/" . $file);
$filetype = "image/jpeg";
$filename = "remote_filename.jpg";
xmlrpc_set_type($file,'base64'); // <-- required!
$params = array($blogid,$username,$password,
array('name'=>$filename,'type'=>$filetype,'bits'=>$file,'overwrite'=>false));
$request = xmlrpc_encode_request('wp.uploadFile',$params);
}
function go($request,$rpcurl){
$ch = curl_init();
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_URL,$rpcurl);
curl_setopt($ch,CURLOPT_POSTFIELDS,$request );
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
}
$result = go($request,$rpcurl);
print_r($result);
scandir
将返回.
和..
,以及所有实际文件和子目录。你需要过滤掉这些:
foreach ($fileslist as $file) {
if( $file === '.' || $file === '..' ) {
continue;
}
$file = file_get_contents( $post_dir . "/" . $file);
$filetype = "image/jpeg";
$filename = "remote_filename.jpg";
xmlrpc_set_type($file,'base64'); // <-- required!
$params = array($blogid,$username,$password,
array('name'=>$filename,'type'=>$filetype,'bits'=>$file,'overwrite'=>false));
$request = xmlrpc_encode_request('wp.uploadFile',$params);
}
这里的提示是错误消息:file_get_contents(/path/to/directory/): failed to open stream. Permission denied in /path/to/script/
如果$file
是一个真实的文件,您将看到/path/to/directory/somefile.extension
,而不仅仅是/path/to/directory/
。
此外,您将为每个上传的文件指定相同的文件名,并使用以下行:$filename = "remote_filename.jpg";
因此,无论上传多少个文件,最后都只剩下一个(第一个,因为'overwrite'=>false
)。