<?php function getService() { require_once 'vendor/autoload.php'; $service_account_email = 'xxx'; $key_file_location = '/'; $client = new Google_Client(); $client->setApplicationName("MyAnalyticsApp"); $analytics = new Google_Service_Analytics($client); $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key ); $client->setAssertionCredentials($cred); if($client->getAuth()->isAccessTokenExpired()){ $client->getAuth()->refreshTokenWithAssertion($cred); } return $analytics; } function getFirstprofileId(&$analytics){ $accounts = $analytics->management_accounts->listManagementAccounts(); if(count($accounts->getItems()) > 0){ $items = $accounts->getItems(); $firstAccountId = $items[0]->getId(); $properties = $analytics->management_webproperties ->listManagementWebproperties($firstAccountId); if (count($properties->getItems()) > 0){ $items = $properties->getItems(); $firstPropertyId = $items[0]->getId(); $profiles = $analytics->management_profiles ->listManagemetProfiles($firstAccountId, $firstPropertyId); if(count($profiles->getItems()) > 0){ $items = $profiles->getItems(); return $items[0]->getId(); } else { throw new Exception('No views (profiles) found for this user.'); } } else { throw new Exception('No properties found for this user.'); } } else { throw new Exception('No accounts found for this user.'); } } function getResult(&$analytics, $profileId){ return $analytics->data_ga->get( 'ga:' . $profileId, '7daysAgo', 'today', 'ga:sessions'); } function printResults(&$results){ if (count($results->getRows()) > 0){ $profileName = $results->getProfileInfo()->getProfileName(); $rows = $results->getRows(); $sessions = $rows[0][0]; print "First view (profile) found: $profileName\n"; print "Total sessions: $sessions\n"; } else { print "No results found.\n"; } } $analytics = getService(); $profile = getFirstProfileId($analytics); $results = getResults($analytics, $profile); printResults($results); ?>
$_GET example2
<?php $totalPage = 100; if ( isset($_GET["page"]) && $_GET["page"] > 0 && $_GET["page"] <= $totalPage ) { $page = (int)$_GET["page"]; } else { $page = 1; } ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>サンプル</title> </head> <body <p>現在 <?php echo $page; ?>ページ目です。 <p> <?php if ($page > 1) : ?> <a href="?page=<?php echo ($page - 1); ?>">前ページへ</a> <?php endif; ?> <?php if ($page < $totalPage) : ?> <a href="?page=<?php echo ($page + 1); ?>">次ページへ</a> <?php endif; ?> </p> </body> </html>
$_GET
<html> <head> <title>銘柄</title> </head> <body> <form action="" method="get"> <p>コード</p> <p><input type="text" name="code"></p> <p>銘柄名</p> <p><input type="text" name="name"></p> <p><input type="submit" value="送信"></p> </form> </body> </html> <?php echo $_GET["code"]; echo "<br>"; echo $_GET["name"]; ?>
session_start();
サーバーは、リクエストがあったクライアントに対し、セッションIDを出してクライアント側に保存させる。サーバーはセッションIDとクライアントのやりとりを保存。
次回、クライアントがサーバーに接続した際に、記録を引き継ぐことができる。
クッキーは、クライアント側で情報を保存する。
example
index.php
<html> <head> <title>空売り機関投資家</title> </head> <body> 機関投資家 <form action="regist.php" method="post"> <table> <tr> <td><input type="text" name="investor"></td> <td> <input type="submit" value="登録"> </td> </tr> </table> </body> </html>
regist.php
<?php session_start(); ?> <html> <head> <title>登録画面</title> </head> <body> <?php $investor = $_POST['investor']; $_SESSION['investor'] = $_POST['investor']; print("次の機関投資家を登録しました<br>"); print("機関投資家: $investor<br>"); ?> <a href="regist_check.php">確認</a> </body> </html>
<? session_start(); ?> <html> <head> <title>登録画面</title> </head> <body> <?php print("登録済み:<br>"); print($_SESSION['investor']."<br>"); ?> <a href="index.php">追加登録</a> </body> </html>
require, require_once
require は同じファイルを何度も取り込む
require_once は一度だけ取り込む
インクルードファイルがない場合、Fatal errorとして処理を中断
include, include_once
Warningを出力し、処理を継続
sample
ini.php
<?php echo "お客様の信用取引の委託保証金状況(概算)により、追加保証金(追証)の状態となっております。 <br>" ?>
index.php
<?php require("in.php"); require("in.php"); require("in.php"); ?>
require_onceに変更します。
index.php
<?php require_once("in.php"); require_once("in.php"); require_once("in.php"); ?>
github AOuth2
_config.php
<?php require_once './vendor/autoload.php'; session_start(); $github_keys = require('./github-app-keys.php'); $provider = new League\OAuth2\Client\Provider\Github([ 'clientId' => $github_keys['clientId'], 'clientSecret' => $github_keys['clientSecret'], ]); $title = "PHP GitHub Login Sample";
github-app-keys.php
<?php return [ 'clientId' => 'xxxx', 'clientSecret' => 'xxxxxxxx' ];
login.php
<?php require_once '_config.php'; $authUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth2state'] = $provider->getState(); header('Location: '.$authUrl); exit;
callback.php
<?php require_once '_config.php'; if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])){ unset($_SESSION['oauth2state']); exit('Invalid state'); } $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); echo $token.'\n'; echo 'Successfully callbacked!!'.'\n'; $user = $provider->getResourceOwner($token); echo '<pre>'; var_dump($user); echo '</pre>';
[vagrant@localhost api]$ php -S 192.168.33.10:8000
github AOuth
まずComposerを入れます。
$ curl -sS https://getcomposer.org/installer | php
composer.jsonの作成
$ php composer.phar init
[vagrant@localhost api]$ ls composer.json composer.phar google-api-php-client [vagrant@localhost api]$ sudo mv composer.phar /usr/local/bin/composer
GitHubでApplicationをregisterして、Client IDとClient Secretを取得します。
https://github.com/settings/developers
composerで入れます。
[vagrant@localhost api]$ composer require league/oauth2-client league/oauth2-github Using version ^2.3 for league/oauth2-client Using version ^2.0 for league/oauth2-github ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 7 installs, 0 updates, 0 removals - Installing paragonie/random_compat (v2.0.11): Downloading (100%) - Installing guzzlehttp/promises (v1.3.1): Downloading (100%) - Installing psr/http-message (1.0.1): Downloading (100%) - Installing guzzlehttp/psr7 (1.4.2): Downloading (100%) - Installing guzzlehttp/guzzle (6.3.0): Downloading (100%) - Installing league/oauth2-client (2.3.0): Downloading (100%) - Installing league/oauth2-github (2.0.0): Downloading (100%) paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.) guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware) Writing lock file Generating autoload files [vagrant@localhost api]$ ls composer.json composer.lock google-api-php-client vendor
OAuthとは
OAuthは認可情報の委譲のための仕様
-あらかじめ信頼関係を構築したサービス間で、ユーザの同意のもとに、セキュアにユーザの権限を受け渡しする
※自分が利用したいサービスに最低限必要な権限のみを委譲することができる。そのため、basic認証と比べて柔軟かつセキュアな運用が可能
認可情報の委譲を行う仕様には、Google、Yahoo!、Flickr、Facebookなどが独自に提供しているものが
OAuth Service Provider(Google, Yahoo, Twitter)
OAuth Consumer
Users
[vagrant@localhost api]$ php composer.phar ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/ Composer version 1.6.2 2018-01-05 15:28:41 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands: about Shows the short information about Composer. archive Creates an archive of this composer package. browse Opens the package's repository URL or homepage in your browser. check-platform-reqs Check that platform requirements are satisfied. clear-cache Clears composer's internal package cache. clearcache Clears composer's internal package cache. config Sets config options. create-project Creates new project from a package into given directory. depends Shows which packages cause the given package to be installed. diagnose Diagnoses the system to identify common errors. dump-autoload Dumps the autoloader. dumpautoload Dumps the autoloader. exec Executes a vendored binary/script. global Allows running commands in the global composer dir ($COMPOSER_HOME). help Displays help for a command home Opens the package's repository URL or homepage in your browser. info Shows information about packages. init Creates a basic composer.json file in current directory. install Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json. licenses Shows information about licenses of dependencies. list Lists commands outdated Shows a list of installed packages that have updates available, including their latest version. prohibits Shows which packages prevent the given package from being installed. remove Removes a package from the require or require-dev. require Adds required packages to your composer.json and installs them. run-script Runs the scripts defined in composer.json. search Searches for packages. self-update Updates composer.phar to the latest version. selfupdate Updates composer.phar to the latest version. show Shows information about packages. status Shows a list of locally modified packages. suggests Shows package suggestions. update Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file. upgrade Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file. validate Validates a composer.json and composer.lock. why Shows which packages cause the given package to be installed. why-not Shows which packages prevent the given package from being installed.
Analytics API
The Analytics API provides access to Analytics configuration and report data.
最新のgoogle-api-php-client
まず、コマンドラインでphpのバージョンを確認します。
[vagrant@localhost api]$ php -v PHP 5.6.27 (cli) (built: Oct 14 2016 14:06:54) Copyright (c) 1997-2016 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
gitも確認。
[vagrant@localhost api]$ git version git version 2.2.1
githubにあるリポジトリをローカルにcloneします。
[vagrant@localhost api]$ git clone https://github.com/google/google-api-php-client.git Cloning into 'google-api-php-client'... remote: Counting objects: 10177, done. remote: Compressing objects: 100% (16/16), done. remote: Total 10177 (delta 3), reused 8 (delta 2), pack-reused 10158 Receiving objects: 100% (10177/10177), 6.98 MiB | 1.51 MiB/s, done. Resolving deltas: 100% (6953/6953), done. Checking connectivity... done.
入りました。
では、試しに、examplesをサーバーで見てみましょう。
[vagrant@localhost google-api-php-client]$ php -S 192.168.33.10:8000 PHP 5.6.27 Development Server started at Mon Jan 29 16:12:27 2018 Listening on http://192.168.33.10:8000 Document root is /home/vagrant/api/google-api-php-client Press Ctrl-C to quit. [Mon Jan 29 16:12:44 2018] 192.168.33.1:59098 [200]: /examples/ [Mon Jan 29 16:12:44 2018] 192.168.33.1:59099 [200]: /examples/styles/style.css [Mon Jan 29 16:12:44 2018] 192.168.33.1:59101 [404]: /favicon.ico - No such file or directory [Mon Jan 29 16:12:47 2018] 192.168.33.1:59100 Invalid request (Unexpected EOF)