How can I get headers of the URL from chrome-php - chromephp

I am using chrome-php
I want to get the header from the response
Is there any way I can get it?
Here is how I am trying to implement the functionality ...
$browserFactory = new BrowserFactory('chromium-browser');
// starts headless chrome
$browser = $browserFactory->createBrowser([
'noSandbox' => true,
'debugLogger' => 'php://stdout',
]);
try {
$page = $browser->createPage();
$page->navigate($url)->waitForNavigation();
info([$page->getHtml()]);
finally {
$browser->close();
}

Related

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects
you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

How to integrate Google login on a CakePHP REST API

I am building an Android app that is interfaced with a CakePHP 3 web API. Since a RESTful API cannot rely on cookies, I understand that I need JSON web tokens (JWT) to make this happen, and would much prefer to use a google login. I already got the Android side to request a token from Google's API, but now I am lost on how to incorporate this into my API for authentication.
I've searched around for some tutorials, such as this one: http://blog.jainsiddharth21.com/2013/04/29/login-with-google-in-cakephp/, but it relies on session data. I'm building the API in CakePHP 3, so I've looked at some of the plugins, such as ADmad/JwtAuth, so maybe I could extend on this to allow google authentication, but I am not sure how.
Login With Gmail and Specific email address to allowed to login in CakePHP 3.x
Composer to install
"google/apiclient": "^2.0"
Required gmail with login
https://console.developers.google.com/apis/credentials?project=mdpms-187410&organizationId=1095988912954
Create project and create secret key and client id
Project in set name and redirect URL
NOTE:- redirect URL must be .com and .org domain
If you develop in local machine then create follow type of virtual host
example.com and example.org
Virtual host create then
Follow this step:
Set configuration file in app_globle.php
'Google' =>
[
'googleClientID' => '123456.apps.googleusercontent.com',
'googleClientSecret' => 'abcdefghi',
'googleRedirectUrl' => 'http://example.com/oauth2callback'
]
Gmail login route
//Google login
$routes->connect('/account/google-login', ['controller' => 'Account', 'action' => 'googlelogin'], ['_name' => 'account-google-login']);
$routes->connect('/oauth2callback', ['controller' => 'Account', 'action' => 'confirmlogin'], ['_name' => 'account-google-redirect-url']);
Google login action code:
/**
* Gmail login method
*/
public function googlelogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->se
tScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$url = $client->createAuthUrl();
$this->redirect($url);
}
Google redirect url Action
/**
* Gmail auth redirect action
* #return type gmail auth data
*/
public function confirmlogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->setScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$client->setApprovalPrompt('auto');
$usersTable = TableRegistry::get('Users');
if (isset($this->request->query['code'])) {
$client->authenticate($this->request->query['code']);
$this->request->Session()->write('access_token', $client->getAccessToken());
}
if ($this->request->Session()->check('access_token') && ($this->request->Session()->read('access_token'))) {
$client->setAccessToken($this->request->Session()->read('access_token'));
}
if ($client->getAccessToken()) {
$this->request->Session()->write('access_token', $client->getAccessToken());
$oauth2 = new Google_Service_Oauth2($client);
$user = $oauth2->userinfo->get();
try {
if (!empty($user)) {
if ((preg_match("/(#example\.com)$/", $user['email'])) || (preg_match("/(#example\.in)$/", $user['email']))) {
$result = $usersTable->find('all')
->where(['email' => $user['email']])
->first();
if (!empty($result)) {
$this->AccessControl->setUser($result->toArray(), false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$data = [];
$data['email'] = $user['email'];
$data['first_name'] = $user['givenName'];
$data['last_name'] = $user['familyName'];
$data['socialId'] = $user['id'];
$data['role_id'] = Configure::read('Role.loginWithGmailUserRole');
//$data matches my Users table
$entity = $usersTable->newEntity($data);
if ($usersTable->save($entity)) {
$data['id'] = $entity->id;
$this->AccessControl->setUser($data, false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$this->Flash->error(__('Invalid login.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
}
} else {
$this->Flash->error(__('Your email is invalid for this application.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
} else {
$this->Flash->error(__('Gmail infos not found.'));
//redirect to login action
return $this->redirect(['_name' => 'account-login']);
}
} catch (\Exception $e) {
$this->Flash->error(__('Gmail error.'));
return $this->redirect(['_name' => 'account-login']);
}
}
}

Facebook SDK v5 integration with Laravel 5.0

I'm trying to make a guide on how to integrate Facebook SDK v5 with Laravel 5.0. Have anyone done this before?
First of all i added "facebook/php-sdk-v4" : "~5.0" in composer.json see documentatione here: https://developers.facebook.com/docs/php/gettingstarted
{
"require" : {
"facebook/php-sdk-v4" : "~5.0"
}
}
Next step composer install in CMD
composer install
Next i added a route:
Route::get('/test', 'Facebookintegration#test');
Next i returned a view:
public function test() {
return view('testpage');
}
Next i try to run the info in the view testpage
<?php
require_once URL::asset('vendor/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'YOUR_APP_ID',
'app_secret' => 'YOUR_APP_SECRET',
'default_graph_version' => 'v2.5',
]);
?>
Here is where the problems start and this is my current error
main(): Failed opening required 'http://localhost/fbintegration/vendor/autoload.php' (include_path='.;C:\php\pear')
anyone know how to correctly link yo the files?
https://github.com/SammyK/LaravelFacebookSdk
Use this package for Laravel instead.
The code below is to post to facebook after retrieving token from my DB
Route
Route::post('schedulePost', 'HomeController# exampelSchedulePost');
Composer.json
"require": {
"sammyk/laravel-facebook-sdk": "^3.0"
}
Provider and aliases , refer to Docs
'providers' => [
SammyK\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider::class,
];
'aliases' => [
'Facebook' => SammyK\LaravelFacebookSdk\FacebookFacade::class,
];
public function exampelSchedulePost(Request $request)
{
$postPermission = 0;
$profileToken = DB::table('profiles')->where('user_id',Auth::user()->id)->first();
$fb = App::make('SammyK\LaravelFacebookSdk\LaravelFacebookSdk');
if($profileToken){
try {
$response = $fb->get('/'.$profileToken->uid.'/permissions', $profileToken->access_token);
$permissions = $response->getGraphEdge();
foreach ($permissions as $item) {
if($item['permission'] == 'publish_actions'){
if($item['status']== 'declined'){
$login_link = $fb->getLoginUrl(['email,publish_actions'], 'http://www.URL.com/facebook/callback');
return redirect($login_link);
//Get Permission again
}
}
}
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}else{
$login_link = $fb->getLoginUrl(['email,publish_actions'], 'http://www.URL.com/facebook/callback');
return redirect($login_link);
}
It looks like the path issue when you want to require file in your view.
You can try something like this in you view template:
require_once ($app['path.base'].'/vendor/facebook/graph-sdk/src/Facebook/autoload.php');
And the I believe you can get Facebook\Facebook class without problem.

The server don't receive a Response / SendRequests

Iam new guy for Zend2 framework...I got an error which I didnt trace it...
Iam writing a controller named 'usertask' and in that fir index function i wrote the code like this
public function indexAction()
{
$sendRequest = new SendRequests;
$tableGrid = new DynamicTable();
$prop = array(
'customRequest' => 'GET',
'headerInformation' => array('environment: development', 'token_secret: abc')
);
$returnRequest = $sendRequest->set($prop)->requests('http://service-api/usertask');
$returnData = json_decode($returnRequest['return'],true);
$tableGrid->tableArray = $returnData['result'];
$dynamicTable = $tableGrid->tableGenerate();
$view = new ViewModel(array(
'usertask' => $dynamicTable
));
//print_r($view);exit;
return $view;
}
but it is not listing my usertasks...while Iam printing $returnRequest its giving me error message like
The server don't receive a Response / SendRequests
what it the mistake in my code...could anyone suggest me...please..iam using "zend2"
Sorry guys I found my mistake ...I got big code but I need something like
public function indexAction()
{
$view = new ViewModel(array(
'usertask' => $this->UserTable()->fetchall(),
));
return $view;
}
public function getUserTable()
{
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('User\Model\UserTable');
}
return $this->userTable;
}
that's it...i got it as a list of users

Facebook Graph API - Get Event that a Page have created

How can I get all the Events a Page have created?
I've tried the following:
https://graph.facebook.com/PAGEID/events
But I don't get any data back.
Can someone help me?
I've run in to the same issue and also updated the bug mentioned by ivan.abragimovich.
I'm not proud of it, but here is what I did as a work around.
$accessToken = "..."; // your OAuth token
$uid = "..."; // the id of the page you are using
$feed = $this->facebook->api("/$uid/feed", "GET", array('access_token' => $accessToken,
'limit' => 20));
// temp method of retrieving events until the page events bug is fixed.
// #see http://bugs.developers.facebook.com/show_bug.cgi?id=10399
if (array_key_exists('data', $feed) && is_array($feed['data']))
{
foreach($feed['data'] as $item)
{
if ($item['type'] == "link" && strpos($item['link'], "eid=") !== false)
{
preg_match('/eid=(\d+)/', $item['link'], $urlMatches);
if (count($urlMatches) == 2)
{
$eventId = $urlMatches[1];
$event = $this->facebook->api("/$eventId", 'GET', array('access_token' => $accessToken));
print_r($event);
}
}
}
}
Are you sure there are events that are associated with the Page? You might want to check if you can retrieve the feed. Just swap "events" with "feed" in the URL.