PHP autoload.php not found - php

so this is my code:
<?php
echo 'hey1';
set_time_limit(0);
date_default_timezone_set('UTC');
echo 'hey2';
require __DIR__.'/../vendor/autoload.php';
echo 'hey3';
/////// CONFIG ///////
$username = 'NetsGets';
$password = 'NetsGetsWebsite';
$debug = true;
$truncatedDebug = false;
//////////////////////
$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
try {
$ig->login($username, $password);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
exit(0);
}
try {
$feed = $ig->discover->getExploreFeed();
// Let's begin by looking at a beautiful debug output of what's available in
// the response! This is very helpful for figuring out what a response has!
$feed->printJson();
// Now let's look at what properties are supported on the $feed object. This
// works on ANY object from our library and will show what functions and
// properties are supported, as well as how to call the functions! :-)
$feed->printPropertyDescriptions();
// The getExploreFeed() has an "items" property, which we need. As we saw
// above, we should get it via "getItems()". The property list above told us
// that it will return an array of "Item" objects. Therefore it's an ARRAY!
$items = $feed->getItems();
// Let's get the media item from the first item of the explore-items array...!
$firstItem = $items[0]->getMedia();
// We can look at that item too, if we want to... Let's do it! Note that
// when we list supported properties, it shows everything supported by an
// "Item" object. But that DOESN'T mean that every property IS available!
// That's why you should always check the JSON to be sure that data exists!
$firstItem->printJson(); // Shows its actual JSON contents (available data).
$firstItem->printPropertyDescriptions(); // List of supported properties.
// Let's look specifically at its User object!
$firstItem->getUser()->printJson();
// Okay, so the username of the person who posted the media is easy... And
// as you can see, you can even chain multiple function calls in a row here
// to get to the data. However, be aware that sometimes Instagram responses
// have NULL values, so chaining is sometimes risky. But not in this case,
// since we know that "user" and its "username" are always available! :-)
$firstItem_username = $firstItem->getUser()->getUsername();
// Now let's get the "id" of the item too!
$firstItem_mediaId = $firstItem->getId();
// Finally, let's get the highest-quality image URL for the media item!
$firstItem_imageUrl = $firstItem->getImageVersions2()->getCandidates()[0]->getUrl();
// Output some statistics. Well done! :-)
echo 'There are '.count($items)." items.\n";
echo "The first item has media id: {$firstItem_mediaId}.\n";
echo "The first item was uploaded by: {$firstItem_username}.\n";
echo "The highest quality image URL is: {$firstItem_imageUrl}.\n";
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
}
?>
After running this code, the only things that print are hey1 and hey2. Based on my own reasearch, I concluded that autoload.php is one of the necessery files for the composer to run, but it also seems to be the problem that stops the php from running. This code is from https://github.com/mgp25/Instagram-API. Pease help!

1) If you don't have Composer, install it. For example:
sudo apt-get install composer -y
2) Run:
composer require mgp25/instagram-php
3) Type:
cd vendor
ls
The very first file you see listed should be autoload.php.

Related

Xero Create new Tracking Option

I can't seem to get tracking options created, the Category itself is creating fine.
However firstly - I should point out I believe there is a bug in the Xero-API for PHP, when debugging adding an option according to the documentation here the PUT should be
https://api.xero.com/api.xro/2.0/TrackingCategories/{TrackingCategoryID}/Options
However in the php lib it is
https://api.xero.com/api.xro/2.0/TrackingCategories/{TrackingCategoryID}/TrackingOptions
Even when that is resolved, I get no error however not tracking Option is created, any ideas?
$options = ['US', 'UK'];
$title = 'Region';
$trackingCategory = null;
if(!$trackingCategory) {
$trackingCategory = new \XeroPHP\Models\Accounting\TrackingCategory($xero);
$trackingCategory->setName($title);
$trackingCategory->save();
}
try {
foreach($options as $option) {
$to = new \XeroPHP\Models\Accounting\TrackingCategory\TrackingOption($xero);
$to->setName($option);
$trackingCategory->setOption($option);
$trackingCategory->save();
}
} catch(\Exception $e) {
$this->logger()->info($e->getTraceAsString());
$this->logger()->info("TRACKING: ". $e->getMessage());
return false;
}
So this would appear it is a bug as reported here
The source has not been fixed, however the above link resolves the problem for anyone else searching.
Changing TrackingOptions to Options in XeroPHP worked soughta... but I was still getting a different error. Ended up creating the Option manually
Note: $this->_xero_oauth_object is my \XeroPHP\Application\PublicApplication from authentication
// Create the URL object based on an absolute URL
$url = new \XeroPHP\Remote\URL($this->_xero_oauth_object, "https://api.xero.com/api.xro/2.0/TrackingCategories/{TrackCategoryGuid}/Options");
// Pass this to the request as a PUT request
$request = new \XeroPHP\Remote\Request($this->_xero_oauth_object, $url, \XeroPHP\Remote\Request::METHOD_PUT);
// Probably a better way but I just copied and paste the XML from the Xero API docs.
$request->setBody("<Options><Option><Name>My New Option Name</Name></Option></Options>");
// I wrapped this in a try - if it exists, there will be an error as you cant have duplicates.
try {
$request->send();
} catch (Exception $e) {
\Log::warn("Xero error: " . print_r($request->getResponse(), true));
}
// now option is created, new add the option to the tracking category
$tracking = new \XeroPHP\Models\Accounting\TrackingCategory($this->_xero_oauth_object);
$tracking->setTrackingCategoryID('3fceedc7-764e-490a-ac27-25684473af78');
// tracking category name - not sure if I need this
$tracking->setName('Contractor');
// match the option name above
$tracking->setOption('My New Option Name');

How to get access to parameter of object, created in one daemon-like script from another daemon-like script

I'm trying to write gameserver based on Workerman.
Main idea is: list of workers accept messages from clients and puts them to the queue (RabbitMQ), another group of workers get messages from queue, do some calculation and update GameWorld instance accordingly.
GameWorld instance itself is created on start of the main process, workers are created after creating of the GameWorld object. So, I wrote dummy class Server:
namespace Server;
use \Workerman\Worker;
use \Workerman\Lib\Timer;
class Server {
private $name;
public function setName(string $name){
$this->name = $name;
}
public function printName(){
echo $this->name;
}
}
Also I wrote two simple workers just for testing concept of updating object from different workers.
First (start_worker1.php):
use \Workerman\Worker;
use \Workerman\Lib\Timer;
use \Server\Server;
global $ws_worker;
$ws_worker = new Worker('Websocket://0.0.0.0:8000');
$ws_worker->name = 'FirstWorker';
$ws_worker->onWorkerStart = function($ws_worker)
{
$ws_worker->server = new Server();
$ws_worker->server->setName("FirstName");
echo "worker1 started\n";
$ws_worker->is_started = TRUE;
var_dump($ws_worker);
};
Here I created new Server object and give it a name, also changed property $ws_worker->is_started to TRUE (default value is False).
Second(start_worker2.php):
use \Workerman\Worker;
use \Workerman\Lib\Timer;
global $ws_worker;
$worker = new Worker('Websocket://0.0.0.0:8001');
$worker->name = 'SecondWorker';
// here I'm checking, if I had an object of the first worker
// and actually it outputs all the data about first worker object,
// but $ws_worker->server is NULL and $ws_worker->is_started = FALSE
// This is confusing me so much..
var_dump($ws_worker);
// here I'm trying to detect when first worker is started
// but it return false all the time..
while(!$ws_worker->is_started){
var_dump($ws_worker->is_started);
sleep(1);
}
$worker->onWorkerStart = function() use($ws_worker){
echo "worker2 started\n";
var_dump($ws_worker);
$ws_worker->sever->setName("NewName");
};
Here I created second worker and tried to access server property of the first worker object, but with no success..
All this stuff is started this way:
use Workerman\Worker;
use Server\Server;
if(strpos(strtolower(PHP_OS), 'win') === 0)
{
exit("start.php does not support windows, please use start_for_win.bat\n");
}
if(!extension_loaded('pcntl'))
{
exit("Error! <pcntl> extension not found! Please install pcntl extension.");
}
if(!extension_loaded('posix'))
{
exit("Error! <posix> extension not found! Please install posix extension.");
}
define('GLOBAL_START', 1);
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/start_worker1.php';
require_once __DIR__ . '/start_worker2.php';
// Run all services
Worker::runAll();
I guess that in worker2 I can access an worker1 object before function $ws_worker->onWorkerStart is evaluated, but I have no idea, how to access worker1 object in real time ( I mean - get access to current state of the object).
I'm new to PHP OOP style programming, I should say. So please show me where is my mistake. Detailed explanation greatly appreciated.

Check if blob exists in Azure

I'm wondering if there is a way to check if a blob exists in a container?
$blob = $blobRestProxy->getBlob("mycontainer", "myblobname");
if($blob){
return 'exists';
} else {
return 'not exists';
}
I've tried this but im getting this message whenever the blob does not exists:
BlobNotFoundThe specified blob does not exist.
If exists, the code returns 'exists' naturally. I'm not interested in listing all blobs in the container and iterating until I find a match cause I have a lot of blobs.
When the blob does not exist, the function getBlob will raise a ServiceException exception and exit the PHP progress, the following code will not work.
Please try to add the try catch statement in your code, E.G.
try {
$blob = $tableRestProxy->getBlob("mycontainer", "myblobname");
return 'exists';
} catch (ServiceException $e) {
return 'not exists';
}
so:
$exists = $storageClient->blobExists(<container name>, <blob name>);
Should give you what you're after.
Though older post, below is azure java client sample code, in case if it helps.
//getting the info from external configuration
String accountName = getStorageAccountName();
String accessKey = getAccessKey();
String container = getContainerName();
//create connection string
String connString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net",accountName,accessKey);
// create account
CloudStorageAccount account= CloudStorageAccount.parse(connString );
// create client
CloudBlobClient blobClient = account.createCloudBlobClient();
// create container
CloudBlobContainer container = blobClient.getContainerReference(container);
// fetch item from list
Iterable<ListBlobItem> blobItems = container.listBlobs();
blobItems .forEach(item -> {
if (item instanceof CloudBlockBlob){
//additional condition can be added to check leased
// need to check if the blob item exists first
if((CloudBlockBlob) blobItem).exists()){
//custom business logic
}
// to check container exists and perform logic use below
// ((CloudBlobContainer) item.getContainer()).exists
}
});

PHP SAP RFC Function call not working

This is the first time I used PHP to call a SAP function. Ran into this problem that I couldn’t figure until someone with experience helped me.
<?php
// saprfc-class-library
require_once("saprfc.php");
// Create saprfc-instance
$sap = new saprfc(array(
"logindata"=>array(
"ASHOST"=>"" // application server
,"SYSNR"=>"" // system number
,"CLIENT"=>"" // client
,"USER"=>"" // user
,"PASSWD"=>"" // password
)
,"show_errors"=>false // let class printout errors
,"debug"=>true)) ; // detailed debugging information
// Call-Function
$result=$sap->callFunction("ZBAPI",
array( array("IMPORT","FROM_","100"),
array("EXPORT","RETURN",""),
array("TABLE","Namesdata",array())
));
if ($sap->getStatus() == SAPRFC_OK) {
// Yes, print out the Userlist
?><table>
<?php
//$sap->printStatus();
foreach ($result["Namesdata"] as $orders) {
echo "<tr><td>", $orders["name"],"</td><td>",$orders["form"],"</td> <td>",$orders["Names"],"</td></tr>";
}
?></table><?php
} else {
$sap->printStatus();
}
$sap->logoff();
?>
This Code so some error like this
saprfc::callFunction('ZBAPI')
Import-Parameter=FROM_ could not be set. (Does it exist?)
But i comment the import parameter means its fetch the data from saprfc whats wrong in this code..
Import values like this ---
array("IMPORT","name",array( "fieldname"=>"1000"))

How to connect with OpenFire(xmpp) using RESTAPI plugin And PHP

I am using OpenFire to manage my xmpp server I want to add new users using a PHP, So I have installed RESETAPI Plugin to OpenFire to administrate with http request. I am using gidkom Project also. But getting a error
Parse error: syntax error, unexpected T_VARIABLE in C:\wamp\www\IM\registration.php on line 12
My code for registration.php is:
<?php
if(isset($_POST["User_Name"]) && isset($_POST["Name"]) )
{
$User_ID = $_POST["User_Name"];
$User_Name = $_POST["Name"];
$User_Email = $_POST["Email"];
include "Gidkom/OpenFireRestApi/OpenFireRestApi.php";
// Create the OpenfireUserservice object
$api = new Gidkom\OpenFireRestApi
// Set the required config parameters
$api->secret = "my keys";
$api->host = "domain.my.org";
$api->port = "9090"; // default 9090
// Optional parameters (showing default values)
$api->useSSL = false;
$api->plugin = "/plugins/restapi/v1"; // plugin
// Add a new user to OpenFire and add to a group
$result = $api->addUser($User_ID, 'Password', $User_Name, $User_Email, array('welcome'));
// Check result if command is succesful
if($result['status']) {
// Display result, and check if it's an error or correct response
echo 'Success: ';
echo $result['message'];
} else {
// Something went wrong, probably connection issues
echo 'Error: ';
echo $result['message'];
}
//Add to roster
$api->addToRoster('Administrator', 'admin');
}
else
{
echo 'Error: Something went wrong..... please go back ';
}
I want the page to add a new new user in the openfire and add admin to his roster.
Thanks !!!!
Semicolon is missing.
$api = new Gidkom\OpenFireRestApi\OpenFireRestApi;
The errors were caused because of an outdated version of PHP, YPdating PHP to latest version fixed it...
prerequirements: must to have composer.exe installed on your machine
from cmd.exe
go to your web root server(htdocs) then
go into your directory which contain the rest api sources
then from this cmd.exe(or create one batch)
c:/..../....> composer install
Remark: -this commnad(composer install) must to have in same directory the composer.json
-this command(composer install) will create one subdirectory "vendor" named
now into your index.php must insert on top, the following line:
<?php
include "vendor/autoload.php";
....
and continue your actual program
and is trully must to end the lines with ;
...
?
https://github.com/gnello/php-openfire-restapi
Easy Php REST API Client for the Openfire REST API Plugin which provides the ability to manage Openfire instance by sending an REST/HTTP request to the server
Please read documentation for further information on using this application.
Installation
composer require gnello/php-openfire-restapi
Authentication
There are two ways to authenticate:
Basic HTTP Authentication
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_user', 'your_password');
Shared secret key
$authenticationToken = new \Gnello\OpenFireRestAPI\AuthenticationToken('your_secret_key');
Start
$api = new \Gnello\OpenFireRestAPI\API('your_host', 9090, $authenticationToken);
Users
//Add a new user
$properties = array('key1' => 'value1', 'key2' => 'value2');
$result = $api->Users()->createUser('Username', 'Password', 'Full Name', 'email#domain.com', $properties);
//Delete a user
$result = $api->Users()->deleteUser('Username');
//Ban a user
$result = $api->Users()->lockoutUser('Username');
//Unban a user
$result = $api->Users()->unlockUser('Username');
Open Link Fore more.

Categories