create folder if not exist on google drive with Curl php - php

I'm uploading files to google drive through Curl php. But now I need to upload all these files in specific folder eg: "My Folder"
I need to get all root folders and evaluate if "My folder" isn't exist on google drive.
For first step. I need get all folders in root of google drive
I've founded this function in ahother post
public function getAllGoogleDriveFolders($token)
{
echo "Buscando Folders en Drive \n";
$folderID = "root";
$folderName = "My Folder";
$baseUrl = "https://www.googleapis.com/drive/v3/files";
$query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='$folderName' and '$folderID' in parents";
$url = $baseUrl . "?q=" . urlencode($query);
//print_r($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
$response = curl_exec($ch);
var_dump($response);die();
curl_close($ch);
}
but this function returns "files": [] empty.
string(72) "{
"kind": "drive#fileList",
"incompleteSearch": false,
"files": []
}
Once I get all folders,
Second step, is evaluate these folders
foreach ($data as $folder) {
if ($folder["name"] != "My Folder") {
//.. steps to create folder with name My folder and get its fodler_id
} else {
// if folder exists in google drive // get the folder id
}
}
Note: I'm using service account for authenticate. and the app is old for this reason I can't use the php service package.
thanks in advance

Related

Can't add thumbnail/image to Facebook App link

I've tried to add a thumbnail to the facebook app link, but can't even find documentation about it. Is it possible?
The current code (PHP/Laravel) gives me a working link, which looks like this: https: // fb.me/1234567890. It writes the app name as well when posted on Facebook, but with no image/thumbnail. I've tried putting an "image" or "thumbnail" parameter in http_build_query, but with no luck.
$url = "https://graph.facebook.com/v2.6/app/app_link_hosts";
$ch = curl_init($url);
# create form post data
$metadata = "?item=" . $request->itemid;
$deepLinkURL = "APP://" . $metadata;
//echo $deepLinkURL;
$androidArray = json_encode(array(array("url" => $deepLinkURL,
"package" => "com.app.package",
"app_name" => "APPNAME")
)
);
$iosArray = json_encode(array(array("url" => $deepLinkURL,
"app_store_id" => 45345345,
"app_name" => "APPNAME")
)
);
$webFallbackArray = json_encode(array("should_fallback" => false));
$formQuery = http_build_query(array("access_token" => "1234567890|XXXXXXXXXXXXXXXX",
"name" => "APPNAME",
"android" => $androidArray,
"ios" => $iosArray,
"thumbnail" => "http://i.imgur.com/upnywSR.jpg",
"web" => $webFallbackArray)
);
$path = base_path() . "/vendor/phpunit/phpunit/build/ca.pem";
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CAINFO, $path);
# options
curl_setopt($ch, CURLOPT_POST, true); //1
curl_setopt($ch, CURLOPT_POSTFIELDS, $formQuery);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# get response
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$jsonResponse = json_decode(curl_exec($ch), true);
curl_close($ch);
# decode response from facebook
$appLinkId = "";
# get appLinkId
foreach ($jsonResponse as $key => $val) {
# get status
if($key == "id") {
$appLinkId = $val;
}
}
# if response is good, need to request canonical URL from appLinkId
$errorMessage = "";
$canonicalUrl = "";
if(!empty($appLinkId)) {
# create another instance of cURL to get the appLink object from facebook using the ID generated by the previous post request
$getAppLinkUrl = "https://graph.facebook.com/" . $appLinkId;
$ch2 = curl_init($getAppLinkUrl);
# cURL options
$queryString = http_build_query(array("access_token" => "206722406330430|XRV38UNZsFfRNNF1EkfikzDWkpk",
"fields" => "canonical_url",
"pretty" => true)
);
/////////////////////
$path = base_path() . "/vendor/phpunit/phpunit/build/ca.pem";
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch2, CURLOPT_CAINFO, $path);
/////////////////
curl_setopt($ch2, CURLOPT_URL, $getAppLinkUrl . "?" . $queryString);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
# get response
// $urlResponseJson = curl_exec($ch2);
$urlJsonResponse = json_decode(curl_exec($ch2), true);
curl_close($ch2);
# decode response from facebook
# parse response to get canonical URL
foreach ($urlJsonResponse as $key => $val) {
# get canonical URL
if($key == "canonical_url") {
$canonicalUrl = $val;
}
}
# check for result
if(empty($canonicalUrl)) {
$errorMessage = "Unable to retreive URL.";
}
} else {
$errorMessage = "Unable to publish appLink.";
}
# encode response back to your app
if(empty($errorMessage)) {
$response = json_encode(array("result" => "success",
"canonical_url" => $canonicalUrl));
} else {
$response = json_encode(array("result" => "failed",
"errorMessage" => $errorMessage));
}
return $response;
I've tried to add a thumbnail to the facebook app link, but can't even find documentation about it. Is it possible?
No.
As https://developers.facebook.com/docs/applinks/hosting-api says,
If your application doesn't have a website for content you want to share to Facebook, you don't have public web URLs which you can annotate to support App Links. For these types of apps, Facebook provides an App Links Hosting API that will host App Links for you.
So if you have public web URLs that you want to share, then you should rather annotate those with the meta tags for App Links – then it will take the thumbnail you specified for those URLs via og:image.
If that is not an option, then you could still try and specify a thumbnail when you share the canonical URL of the App Link object, f.e. via the Feed dialog.

CURLOPT_POSTFIELDS array of folder content

i'm making a curl post to Google text to speech. I have a set of .flac files, that i want to send to Google Text to Speech service, in order to have the content wrote in a txt file.
This is the code i wrote to do this and it works:
$url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=it-IT&key=xxx';
$cont2 = array(
'flac/1.flac',
'flac/2.flac',
'flac/3.flac'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: audio/x-flac; rate=44100'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
foreach ($cont2 as $fn) {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
//var_dump($info);
if ($result === false) {
die(curl_error());
}else{
echo "<br />".$fn." upload ok"."<br />";
file_put_contents("pum.txt", $result, FILE_APPEND);
}
}
It works like a charm, in the "pum.txt" i have all the file content wrote and it's ok.
My problem is that i don't want to add to the the array "cont2", each time, the new name o the files i need to pass to, that there are in the "flac folder".
To avoid that, i use "scandir" method, remove "." and ".." string from the array and give that array to the CURL_OPT_POSTFIELD, but the call to GTT return a empty content.
This is the code i wrote to do that (instead $cont2 array)
$directory = 'flac/';
$cont = array_diff(scandir($directory), array('..', '.', '.DS_Store'));
Print_r of that is the same as $cont2 array:
array(3) {
[3]=>
string(6) "1.flac"
[4]=>
string(6) "2.flac"
[5]=>
string(6) "3.flac"
}
But Google TTS return empty result.
Does anyone please tell me where i'm making mistake?
Kind Regards
Brus
EDIT: use "$cont = glob("$directory/*.flac");" solved the issue. Hope help some others.
scandir() won't include full path information - it'll only return filenames. SO when you're building your array of filenames to loop on and send to google, you'll have to include that directories yourself.
e.g.
$dir = 'flac';
$files = scandir($dir);
foreach($files as $key => $file);
$files[$key] = $dir . '/' . $file;
}
e.g. scan dir will return file1.flac, but you need to have flac/file1.flac. Since you're not including the path information, you're trying to do file_get_contents() on a filename which doesn't exist, and are sending a boolean false (file_get failed) over to google.
As Marc B states you need the directory to the files which is missing. I would just use glob as it will return exactly what you need:
$cont = glob("$directory/*.flac");

foldergrid php client get folder info

I am trying to implement a simple foldergrid php client. I am using the simple php client from the foldergrid api documentation. The client code that I got from the api documentation is:
class FolderGridClient {
protected $_cookieFileLocation = './cookie.txt';
public $_webpage;
public $_status;
public $_location;
const SERVER_HOST = 'https://secure.foldergrid.com';
public function authenticate($username,$password, $domain){
$params = array("domain"=>$domain,"username"=>$username,"password"=>$password);
$this->createCurl(self::SERVER_HOST."/login",$params);
}
public function createDomain($adminemail,$adminpassword, $domainname, $adminfname, $adminlname){
$json = json_encode( array('invite'=>true, 'admin' => array('email'=>$adminemail,'password'=>$adminpassword,'firstname'=>$adminfname,'lastname'=>$adminlname) ) );
$this->createCurl(self::SERVER_HOST."/domain/".$domainname,$json,true);
}
public function uploadFile($file,$name,$parentDuid) {
$fh = fopen($file, "rb");
if($fh) {
$json = json_encode( array('parentDuid'=>$parentDuid, 'name' => $name, 'parts' => 1) );
$this->createCurl(self::SERVER_HOST."/file/provision",$json,true);
if($this->_location){
$headers = array(
'fg-eap: false',
'fg-md5:'.md5_file($file),
'Content-Type: binary/octet-stream'
);
$curl = curl_init();
curl_setopt($curl,CURLOPT_PUT,true);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_URL, $this->_location);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_INFILE, $fh);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file));
curl_setopt( $curl, CURLOPT_VERBOSE, true );
$this->_webpage = curl_exec($curl);
$this->_status = curl_getinfo($curl,CURLINFO_HTTP_CODE);
fclose($fh);
curl_close($curl);
}
}else{
echo "File not found: $file \n";
}
}
public function fetchFolder($pathOrDuid){
$this->createCurl(self::SERVER_HOST."/folder/$pathOrDuid");
return $this->_webpage;
}
public function fetchFile($fileid){
$this->createCurl(self::SERVER_HOST."/file/$fileid");
return $this->_webpage;
}
public function createCurl($url,$postFields = null, $put = false)
{
$s = curl_init();
curl_setopt($s, CURLOPT_VERBOSE, true);
curl_setopt($s,CURLOPT_URL,$url);
curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
curl_setopt($s, CURLOPT_HEADER, TRUE);
curl_setopt($s,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
if($postFields)
{
curl_setopt($s,CURLOPT_POST,true);
if($put) {
curl_setopt($s, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($postFields)));
curl_setopt($s,CURLOPT_CUSTOMREQUEST, "PUT");
}else{
curl_setopt($s, CURLOPT_HTTPHEADER, array('Expect:'));
}
curl_setopt($s,CURLOPT_POSTFIELDS,$postFields);
}
$this->_webpage = curl_exec($s);
$this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
preg_match_all('/^Location:(.*)$/mi', $this->_webpage, $matches);
$this->_location = !empty($matches[1]) ? trim($matches[1][0]) : null;
curl_close($s);
}
}
Using this client, I was able to successfully upload a file to my folder grid root folder. Now I have created a test folder under the root, and I am trying to use the API to get the duid of the folder. I used the following code:
$uname='myuname';
$pwd='mypwd';
$domain='mydomain';
$rootDUID='duidOFRootFolder';
$client = new FolderGridClient;
$client->authenticate( $uname,$pwd,$domain);
if($client->_status < 400){
echo "fetchFolder: " . $client->fetchFolder($domain.'/TestNewFolder') . "<BR>";
}
TestNewFolder is the name of the folder I created using the foldergrid javascript reference client at https://mydomain.foldergrid.com/show/*.html
The root foldername is the same as my domain name, which i think is standard for foldergrid.
However, when I run that code, I always get a folder not found response. I have tried various different permutations of the folder path as an input to the fetchFolder function with no success. so two questions:
1. how should I use the fetchFolder function in the php simple client to get the folder info - specifically the duid.
2. Does anyone have an addition to the php simple client to create a sub folder, once I have discovered the duid of the target folder?
THANKS
When you create a new folder programmatically using the FolderGrid API you assign the immutable DUID which uniquely identifies that folder. One easy method to determine the DUID for any existing folder is to simply open the FolderGrid Web App and right click the folder to choose "Show Info".
To determine an unknown DUID programmatically using API calls, you simply traverse the folder path from a higher folder with a known DUID using calls to Show Folder Details which display the DUIDs of all subfolders. For example, you would execute a GET /folder/DUID on your root folder which will return (among other things) a json array of the names and DUIDs of all the subfolders of your root folder - including TestNewFolder
One useful shortcut is mentioned in the API docs for Show Folder Details which is that you can substitute asterisk '*' for DUID in that call as a shorthand reference to the root folder.
The sample PHP client code uses the name "pathOrDuid" for the parameter to fetchFolder but that's misleading because the call to retrieve a folder's details by path is a distinct call as documented here.
So following Simmerman's suggestions, here is some php code that I used to get the duid of a sub folder if I know the parent folders duid (like '*' for the root folder). I have added the following function to the php simple client that foldergrid provided in their documentation:
public function getSubFolderDuid($parentDuid,$folderName) {
$fetchParent = $this->fetchFolder($parentDuid);
$parentJsonMatch = array();
preg_match("/\{.*\}/",$fetchParent,&$parentJsonMatch);
$returnArray=true;
$parentJsonArray = json_decode($parentJsonMatch[0],$returnArray);
$subFolders = $parentJsonArray['folders'];
foreach($subFolders as $folderData) {
if ($folderData['name'] == $folderName) return $folderData['duid'];
}
return '';
}
obviously there is plenty of room to add error handling to this function in case the parent folder is not returned. This function is assuming the parent folder exists and is returned as json data.
Here is the code I used to call the function:
if($client->_status < 400){
$parentDuid = '*';
$folderName = 'TestNewFolder';
$folderDuid = $client->getSubFolderDuid($parentDuid,$folderName);
echo "$folderName: $folderDuid<br>";
}
With these building blocks I can now build code to traverse the directory tree or find a specific folder duid at an arbitrary depth in the tree.
Thanks for the pointing me in the right direction Simmerman

Setting automatic GIT deployment of PHP project

What I want to do is, to switch from FTP deployment into GIT. I mean, I want to keep automatically keep synced my Bitbucket private repo and my shared webhosting. I googled and found following script to deploy my webserver (based on this article).
// Set these dependant on your BB credentials
$username = 'username';
$password = 'password';
// Grab the data from BB's POST service and decode
$json = stripslashes($_POST['payload']);
$data = json_decode($json);
// Set some parameters to fetch the correct files
$uri = $data->repository->absolute_url;
$node = $data->commits[0]->node;
$files = $data->commits[0]->files;
// Foreach through the files and curl them over
foreach ($files as $file) {
if ($file->type == "removed") {
unlink($file->file);
} else {
$url = "https://api.bitbucket.org/1.0/repositories"
. $uri . "raw/" .$node ."/" . $file->file;
$path = $file->file;
$dirname = dirname($path);
if (!is_dir($dirname)) {
mkdir($dirname, 0775, true);
}
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
}
}
The problem is, this works on simple changesets like 5-10 file change. But when I push the whole project for the first time (for example with 600-700 files and folders) into my bitbucket private profile, this script doesn't work. (just doesn't, no error on errors.log)
What am I missing?
By the way, Can I do something like that:
As we know, Bitbucket can send POST information into an exact url (given by user) directly after a commit has been made. So when deploy.php receives POST, we can get the entire commit as a zip or tar, clean our current files and unzip the new commit into webserver.
Is that possible? If yes then how? Any other good way?
Update
I found the code below for automated deploying php project. The problem is https://bitbucket.org/$username/$reponame/get/tip.zip this url doesnt work on bitbucket private git repo: probably related with authentication (I haven't tested this on public repo) What i need is to get the last commit's zip file and unzip inside my project.
<?
// your Bitbucket username
$username = "edifreak";
// your Bitbucket repo name
$reponame = "canvas-game-demo";
// extract to
$dest = "./"; // leave ./ for relative destination
////////////////////////////////////////////////////////
// Let's get stuff done!
// set higher script timeout (for large repo's or slow servers)
set_time_limit(380);
// download the repo zip file
$repofile = file_get_contents("https://bitbucket.org/$username/$reponame/get/tip.zip");
file_put_contents('tip.zip', $repofile);
unset($repofile);
// unzip
$zip = new ZipArchive;
$res = $zip->open('tip.zip');
if ($res === TRUE) {
$zip->extractTo('./');
$zip->close();
} else {
die('ZIP not supported on this server!');
}
// delete unnecessary .hg files
#unlink("$username-$reponame-tip/.hgignore");
#unlink("$username-$reponame-tip/.hg_archival.txt");
// function to delete all files in a directory recursively
function rmdir_recursively($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rmdir_recursively($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
// function to recursively copy the files
function copy_recursively($src, $dest) {
if (is_dir($src)) {
if($dest != "./") rmdir_recursively($dest);
#mkdir($dest);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..") copy_recursively("$src/$file", "$dest/$file");
}
else if (file_exists($src)) copy($src, $dest);
rmdir_recursively($src);
}
// start copying the files from extracted repo and delete the old directory recursively
copy_recursively("$username-$reponame-tip", $dest);
// delete the repo zip file
unlink("tip.zip");
// Yep, we're done :)
echo "We're done!";
?>
This solution do not provides authentication:
// download the repo zip file
$repofile = file_get_contents("https://bitbucket.org/$username/$reponame/get/tip.zip");
file_put_contents('tip.zip', $repofile);
unset($repofile);
But curl allows it. So a zip archive can be downloaded from a private repository in same way like in first script.
$node = ''; // a node from repo, like c366e96f16...
$fp = fopen($path, 'w');
$ch = curl_init("https://bitbucket.org/$username/$reponame/get/$node.zip");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
I have tested it for my bitbucket account. It's work very well.
If necessary to get last changeset node that we should use bitbucket api GET a list of changesets:
$username = 'login';
$password = 'pass';
$owner = $username; // if user is owner
$repo = 'repo name';
$response = "";
$callback = function($url, $chunk) use (&$response){
$response .= $chunk;
return strlen($chunk);
};
$ch = curl_init("https://api.bitbucket.org/1.0/repositories/$owner/$repo/changesets?limit=1");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent:Mozilla/5.0'));
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_exec($ch);
curl_close($ch);
$changesets = json_decode($response, true);
$node = $changesets['changesets'][0]['node'];
$raw_node = $changesets['changesets'][0]['raw_node'];
print($node . PHP_EOL);
print($raw_node . PHP_EOL);
I recently discovered Capistrano which is a great tool. It was initially developed for ruby but it's also great in combination with php http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/
Based on your update, replace you php files contents with code below:
<?php
// Set these dependant on your BB credentials
$username = '';
$password = '';
// your Bitbucket repo name
$reponame = "";
// extract to
$dest = "./"; // leave ./ for relative destination
// Grab the data from BB's POST service and decode
$json = stripslashes($_POST['payload']);
$data = json_decode($json);
// set higher script timeout (for large repo's or slow servers)
set_time_limit(5000);
// Set some parameters to fetch the correct files
$uri = $data->repository->absolute_url;
$node = $data->commits[0]->node;
$files = $data->commits[0]->files;
// download the repo zip file
$fp = fopen("tip.zip", 'w');
$ch = curl_init("https://bitbucket.org/$username/$reponame/get/$node.zip");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
// unzip
$zip = new ZipArchive;
$res = $zip->open('tip.zip');
if ($res === TRUE) {
$zip->extractTo('./');
$zip->close();
} else {
die('ZIP not supported on this server!');
}
// function to delete all files in a directory recursively
function rmdir_recursively($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir")
rmdir_recursively($dir . "/" . $object); else
unlink($dir . "/" . $object);
}
}
reset($objects);
rmdir($dir);
}
}
// function to recursively copy the files
function copy_recursively($src, $dest) {
if (is_dir($src)) {
if ($dest != "./")
rmdir_recursively($dest);
#mkdir($dest);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..")
copy_recursively("$src/$file", "$dest/$file");
}
else if (file_exists($src))
copy($src, $dest);
rmdir_recursively($src);
}
// start copying the files from extracted repo and delete the old directory recursively
copy_recursively("$username-$reponame-$node", $dest);
// delete the repo zip file
unlink("tip.zip");
?>
Update
Here are repositories of this script (Modified by Me) on
GitHub
Bitbucket

PHP - Run function for each file in a directory passing two parameters

I should start by saying I have no php experience what so ever, but I know this script can't be that ambitious.
I'm using Wordpress' metaWeblog API to batch the creation of several hundred posts. Each post needs a discrete title, a description, and url's for two images, the latter being custom fields.
I have been successful producing one post by manually entering data into the following file;
<?php // metaWeblog.Post.php
$BLOGURL = "http://path/to/your/wordpress";
$USERNAME = "username";
$PASSWORD = "password";
function get_response($URL, $context) {
if(!function_exists('curl_init')) {
die ("Curl PHP package not installed\n");
}
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
return $response;
}
function createPost(){
/*The contents of your post*/
$description = "post description";
/*Forming the content of blog post*/
$content['title'] = $postTitle;
$content['description'] = $description;
/*Pass custom fields*/
$content['custom_fields'] = array(
array( 'key' => 'port_thumb_image_url', 'value' => "$imagePath" ),
array( 'key' => 'port_large_image_url', 'value' => "$imagePath" )
);
/*Whether the post has to be published*/
$toPublish = false;//false means post will be draft
$request = xmlrpc_encode_request("metaWeblog.newPost",
array(1,$USERNAME, $PASSWORD, $content, $toPublish));
/*Making the request to wordpress XMLRPC of your blog*/
$xmlresponse = get_response($BLOGURL."/xmlrpc.php", $request);
$postID = xmlrpc_decode($xmlresponse);
echo $postID;
}
?>
In an attempt to keep this short, here is the most basic example of the script that iterates through a directory and is "supposed" to pass the variables $postTitle, and $imagePath and create the posts.
<?php // fileLoop.php
require('path/to/metaWeblog.Post.php');
$folder = 'foldername';
$urlBase = "images/portfolio/$folder";//truncate path to images
if ($handle = opendir("path/to/local/images/portfolio/$folder/")) {
/*Loop through files in truncated directory*/
while (false !== ($file = readdir($handle))) {
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']); // strip file extension
$postTitle = preg_replace("/\.0|\./", " ", $file_name); // Make file name suitable for post title !LEAVE!
echo "<tr><td>$postTitle</td>";
$imagePath = "$urlBase/$file";
echo " <td>$urlBase/$file</td>";
createPost($postTitle, $imagePath);
}
closedir($handle);
}
?>
It's supposed to work like this,
fileLoop.php opens the directory and iterates through each file
for each file in the directory, a suitable post title(postTitle) is created and a url path(imagePath) to the server's file is made
each postTitle and imagePath is passed to the function createPost in metaWeblog.php
metaWeblog.php creates the post and passes back the post id to finish creating the table row for each file in the directory.
I've tried declaring the function in fileLoop.php, I've tried combining the files completely. It either creates the table with all files, or doesn't step through the directory that way. I'm missing something, I know it.
I don't know how to incorporate $POST_ here, or use sessions as I said I'm very new to programming in php.
You need to update your declaration of the createPost() function so that it takes into account the parameters you are attempting to send it.
So it should be something like this:
function createPost($postTitle, $imagePath){
/*The contents of your post*/
$description = "post description";
...
}
More information about PHP function arguments can be found on the associated manual page.
Once this has been remedied you can use CURL debugging to get more information about your external request. To get more information about a CURL request try setting the following options:
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
curl_setopt($curlHandle, CURLOPT_HEADER, true); // Display headers
curl_setopt($curlHandle, CURLOPT_VERBOSE, true); // Display communication with server
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
print "<pre>\n";
print_r(curl_getinfo($ch)); // get error info
echo "\n\ncURL error number:" .curl_errno($ch); // print error info
echo "\n\ncURL error:" . curl_error($ch);
print "</pre>\n";
The above debug example code is from eBay's help pages.
It should show you if Wordpress is rejecting the request.

Categories