<?php
require_once('./google-api-php-client/src/Google/autoload.php');
session_start();
$client = new Google_Client();
$client->setClientId('クライアントID');
$client->setClientSecret('クライアントシークレット');
$client->setRedirectUri('リダイレクトURI');
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if(isset($_SESSION['token'])){
$client->setAccessToken($_SESSION['token']);
}
if($client->getAccessToken()){
try {
echo "Google Drive Api 連携完了!<br>";
$_SESSION['client'] = $client;
} catch (Google_Exception $e){
echo $e->getMessage();
}
} else {
$client->setScopes(Google_Service_Drive::DRIVE);
$authUrl = $client->createAuthUrl();
echo '<a href="'.$authUrl.'">アプリケーションのアクセスを許可してください。</a>';
exit;
}
?>
<a href="list.php">ファイル一覧</a><br>
<a href="imageview.php">画像表示</a><br>
<a href="upload.php">アップロード</a>
count
countは配列の要素数を数える。
<?php $a[] = "10"; $a[] = "25"; $a[] = "8"; print count( $a ); ?>
では、ストップ高のサンプルです。条件分岐も入れておきましょう。
<?php
$stophigh[] = "ホーブ";
$stophigh[] = "バリューコマース";
$stophigh[] = "オイシックスドット大地";
$stophigh[] = "大村紙業";
$stophigh[] = "国際チャート";
$stophigh[] = "ジャストプランニング";
$stophigh[] = "RSC";
$num = count($stophigh);
if($num>0){
print "本日のストップ高は $num 銘柄です。";
} else {
print "本日ストップ高はありません。";
}
?>

アロー演算子 ->
アロー演算子(->)はクラスやオブジェクトに関係ある演算子です。
1)クラスの例
class
{
public $color = "塗装前";
public $speed = 0;
function run(){
print "{this->color}の車で、時速{$this->speed}kmで走行しています。"
}
}
例がわかりにくいので、立会外分売の例で考えてみましょう。
2)クラスの例2
class Offselling
{
public $price = "終値";
public $discount = 0;
function sales(){
print "終値{$this->price}の株を、割引率{$this->discount}で売り出します。"
}
}
設計図が完成したので、objectを記載します。
<?php
$myCar = new Car;
$myCar->run();
class Car
{
public $color = "塗装前";
public $speed = 0;
function run(){
print "{$this->color}の車で、時速{$this->speed}kmで走行しています。";
}
}
?>

オブジェクトに代入してみます。
<?php
$myCar = new Car;
$myCar->color = "赤い色";
$myCar->speed = 20;
$myCar->run();
class Car
{
public $color = "塗装前";
public $speed = 0;
function run(){
print "{$this->color}の車で、時速{$this->speed}kmで走行しています。";
}
}
?>

では、立会外分売3547串カツ田中でやってみましょう。
<?php
$kushikatu = new Offselling;
$kushikatu->price = "4020";
$kushikatu->discount = 3.01;
$kushikatu->sales();
class Offselling
{
public $price = "終値";
public $discount = 0;
function sales(){
print "終値{$this->price}円の株を、割引率{$this->discount}で売り出します。";
}
}
?>

analytics api
<?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