I dont know why i get this error i can open the photo from the url but when i run the code it says ' Stream must be a Resource' Can anybody help me?. ( I use the Aws S3 library)
$stream = new Stream(fopen($_url, 'r'));
<?php
use Aws\S3\S3Client;
use GuzzleHttp\Psr7\Stream;
require __DIR__.'/vendor/autoload.php';
$_url = "http://m.cellograf.com/uploads/iz-jxwjippf-fftx-1lyb-2afkqln8-505-7145-54-x5.jpg";
$_url = str_replace('https', 'http', $_url);
try {
$stream = new Stream(fopen($_url, 'r'));
echo $stream;
} catch(Exception $e) {
echo $e->getMessage();
}
// ?>
Related
Trying to access data from a local API that outputs in JSON data, but I just keep getting:
file_get_contents(/var/www/html/api/api.php?action=stats&user=testplayer): failed to open stream: No such file or directory
Code:
<?php
error_reporting(-1);
ini_set("display_errors", 1);
include 'functions.php';
if(isset($_GET['action']))
{
header('Content-Type: application/json');
try
{
switch($_GET['action'])
{
case 'stats':
if(!isset($_GET['user']))
throw new Exception('Insufficient information : Username');
$user = $_GET['user'];
$url = htmlspecialchars_decode("/var/www/html/api/api.php?action=stats&user=$user");
$response = file_get_contents("$url");
$data = json_decode($response);
echo $data;
break;
}
}
catch(Exception $e)
{
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('result' => 'error', 'cause' => $e->getMessage()));
}
}
?>
Is it not possible to pass ? and &s through file_get_contents?
You can't process the php code if you are reading the file contents.
update the $url like this:
$url = htmlspecialchars_decode($_SERVER["SERVER_NAME"] . "/api/api.php?action=stats&user=$user") ;
This will make the request to your apache server instead of reading the file contents.
I have created following code. I have to download files from my Google Drive folder. The folder is shared. After downloading, I have to delete those files from the Google Drive.
I tried -
$file = $service->parents->delete($file_id,$folder_id); - It doesn't do anything, nor does it give any error.
$file = $service->files->trash($file_id); - It gives Error calling DELETE - (403) Insufficient permissions for this file" Error.
My code :
<?php
require_once "google/google-api-php-client/src/Google_Client.php";
require_once "google/google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google/google-api-php-client/src/contrib/Google_Oauth2Service.php";
require_once "google/vendor/autoload.php";
$file_id = '1bJm_cqIRVh5RaVrqVXGRL0CSYwTBlZur';
$folder_id='1gEllj4B9TCnLPe_dnl1ujX4u8smLL-Ky';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'service_account_email#domain.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'GoogleDriveApi-7cd8056e9eae.p12';
function buildService() {//function for first build up service
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
function printFilesInFolder($service, $folderId) {
$pageToken = NULL;
$arrayFile=array();
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$children = $service->children->listChildren($folderId, $parameters);
$arrayFile=$children;
$pageToken = $children->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $arrayFile;
}
try {
$service = buildService();
$children=printFilesInFolder($service,$folder_id);
$myfile = fopen("D:/list.txt", "wb") or die("Unable to open file!");
foreach ($children->getItems() as $child) {
print "\r\nFile Id: " . $child->getId();
fwrite($myfile, $child->getId());
fwrite($myfile, "\r\n");
}
$file = $service->parents->delete($file_id,$folder_id);
$file = $service->files->trash($file_id);
fclose($myfile);
} catch (Exception $e) {
print "An error occurred1: " . $e->getMessage();
}
?>
Your error indicates that the user doesn't have a write access to the file, and an app is attempting to modify the particular file.
Suggested action: Report to the user that there is a need to ask for
those permissions in order to update the file. You may also want to
check user access levels in the metadata retrieved by
files.get and use that to change your UI to a read only UI.
i use server on Debian 8 with ISP 5. I have installed that lib: https://github.com/akalongman/php-telegram-bot. Webhook was set but bot doesn't respond messages and commands. Server hadn't logs, I do not know what the problem is :(
I received a SSL from Let's Encrypt in ISP Manager for IP adress.
enter image description here
Here is my set.php
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'key';
$BOT_NAME = 'evtepo_bot';
$hook_url = 'https://213./hook.php';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// Set webhook
$result = $telegram->setWebhook($hook_url);
if ($result->isOk()) {
echo $result->getDescription();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
}
And hook.php
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'key';
$BOT_NAME = 'evtepo_bot';
$commands_path = __DIR__ . '/Commands/';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// Handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
\Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . '/' . $BOT_NAME . '_error.log');
\Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . '/' . $BOT_NAME . '_debug.log');
\Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . '/' . $BOT_NAME . '_update.log');
}
$telegram->addCommandsPath($commands_path);
You should use getWebhookInfo method to check if the updates were delivered to the hook and if there were any errors.
The problem was that I needed to buy a domain and get a SSL from Lets'Encrypt.
I am creating a simple dropbox app where after authenticating the user, the app is supposed to prompt for some information, read the content of a txt file. Use ajax for everything after authentication.
so far I have managed to authenticate but when I send the info to the server using ajax I am failing to open the file.
I have the following server side script:
<?php
require_once "../app/start.php";
require_once __DIR__.'/../app/config.php';
$regex = $_POST['regex'];
(...)
$accessToken = $_SESSION['accessToken'] ;
$client = new Dropbox\Client($accessToken, $GLOBALS['app_name'], 'UTF-8');
var_dump($client);
// Read File todo.txt
$filename = __DIR__.'/todo/todo.txt';
$f = fopen($filename, "w+b") or die("Unable to open file!");
$fileMetadata = $client->getFile('/todo/todo.txt', $f);
var_dump($fileMetadata);
and when I execute it the output is the following:
object(Dropbox\Client)#8 (6) {
["accessToken":"Dropbox\Client":private]=>
string(64) "xxxxxxxxxxxxxxxxxxxxxxxxx"
["clientIdentifier":"Dropbox\Client":private]=>
string(13) "oauth-php/1.0"
["userLocale":"Dropbox\Client":private]=>
string(5) "UTF-8"
["apiHost":"Dropbox\Client":private]=>
string(15) "api.dropbox.com"
["contentHost":"Dropbox\Client":private]=>
string(23) "api-content.dropbox.com"
["host"]=>
object(Dropbox\Host)#5 (3) {
["api":"Dropbox\Host":private]=>
string(15) "api.dropbox.com"
["content":"Dropbox\Host":private]=>
string(23) "api-content.dropbox.com"
["web":"Dropbox\Host":private]=>
string(15) "www.dropbox.com"
}
}
NULL
Where the last NULL refers to the content of $fileMetadata. Why is it empty?
the contnet of start.php are the dropbox objects.
<?php
session_start();
require_once __DIR__.'/../vendor/autoload.php';
$key = "XCV...";
$secret = "DFG...";
$GLOBALS['app_name'] = "oauth-php/1.0";
$GLOBALS['redirectURI'] = "https://oauth.dev/dropbox_finish.php";
$GLOBALS['HomeURI'] = "https://oauth.dev";
$appInfo = new Dropbox\AppInfo($key, $secret);
$csrfTokenStore = new Dropbox\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
$webAuth = new Dropbox\WebAuth($appInfo, $GLOBALS['app_name'], $GLOBALS['redirectURI'], $csrfTokenStore);
Edit: in the local files I have a directory called web, where the files executed are. the there is as well a folder (inside web) called todo and the file todo.txt it is inside. __DIR__ refers to inside the web directory that i have mentioned.
In Dropbox i have a direcotry called todo with todo.txt inside.
Edit2: adding the rest of the code.
index.php contains:
<?php
include_once __DIR__.'/../app/start.php';
include_once __DIR__.'/../app/dropbox_auth.php';
Then dropbox_auth.php has the following code:
$authURL = $webAuth->start();
header("Location: $authURL");
and finally dropbox_finish.php
<?php
//session_start();
require_once "../app/start.php";
try {
list($accessToken, $userId, $urlState) = $webAuth->finish($_GET);
assert($urlState === null); // Since we didn't pass anything in start()
}
catch (Dropbox\WebAuthException_BadRequest $ex) {
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
// Respond with an HTTP 400 and display error page...
}
//review
catch (Dropbox\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header('Location: '.$GLOBALS['HomeURI']);
}
catch (Dropbox\WebAuthException_Csrf $ex) {
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
// Respond with HTTP 403 and display error page...
}
catch (Dropbox\WebAuthException_NotApproved $ex) {
error_log("/dropbox-auth-finish: not approved: " . $ex->getMessage());
}
catch (Dropbox\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: error redirect from Dropbox: " . $ex->getMessage());
}
catch (Dropbox\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
}
$client = new Dropbox\Client($accessToken, $GLOBALS['app_name'], 'UTF-8');
$_SESSION['accessToken'] = $accessToken;
$_SESSION['client_object'] = $client;
{... here I load an HTML form that uses AJAX send to `insert.php`}
Sorry I cant write a comment right now.
Try to get the folder/file list by calling $client->getMetadataWithChildren('/todo/') and check if $f is a valid FilePointerRessource :)
Trying out using PHP with thrift and I can't run it properly due to being unable to find certain classes. I was able to do this in 0.8.0 fine, now that I've downloaded 0.9.0 I'm at a loss as to how I should include the thrift files properly.
Here is my snippet of code:
$GLOBALS['THRIFT_ROOT'] = '/home/user/final/Thrift';
require_once( $GLOBALS['THRIFT_ROOT'] . '/Transport/TSocket.php' );
require_once( $GLOBALS['THRIFT_ROOT'] . '/Transport/TBufferedTransport.php' );
require_once( $GLOBALS['THRIFT_ROOT'] . '/Protocol/TBinaryProtocol.php' );
require_once( 'Hbase/Hbase.php');
require_once( 'Hbase/Types.php');
use Hbase\HbaseClient;
try
{
$socket = new TSocket('127.0.0.1', 9090);
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocolAccelerated($transport);
$client = new HbaseClient( $protocol );
$transport->open();
//show all tables
$tables = $client->getTableNames();
foreach ( $tables as $name )
{
echo( " found: {$name}\n" );
}
}
catch (Exception $e)
{
echo "Exception: %e\r\n";
}
All files are layed out properly in the directories as seen here:
But when I run the file from the command line (php -f index.php) I'm receiving this error:
Class 'Thrift\Transport\TTransport' not found in
/home/user/final/Thrift/Transport/TSocket.php on line 35
I'm really at a loss as to what I should do next, I'm not familiar with using the "use" command or "namespace" in PHP, which I have a feeling would help solve this. The thrift README for php also mentions using symfony, which is just further confusing me.
Any advice would be greatly appreciated!
Thanks!
Name space Like this:
use Thrift\Transport\TSocket;
use Thrift\Transport\TBufferedTransport;
use Thrift\Protocol\TBinaryProtocolAccelerated;
try {
$socket = new TSocket('xxxxx', 9090);
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocolAccelerated($transport);
$client = new HbaseClient($protocol);
$transport -> open();
//show all tables
$tables = $client -> getTableNames();
foreach ($tables as $name) {
echo(" found: {$name}\n");
}
} catch (Exception $e) {
print_r($e);
}
Use ClassLoader. Hbase classes do not support classLoader but uses Thrift namespaces.
<?php
define('THRIFT_PATH', __DIR__);
require_once THRIFT_PATH . '/Thrift/ClassLoader/ThriftClassLoader.php';
$classLoader = new Thrift\ClassLoader\ThriftClassLoader();
$classLoader->registerNamespace('Thrift', THRIFT_PATH);
$classLoader->register();
// (!) include after classLoader
require_once 'Hbase/Hbase.php';
require_once 'Hbase/Types.php';
try
{
$socket = new Thrift\Transport\TSocket('127.0.0.1', 9090);
$transport = new Thrift\Transport\TBufferedTransport($socket, 1024, 1024);
$protocol = new Thrift\Protocol\TBinaryProtocolAccelerated($transport);
$client = new Hbase\HbaseClient($protocol);
$transport->open();
//show all tables
$tables = $client->getTableNames();
foreach ($tables as $name)
{
echo "found: {$name}\n";
}
}
catch (Exception $e)
{
echo "Exception: %e\r\n";
}
P.S. This code work for your directory structure:
you need to keep Thrift parent dirname, don't rename it;
the directory structure like this
Thrift/Base
Thrift/ClassLoader
Thrfit/xxxx
example
I put whole Thrift folder in htdocs\thrift-0.9.3\
then it look like this img
the php code should be like this:
<?php
ini_set('display_error', E_ALL);
$THRIFT_ROOT = __DIR__.'/thrift-0.9.3';
require_once $THRIFT_ROOT . '/Thrift/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;
$classLoader = new ThriftClassLoader();
$classLoader->registerNamespace('Thrift', $THRIFT_ROOT);
$classLoader->register();
use Thrift\Transport\TSocket;
use Thrift\Transport\TBufferedTransport;
use Thrift\Protocol\TBinaryProtocolAccelerated;
// (!) include after classLoader
/* Dependencies. In the proper order. */
require_once './hbase-1.2.0-thrift2/THBaseService.php';
require_once './hbase-1.2.0-thrift2/Types.php';
$host = 'xxxxx';
$port = 19090;
$tableName='test';
$rowKey='b';
$socket = new TSocket($host, $port);
$transport = new TBufferedTransport($socket);
$protocol = new TBinaryProtocolAccelerated($transport);
$client = new THBaseServiceClient($protocol);
$transport->open();
$get = new TGet();
$get->row = $rowKey;
$arr = $client->get($tableName, $get);
$data = array();
$results = $arr->columnValues;
foreach($results as $result)
{
$qualifier = (string)$result->qualifier;
$value = $result->value;
$data[$qualifier] = $value;
}
var_dump($data);
$transport->close();