Hi im new in slim 3 framework (Api for mobile) i would like to know how to upload an image to a server, e seacrh for examples didnt find much, this is the code i have but it does not work.Any help would be great thanks.
$app->post('/photo', function ($request, $response) use ($app) {
$files = $request->getUploadedFiles();
if (empty($files['newfile'])) {
throw new Exception('Expected a newfile');
}
$newfile = $files['newfile'];
if ($newfile->getError() === UPLOAD_ERR_OK) {
$uploadFileName = $newfile->getClientFilename();
$newfile->moveTo("../photos/");
}
});
The error it gives me
<h1>Slim Application Error</h1>
<p>The application could not run because of the following error:</p>
<h2>Details</h2>
<div>
<strong>Type:</strong> Error
</div>
<div>
<strong>Message:</strong> Call to a member function getError() on null
</div>
<div>
<strong>File:</strong> /home/bitstudi/public_html/api_pricegram/public/index.php
</div>
<div>
<strong>Line:</strong> 155
</div>
<h2>Trace</h2>
#0 [internal function]: Closure->{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#1 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php(41): call_user_func(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#2 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/Route.php(344): Slim\Handlers\Strategies\RequestResponse->__invoke(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#3 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(122): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#4 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/Route.php(316): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#5 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/App.php(476): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#6 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(122): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#7 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/App.php(370): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#8 /home/bitstudi/public_html/api_pricegram/vendor/slim/slim/Slim/App.php(295): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 /home/bitstudi/public_html/api_pricegram/public/index.php(161): Slim\App->run()
#10 {main}
i solved like this
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\Http\UploadedFile;
require '../vendor/autoload.php';
$app = new \Slim\App([
'settings' => [
'displayErrorDetails' => true
]
]);
$container = $app->getContainer();
$container['upload_directory'] ='../photos/';
$app->post('/photo', function (Request $request, Response $response) use ($app) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['picture'];
if($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->write('uploaded ' . $filename . '<br/>');
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(),
PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
$app->run();
Related
We have an application with million events go through every hour. Using RabbitMQ and PHP-AMQP we process them through our own made consumers. Once in a while the connection drops.
Consumers are running on DO App Platform (worker) and the RabbitMQ is a droplet.
Consumer is a Laravel Command.
public function handle() {
$queuesToListen = $this->constructQueues();
$queueJobs = $this->extractQueueJobs($this->queues);
if(is_array($queuesToListen) && count($queuesToListen) > 0){
$this->output->writeln('<fg=green>[EVENTS] Found ' . count($queuesToListen) . ' queues to subscribe to, starting to listen</>');
while(true) {
foreach ($queuesToListen as $queueName) {
$this->output->writeln('<fg=yellow>Let\'s listen to queue ' . $queueName." </>");
$this->currentQueue = $queueName;
try {
$connection = AMQPStreamConnection::create_connection([
['host' => env('RABBITMQ_HOST'), 'port' => env('RABBITMQ_PORT'), 'user' => env('RABBITMQ_USER'), 'password' => env('RABBITMQ_PASSWORD'), 'vhost' => env('RABBITMQ_VHOST')]
], ['heartbeat' => constant($queueJobs[$this->currentQueue] . '::HEARTBEAT_RATE')]);
$channel = $connection->channel();
$channel->queue_declare($queueName, false, true, false, false);
echo ' [*] Connected to queue ' . $queueName . ' , waiting for messages.', "\n";
$channel->basic_qos(null, 10, null);
$channel->basic_consume($queueName, '', false, false, false, false, [$this, 'processEvent']);
// Loop as long as the channel has callbacks registered
while (count($channel->callbacks)) {
$channel->wait(null, false, 2);
}
} catch (\PhpAmqpLib\Exception\AMQPExceptionInterface $e) {
echo "AMQP Exception: ", $e->getMessage(), "\n";
echo "AMQP Code: ", $e->getCode(), "\n";
$channel->close(); //LINE 72
$connection->close();
}
}
}
}else{
$this->output->writeln('<fg=red>[EVENTS] No queues to process, command stopped</>');
}
}
Error we get are:
PhpAmqpLib\Exception\AMQPConnectionClosedException: Broken pipe or closed connection
#19 /vendor/php-amqplib/php-amqplib/PhpAmqpLib/Wire/IO/StreamIO.php(235): PhpAmqpLib\Wire\IO\StreamIO::write
#18 /vendor/php-amqplib/php-amqplib/PhpAmqpLib/Connection/AbstractConnection.php(408): PhpAmqpLib\Connection\AbstractConnection::write
#17 /vendor/php-amqplib/php-amqplib/PhpAmqpLib/Connection/AbstractConnection.php(536): PhpAmqpLib\Connection\AbstractConnection::send_channel_method_frame
#16 /vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AbstractChannel.php(248): PhpAmqpLib\Channel\AbstractChannel::send_method_frame
#15 /vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AMQPChannel.php(198): PhpAmqpLib\Channel\AMQPChannel::close
#14 /vendor/sdk-blueprint-service/src/RabbitMQ/Console/Consume.php(72):BluePrint\RabbitMQ\Console\Consume::handle
#13 /vendor/illuminate/container/BoundMethod.php(36): Illuminate\Container\BoundMethod::Illuminate\Container{closure}
#12 /vendor/illuminate/container/Util.php(40): Illuminate\Container\Util::unwrapIfClosure
#11 /vendor/illuminate/container/BoundMethod.php(93): Illuminate\Container\BoundMethod::callBoundMethod
#10 /vendor/illuminate/container/BoundMethod.php(37): Illuminate\Container\BoundMethod::call
#9 /vendor/illuminate/container/Container.php(653): Illuminate\Container\Container::call
#8 /vendor/illuminate/console/Command.php(136): Illuminate\Console\Command::execute
#7 /vendor/symfony/console/Command/Command.php(298): Symfony\Component\Console\Command\Command::run
#6 /vendor/illuminate/console/Command.php(121): Illuminate\Console\Command::run
#5 /vendor/symfony/console/Application.php(1024): Symfony\Component\Console\Application::doRunCommand
#4 /vendor/symfony/console/Application.php(299): Symfony\Component\Console\Application::doRun
#3 /vendor/symfony/console/Application.php(171): Symfony\Component\Console\Application::run
#2 /vendor/illuminate/console/Application.php(94): Illuminate\Console\Application::run
#1 /vendor/laravel/lumen-framework/src/Console/Kernel.php(116): Laravel\Lumen\Console\Kernel::handle
#0 /artisan(35): null
Whenever this error occurs the application stops processing the events. And we manually have to redeploy the application.
How can we prevent this from crashing? Is there a way to detect if a channel is still open?
We are using open cart for website development and recently i have changed Reply To mail address as i wanted while sending confirmation mail to admin when a user registered on website saying new customer has registered on website,now i am getting the error after submitting another form (request for Price).
Uncaught exception 'Exception' with message 'Error: E-Mail to required!' in /var/www/html/neon_opencart/system/library/mail.php:60 Stack trace: #0 /var/www/html/neon_opencart/catalog/controller/product/category.php(124): Mail->send() #1 [internal function]: ControllerProductCategory->index() #2 /var/www/html/neon_opencart/system/storage/modification/system/engine/action.php(44): call_user_func_array(Array, Array) #3 /var/www/html/neon_opencart/catalog/controller/startup/router.php(25): Action->execute(Object(Registry)) #4 [internal function]: ControllerStartupRouter->index() #5 /var/www/html/neon_opencart/system/storage/modification/system/engine/action.php(44): call_user_func_array(Array, Array) #6 /var/www/html/neon_opencart/system/engine/front.php(34): Action->execute(Object(Registry)) #7 /var/www/html/neon_opencart/system/engine/front.php(29): Front->execute(Object(Action)) #8 /var/www/html/neon_opencart/system/framework.php(99): Front->dispatch(Object(Action), Object(Action)) #9 /var/www/html/neon_openca in /var/www/html/neon_opencart/system/library/mail.php on line 60
Please have a look at the error,here is my code
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($this->config->get('config_email'));
$mail->setReplyTo('example#domain.com');
$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($this->language->get('text_new_customer'), ENT_QUOTES, 'UTF-8') . '-' . date('d-m-y'));
//$mail->sethtml($message);
$mail->setText($message_admin);
$mail->send();
I am developing a custom wp plugin that deals with twitter so I am using this as repository https://github.com/J7mbo/twitter-api-php
This is my code for the shortcode:
function ct_twitter_shortcode_func( $atts ){
ob_start();
include_once '/includes/twitter-api-php-master/TwitterAPIExchange.php';
$ct_twitter_keys = get_option("ct_twitter_keys");
$settings = array(
'oauth_access_token' => $ct_twitter_keys["OAUTH_ACCESS_TOKEN"],
'oauth_access_token_secret' => $ct_twitter_keys["OAUTH_ACCESS_TOKEN_SECRET"],
'consumer_key' => $ct_twitter_keys["CONSUMER_KEY"],
'consumer_secret' => $ct_twitter_keys["CONSUMER_SECRET"]
);
//echo dirname(__FILE__) . '/cacert.pem';
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name=bikegearup&count=20';
$twitter = new TwitterAPIExchange($settings);
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(true, array(CURLOPT_CAINFO => '/includes/twitter-api-php-master/cacert.pem'));
return ob_get_clean();
}
add_shortcode( 'ct_twitter', 'ct_twitter_shortcode_func' );
but I got this kind of error:
Fatal error: Uncaught exception 'Exception' with message 'error setting certificate verify locations: CAfile: /includes/twitter-api-php-master/cacert.pem CApath: none' in C:\xampp\htdocs\pluto\wp-content\plugins\ct-socials\shortcodes\ct-twitter\includes\twitter-api-php-master\TwitterAPIExchange.php:321 Stack trace: #0 C:\xampp\htdocs\pluto\wp-content\plugins\ct-socials\shortcodes\ct-twitter\class-fw-shortcode-ct-twitter.php(23): TwitterAPIExchange->performRequest(true, Array) #1 [internal function]: ct_twitter_shortcode_func(Array, '', 'ct_twitter') #2 C:\xampp\htdocs\pluto\wp-includes\shortcodes.php(345): call_user_func('ct_twitter_shor...', Array, '', 'ct_twitter') #3 [internal function]: do_shortcode_tag(Array) #4 C:\xampp\htdocs\pluto\wp-includes\shortcodes.php(223): preg_replace_callback('/\[(\[?)(ct_soc...', 'do_shortcode_ta...', '[ct_twitter sty...') #5 [internal function]: do_shortcode('[ct_twitter sty...') #6 C:\xampp\htdocs\pluto\wp-includes\class-wp-hook.php(298): call_user_func_array('do_shortcode', Arra in C:\xampp\htdocs\pluto\wp-content\plugins\ct-socials\shortcodes\ct-twitter\includes\twitter-api-php-master\TwitterAPIExchange.php on line 321
I also tried to include https://curl.haxx.se/ca/cacert.pem but still it won't work.. can anyone help me with this?
any help will be appreciated, thanks in advance...
I am having problems getting a list of users for accounts
If I put the account number in the try me page (https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/accountUserLinks/list) it works
$client = new Google_Client();
$client->setAuthConfigFile($_SERVER['DOCUMENT_ROOT'] . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_MANAGE_USERS);
$client=gaGetClient();
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$analytics = new Google_Service_Analytics($client);
//this doesn't work
$accountUserlinks=$analytics->management_accountUserLinks->listManagementAccountUserLinks('123456');
//this works
$man_accounts = $analytics->management_accounts->listManagementAccounts();
$accounts = [];
foreach ($man_accounts['items'] as $account) {
$accounts[] = [ 'id' => $account['id'], 'name' => $account['name'] ];
echo $account['name'] . " (" . $account['id'] . ")<br/>";
}
}
I get this error message
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/123456/entityUserLinks:
(403) Insufficient Permission' in
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php:110
Stack trace: #0
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php(62):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]:
Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request)) #2
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Task/Runner.php(174):
call_user_func_array(Array, Array) #3
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php(46):
Google_Task_Runner->run() #4
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Goo
in
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php
on line 110
Can anyone think what I am doing wrong. I am thinking it is a scope issue, but I have stated my scopes
Thanks
Grant
I have a problem using Google Cloud Storage and Google Play reports. I'd like to parse reports on my server in PHP. To do that I'd like to move the file in the default app bucket to a new one. When I try to do that, I get the following error :
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "Not Found" } ], "code": 404, "message": "Not Found" } } ' in /var/www/d2/libs/googleAPI/src/Google/Http/REST.php:118 Stack trace: #0 /var/www/d2/libs/googleAPI/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 /var/www/d2/libs/googleAPI/src/Google/Task/Runner.php(181): call_user_func_array(Array, Array) #3 /var/www/d2/libs/googleAPI/src/Google/Http/REST.php(58): Google_Task_Runner->run() #4 /var/www/d2/libs/googleAPI/src/Google/Client.php(781): Google_Http_REST::execute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...', Array) #5 /var/www/d2/libs/googleAPI/src/Google/Service in /var/www/d2/libs/googleAPI/src/Google/Http/REST.php on line 118
I don't know why because the destination bucket exists, origin file too.
This is my implementation of my PHP script :
<?php
session_start();
require_once dirname(__FILE__).'/../libs/googleAPI/vendor/autoload.php';
$scopes = array("https://www.googleapis.com/auth/cloud-platform");
// Create client object
$client = new Google_Client();
$client->setRedirectUri('http://CENSORED/TEST_API.php');
$client->setAuthConfig("client_credentials_OAUTH.json");
$client->addScope($scopes);
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Storage($client);
$request = $service->objects->listObjects("statsinstalls");
$objects = $request->getItems();
$sourceBucket = "pubsite_prod_rev_CENSORED";
$sourceObject = "installs_CENSORED_" . date("Ym") . "_app_version.csv";
$destinationBucket = "statsinstalls";
$destinationObject = $sourceObject;
$postBody = new Google_Service_Storage_StorageObject($client);
$response = $service->objects->copy($sourceBucket, $sourceObject, $destinationBucket, $destinationObject, $postBody);
foreach ($objects as $item)
echo $item->id . "<br>";
}
else if (!isset($_GET['code']))
{
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
else
{
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://CENSORED/TEST_API.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Why I got a 404 error?
Thanks.
I found the solution. The source Object must be the full path of the file.
I just replace :
$sourceObject = "installs_CENSORED_" . date("Ym") . "_app_version.csv";
by :
$sourceObject = "stats/installs/installs_CENSORED_" . date("Ym") . "_app_version.csv";
and that work well now. Now I'll try to get this CSV into a PHP array