Ground Sunlight

Windowsで作る - PHPプログラミングの開発環境

ユーザ用ツール

サイト用ツール


slim:4:cookbook

差分

このページの2つのバージョン間の差分を表示します。

この比較画面にリンクする

両方とも前のリビジョン 前のリビジョン
次のリビジョン
前のリビジョン
slim:4:cookbook [2020/10/09 10:32]
y2sunlight [Access-Control-Allow-Methods]
slim:4:cookbook [2020/10/13 21:59] (現在)
y2sunlight [Uploading files using POST forms]
行 22: 行 22:
 ----- -----
  
-===== Trailing in route patterns =====+===== ルートパターンの末尾のスラッシュ(/=====
  
-Slim treats a URL pattern with a trailing slash as different to one without. That is, ''/user'' and ''/user/'' are different and so can have different callbacks attached.+Slimは、末尾にスラッシュがあるURLパターンを、無いものとは異なるものとして扱います。つまり、''/user'' と ''/user/'' は異なるので、異なるコールバックをアタッチできます。
  
 For GET requests a permanent redirect is fine, but for other request methods like POST or PUT the browser will send the second request with the GET method. To avoid this you simply need to remove the trailing slash and pass the manipulated url to the next middleware. For GET requests a permanent redirect is fine, but for other request methods like POST or PUT the browser will send the second request with the GET method. To avoid this you simply need to remove the trailing slash and pass the manipulated url to the next middleware.
  
-If you want to redirect/rewrite all URLs that end in a ''/'' to the non-trailing ''/'' equivalent, then you can add this middleware:+GETリクエストの場合、パーマネント(permanent)リダイレクトは問題ありませんが、POSTやPUTなどの他のリクエストメソッドの場合、ブラウザはGETメソッドを使用して2番目のリクエストを送信します。これを回避するには、単に、末尾のスラッシュを削除し、操作されたURLを次のミドルウェアに渡す必要があります。
  
-Slimは、末尾にスラッシュがあるURLパターンを、ないものとは異なるものとして扱います。 つまり、''/user'' と ''/user/'' は異なるため、異なるコールバックをアタッチできます。 +''/'' で終わるすべてのURLを、末尾以外の ''/'' に相当するものにリダイレクトまたはリライトする場合、次のミドルウェアを追加できます。
- +
-GETリクエストの場合、永続的なリダイレクトは問題ありませんが、POSTやPUTなどの他のリクエストメソッドの場合、ブラウザはGETメソッドを使用して2番目のリクエストを送信します。 これを回避するには、末尾のスラッシュを削除し、操作されたURLを次のミドルウェアに渡す必要があります。 +
- +
-''/'' で終わるすべてのURLを、末尾以外の ''/'' に相当するものにリダイレクト/書き換える場合、次のミドルウェアを追加できます。+
  
 <code php> <code php>
行 73: 行 69:
 </code> </code>
  
-Alternatively, consider [[https://github.com/middlewares/trailing-slash|middlewares/trailing-slash]] middleware which also allows you to force a trailing slash to be appended to all URLs: +あるいは、[[https://github.com/middlewares/trailing-slash|middlewares/trailing-slash]] ミドルウェアを検討してください。これにより、すべてのURLに末尾のスラッシュを強制的に追加することもできます。
- +
-または、[[https://github.com/middlewares/trailing-slash|middlewares/trailing-slash]] ミドルウェアを検討してください。これにより、すべてのURLに末尾のスラッシュを強制的に追加することもできます。+
  
 <code php> <code php>
行 85: 行 79:
 \\ \\
  
-===== Retrieving Current Route ===== +===== 現在のルートの取得 =====
- +
-If you ever need to get access to the current route within your application, you will need to instantiate the ''RouteContext'' object using the incoming ''ServerRequestInterface''.+
  
 アプリケーション内の現在のルートにアクセスする必要がある場合は、着信時の ''ServerRequestInterface'' を使用して ''RouteContext'' オブジェクトをインスタンス化する必要があります。 アプリケーション内の現在のルートにアクセスする必要がある場合は、着信時の ''ServerRequestInterface'' を使用して ''RouteContext'' オブジェクトをインスタンス化する必要があります。
- 
-From there you can get the route via $routeContext->getRoute() and access the route’s name by using getName() or get the methods supported by this route via getMethods(), etc. 
  
 そこから、''$routeContext->getRoute()'' を介してルートを取得し、''getName()'' を使用してルートの名前にアクセスするか、''getMethods()'' などを介してこのルートでサポートされているメソッドを取得できます。 そこから、''$routeContext->getRoute()'' を介してルートを取得し、''getName()'' を使用してルートの名前にアクセスするか、''getMethods()'' などを介してこのルートでサポートされているメソッドを取得できます。
  
-Note: If you need to access the ''RouteContext'' object during the middleware cycle before reaching the route handler you will need to add the ''RoutingMiddleware'' as the outermost middleware before the error handling middleware (See example below). +注:ルート(route)ハンドラーに到達する前にミドルウェアサイクル中に ''RouteContext'' オブジェクトにアクセスする必要がある場合は、エラー処理ミドルウェアの前に、''RoutingMiddleware'' を最も外側のミドルウェアとして追加する必要があります(以下の例を参照)。
- +
-注:ルートハンドラーに到達する前にミドルウェアサイクル中に ''RouteContext'' オブジェクトにアクセスする必要がある場合は、エラー処理ミドルウェアの前に、''RoutingMiddleware'' を最も外側のミドルウェアとして追加する必要があります(以下の例を参照)。 +
- +
-Example:+
  
 例: 例:
行 146: 行 132:
 \\ \\
  
-===== Setting up CORS =====+===== CORSの設定 =====
  
-CORS - Cross origin resource sharing+CORS - クロス オリジンリソース シェアリング(オリジン間リソース共有)
  
-A good flowchart for implementing CORS support Reference:+  * CORSサポートを実装するための適切なフローチャートリファレンス: \\ [[https://www.html5rocks.com/static/images/cors_server_flowchart.png|CORSサーバーのフローチャート]] 
 +  * CORSサポートはここでテストできます:[[http://www.test-cors.org/]] 
 +  * ここで仕様を読むことができます:[[https://www.w3.org/TR/cors/]]
  
-CORS server flowchart+> 参考:https://developer.mozilla.org/ja/docs/Glossary/CORS 
 +==== シンプル ソリューション ====
  
-You can test your CORS Support here: http://www.test-cors.org/+単純なCORSリクエストの場合、サーバーはレスポンスに次のヘッダーを追加するだけで済みます。
  
-You can read the specification here: https://www.w3.org/TR/cors/ +<code>
- +
-CORS-クロスオリジンリソースシェアリング +
- +
-CORSサポートを実装するための適切なフローチャートリファレンス: +
- +
-CORSサーバーのフローチャート +
- +
-CORSサポートはここでテストできます:http://www.test-cors.org/ +
- +
-ここで仕様を読むことができます:https://www.w3.org/TR/cors/ +
-==== The simple solution ==== +
- +
-For simple CORS requests, the server only needs to add the following header to its response: +
- +
-単純なCORSリクエストの場合、サーバーは応答に次のヘッダーを追加するだけで済みます。 +
- +
-<code php>+
 Access-Control-Allow-Origin: <domain>, ...  Access-Control-Allow-Origin: <domain>, ... 
 </code> </code>
行 179: 行 151:
 The following code should enable lazy CORS. The following code should enable lazy CORS.
  
-次のコードは、レイジーCORSを有効にする必要があります。+次のコードは、Lazy CORS を有効にする必要があります。
  
 <code php> <code php>
行 194: 行 166:
 }); });
 </code> </code>
- 
-Add the following route as the last route: 
  
 最後のルートとして次のルートを追加します: 最後のルートとして次のルートを追加します:
行 215: 行 185:
  
 ==== Access-Control-Allow-Methods ==== ==== Access-Control-Allow-Methods ====
- 
-The following middleware can be used to query Slim’s router and get a list of methods a particular pattern implements. 
- 
-Here is a complete example application: 
  
 次のミドルウェアを使用して、Slimのルーターにクエリを実行し、特定のパターンが実装するメソッドのリストを取得できます。 次のミドルウェアを使用して、Slimのルーターにクエリを実行し、特定のパターンが実装するメソッドのリストを取得できます。
行 334: 行 300:
  
 ==== Access-Control-Allow-Credentials ==== ==== Access-Control-Allow-Credentials ====
 +
 +リクエストに資格情報(Cookie、承認ヘッダー、またはTLSクライアント証明書)が含まれている場合は、レスポンスオブジェクトに ''Access-Control-Allow-Credentials'' ヘッダーを追加する必要がある場合があります。
  
 <code php> <code php>
 +$response = $response->withHeader('Access-Control-Allow-Credentials', 'true');
 </code> </code>
  
 \\ \\
  
-===== Uploading files using POST forms =====+===== POSTフォームを使ったファイルのアップロード ===== 
 + 
 +POSTリクエストのフォームを使用してアップロードされたファイルは、Requestメソッド ''getUploadedFiles()'' を使用して取得できます。 
 + 
 +POSTリクエストを使用してファイルをアップロードする場合は、ファイルアップロードフォームに属性 ''enctype="multipart/form-data"'' があることを確認してください。そうでない場合、''getUploadedFiles()'' は空の配列を返します。 
 + 
 +同じ input name に対して複数のファイルがアップロードされる場合は、HTMLのinput nameの後に鍵括弧( ''[]'' )を追加します。そうでない場合、''getUploadedFiles()'' によってinput nameに対してアップロードされたファイルが1つだけ返されます。 
 + 
 +以下は、単一ファイルと複数ファイルの両方のアップロードを含むHTMLフォームの例です。
  
 <code php> <code php>
 +<!-- make sure the attribute enctype is set to multipart/form-data -->
 +<form method="post" enctype="multipart/form-data">
 +    <!-- upload of a single file -->
 +    <p>
 +        <label>Add file (single): </label><br/>
 +        <input type="file" name="example1"/>
 +    </p>
 +
 +    <!-- multiple input fields for the same input name, use brackets -->
 +    <p>
 +        <label>Add files (up to 2): </label><br/>
 +        <input type="file" name="example2[]"/><br/>
 +        <input type="file" name="example2[]"/>
 +    </p>
 +
 +    <!-- one file input field that allows multiple files to be uploaded, use brackets -->
 +    <p>
 +        <label>Add files (multiple): </label><br/>
 +        <input type="file" name="example3[]" multiple="multiple"/>
 +    </p>
 +
 +    <p>
 +        <input type="submit"/>
 +    </p>
 +</form>
 </code> </code>
 +
 +アップロードされたファイルは、''moveTo'' メソッドを使用してディレクトリに移動できます。以下は、上記のHTMLフォームのアップロードされたファイルを処理するサンプルアプリケーションです。
  
 <code php> <code php>
 +<?php
 +
 +use DI\ContainerBuilder;
 +use Psr\Http\Message\ResponseInterface;
 +use Psr\Http\Message\ServerRequestInterface;
 +use Psr\Http\Message\UploadedFileInterface;
 +use Slim\Factory\AppFactory;
 +
 +require __DIR__ . '/../vendor/autoload.php';
 +
 +$containerBuilder = new ContainerBuilder();
 +$container = $containerBuilder->build();
 +
 +$container->set('upload_directory', __DIR__ . '/uploads');
 +
 +AppFactory::setContainer($container);
 +$app = AppFactory::create();
 +
 +$app->post('/', function (ServerRequestInterface $request, ResponseInterface $response) {
 +    $directory = $this->get('upload_directory');
 +    $uploadedFiles = $request->getUploadedFiles();
 +
 +    // handle single input with single file upload
 +    $uploadedFile = $uploadedFiles['example1'];
 +    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
 +        $filename = moveUploadedFile($directory, $uploadedFile);
 +        $response->getBody()->write('Uploaded: ' . $filename . '<br/>');
 +    }
 +
 +    // handle multiple inputs with the same key
 +    foreach ($uploadedFiles['example2'] as $uploadedFile) {
 +        if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
 +            $filename = moveUploadedFile($directory, $uploadedFile);
 +            $response->getBody()->write('Uploaded: ' . $filename . '<br/>');
 +        }
 +    }
 +
 +    // handle single input with multiple file uploads
 +    foreach ($uploadedFiles['example3'] as $uploadedFile) {
 +        if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
 +            $filename = moveUploadedFile($directory, $uploadedFile);
 +            $response->getBody()->write('Uploaded: ' . $filename . '<br/>');
 +        }
 +    }
 +
 +    return $response;
 +});
 +
 +/**
 + * Moves the uploaded file to the upload directory and assigns it a unique name
 + * to avoid overwriting an existing uploaded file.
 + *
 + * @param string $directory The directory to which the file is moved
 + * @param UploadedFileInterface $uploadedFile The file uploaded file to move
 + *
 + * @return string The filename of moved file
 + */
 +function moveUploadedFile(string $directory, UploadedFileInterface $uploadedFile)
 +{
 +    $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
 +
 +    // see http://php.net/manual/en/function.random-bytes.php
 +    $basename = bin2hex(random_bytes(8));
 +    $filename = sprintf('%s.%0.8s', $basename, $extension);
 +
 +    $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
 +
 +    return $filename;
 +}
 +
 +$app->run();
 </code> </code>
  
 \\ \\
  
slim/4/cookbook.1602207168.txt.gz · 最終更新: 2020/10/09 10:32 by y2sunlight