PHP 8.3.4 Released!

実行時設定

php.ini の設定により動作が変化します。

セッションの設定オプション
名前 デフォルト 変更可能 変更履歴
session.save_path "" INI_ALL  
session.name "PHPSESSID" INI_ALL  
session.save_handler "files" INI_ALL  
session.auto_start "0" INI_PERDIR  
session.gc_probability "1" INI_ALL  
session.gc_divisor "100" INI_ALL  
session.gc_maxlifetime "1440" INI_ALL  
session.serialize_handler "php" INI_ALL  
session.cookie_lifetime "0" INI_ALL  
session.cookie_path "/" INI_ALL  
session.cookie_domain "" INI_ALL  
session.cookie_secure "0" INI_ALL PHP 7.2.0 より前のバージョンでは、デフォルト値は "" でした。
session.cookie_httponly "0" INI_ALL PHP 7.2.0 より前のバージョンでは、デフォルト値は "" でした。""
session.cookie_samesite "" INI_ALL PHP 7.3.0 から利用可能
session.use_strict_mode "0" INI_ALL  
session.use_cookies "1" INI_ALL  
session.use_only_cookies "1" INI_ALL  
session.referer_check "" INI_ALL  
session.cache_limiter "nocache" INI_ALL  
session.cache_expire "180" INI_ALL  
session.use_trans_sid "0" INI_ALL  
session.trans_sid_tags "a=href,area=href,frame=src,form=" INI_ALL PHP 7.1.0 から利用可能
session.trans_sid_hosts $_SERVER['HTTP_HOST'] INI_ALL PHP 7.1.0 から利用可能
session.sid_length "32" INI_ALL PHP 7.1.0 から利用可能
session.sid_bits_per_character "4" INI_ALL PHP 7.1.0 から利用可能
session.upload_progress.enabled "1" INI_PERDIR  
session.upload_progress.cleanup "1" INI_PERDIR  
session.upload_progress.prefix "upload_progress_" INI_PERDIR  
session.upload_progress.name "PHP_SESSION_UPLOAD_PROGRESS" INI_PERDIR  
session.upload_progress.freq "1%" INI_PERDIR  
session.upload_progress.min_freq "1" INI_PERDIR  
session.lazy_write "1" INI_ALL  
session.hash_function "0" INI_ALL PHP 7.1.0 で削除されました。
session.hash_bits_per_character "4" INI_ALL PHP 7.1.0 で削除されました。
session.entropy_file "" INI_ALL PHP 7.1.0 で削除されました。
session.entropy_length "0" INI_ALL PHP 7.1.0 で削除されました。
INI_* モードの詳細および定義については どこで設定を行うのか を参照してください。

セッション管理システムは、php.iniファイルに記述可能な多くの設定オ プションをサポートします。以下に概要を示します。

session.save_handler string
session.save_handler は、 セッションに関連するデータの保存および取得時に使用するハンドラを定義します。 デフォルトは、files です。各拡張モジュールで、 独自の save_handler を使用できることに注意しましょう。 インストール環境単位で登録されているハンドラを取得するには phpinfo() を使用します。 session_set_save_handler() も参照ください。
session.save_path string
session.save_path は、保存ハンドラに渡される 引数を定義します。デフォルトのファイルハンドラを選択した場合、 ファイルが作成される場所のパスになります。 session_save_path() も参照ください。

オプションの引数として N(数値)を指定できます。 これはセッションファイルを分散して保存する際に ディレクトリ階層レベルを決定します。 例えば、'5;/tmp'とすると /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If という位置にセッションファイルを生成します。 N を使用するには、これらすべてのディレクトリが 事前に作成されている必要があります。 そのためのシェルスクリプトがext/sessionmod_files.shというファイル名であります。 Windows 版の mod_files.bat もあります。 また、0以上の N が指定されている場合には自動ガーベッジコレクション が機能しないことに注意してください。詳細は php.ini を見てください。 また、N を指定する場合は、 session.save_pathを"quotes"で囲う必要があります。 なぜならセパレータ(;) は php.ini ではコメントとしても利用されているからです。

ファイルストレージモジュールが作るファイルのモードは、デフォルトで 600 になります。 このデフォルトを変更するには、オプションの引数 MODE を利用します。 N;MODE;/path のように使い、MODE の部分に八進形式のモードを指定します。MODE を設定しても、そのプロセスの umask は変わりません。

警告

この設定を /tmp (デフォルト) のようにどこか らでも読み込み可能なディレクトリに設定した場合、サーバー上 の他のユーザーがこのディレクトリのファイルのリストを取得すること により、セッションをハイジャックをすることが可能となります。

警告

オプションのディレクトリレベル定数 N で、 1 あるいは 2 以外の値を使うのは、大半のサイトでは不適切です。 大量のディレクトリが必要になってしまうからです。たとえば、この値を 3 にすると、 ファイルシステム上のディレクトリの数が (2 ** session.sid_bits_per_character) ** 3 にもなり、 ディスク容量や inode の無駄遣いになってしまいます。

N を 2 より大きくするのは、 それを必要とするような大規模サイトに限るようにしましょう。

session.name string
session.name はセッション名を指定し、 クッキー名として使用されます。 アルファベット文字のみで指定する必要があります。 デフォルトは、PHPSESSID です。 session_name()も参照ください。
session.auto_start bool
session.auto_start はリクエスト開始時に セッションモジュールがセッションを自動的に開始するかどうかを 指定します。デフォルトは、0(無効)です。
session.serialize_handler string
session.serialize_handler は、シリアル化または シリアル化データを復元するために使用されるハンドラの名前を定義します。 PHP シリアライズフォーマット (php_serialize)、 PHP 内部フォーマット (php あるいは php_binary)、 そして WDDX (wddx) に対応しています。WDDX は、PHP がWDDX サポート を有効にしてコンパイルされている場合のみ使用可能です。 php_serialize はプレーンな serialize/unserialize 関数を内部的に使っており、phpphp_binary のような制約はありません。これらのシリアライズハンドラでは、$_SESSION の中で数値のインデックスや特殊文字 (|!) を含む文字列のインデックスを使えませんでした。 php_serialize を使えば、 スクリプトの終了時に数値インデックスや特殊文字インデックスのエラーが出ないようにできます。 デフォルトは php です。
session.gc_probability int
session.gc_probabilitysession.gc_divisorの組み合わせでgc (ガーベッジコレクション)ルーチンの始動を制御します。 デフォルトは、1 です。 詳細はsession.gc_divisor をご覧ください
session.gc_divisor int
session.gc_divisorsession.gc_probabilityの組み合わせで すべてのセッションの初期化過程でgc(ガーベッジコネクション)プロセス も始動する確率を制御します。確率は gc_probability/gc_divisor で計算されます。例えば、1/100は各リクエスト毎に1%の確率でGCプロセスが 始動します。 session.gc_divisorのデフォルトは100です。
session.gc_maxlifetime int
session.gc_maxlifetime は、データが 'ごみ' とみなされ、消去されるまでの秒数を指定します。 ガベージコレクション (ごみの収集) は、 セッションの開始時に行われます (session.gc_probabilitysession.gc_divisor に依存します)。 デフォルトは 1440 (24分) です。

注意: 異なる値を session.gc_maxlifetime に指定している 別々のスクリプトがセッションデータの保存場所を共有している場合、 一番小さい設定値に達した時点でデータが消去されます。このような場合には、 お互いに session.save_path を使用します。

session.referer_check string
session.referer_check には、HTTP Referer に おいて確認を行う文字列を指定します。Refererがクライアントにより 送信されており、かつ、指定した文字列が見付からない場合、埋め込 まれたセッションIDは無効となります。デフォルトは空の文字列です。
session.entropy_file string
session.entropy_file は、 セッションIDを作成する際の別のエントロピーソースとして使用する 外部リソースへのパスを指定します。 例としては、多くの UNIX で利用可能な /dev/random または /dev/urandom があげられます。 この機能は、Windows でもサポートされています。 session.entropy_length にゼロ以外の値を設定すると、 PHP は Windows Random API をエントロピーソースとして使います。

注意: PHP 7.1.0 で削除されました。 /dev/urandom あるいは /dev/arandom が使えるときは、 それが session.entropy_file のデフォルトになります。

session.entropy_length int
session.entropy_length は、前記のファイルから 読みこむバイト数を指定します。デフォルトは、32 です。 PHP 7.1.0 で削除されました。
session.use_strict_mode bool
session.use_strict_mode は、 厳格なセッション ID モードを利用するかどうかを指定します。 有効にすると、初期化していないセッション ID を受け付けなくなります。 初期化していないセッション ID がブラウザから送信された場合は、 新しいセッション ID をブラウザに送り返します。 このモードを利用すると、セッションアダプションを利用したセッション固定攻撃からアプリケーションを保護できます。 デフォルトは 0 (無効) です。

注意: 一般的なセッションのセキュリティを踏まえると、 session.use_strict_mode を有効にしておく必要があります。 すべてのサイトでこれを有効にすることを推奨します。 詳細は session_create_id() のサンプルコードを参照ください。

警告

カスタムのセッションハンドラが session_set_save_handler() 経由で登録され、 それが SessionUpdateTimestampHandlerInterface::validateId() を実装せず、 validate_sid コールバックを提供しない場合、 このディレクティブの値に関わらず、厳格なセッションIDモードは無効になります。 SessionHandler クラスは SessionHandler::validateId() を実装して いない ことに特に注意して下さい。

session.use_cookies bool
session.use_cookiesによりクライアント側にセッ ションIDを保存する際にクッキーを使用するかどうかを指定します。デ フォルトは1 (有効)です。
session.use_only_cookies bool
session.use_only_cookies は、 このモジュールがクライアント側へのセッション ID の保存に Cookie のみ を使用することを指定します。 この設定を有効にすることにより、セッション ID を URL に埋め込む攻撃を防ぐことができます。 デフォルトは 1 (有効) となります。
session.cookie_lifetime int
session.cookie_lifetime は、 ブラウザに送信するクッキーの有効期間を秒単位で指定します。 0 を指定すると "ブラウザを閉じるまで" という意味になります。 デフォルトは、0 です。 session_get_cookie_params() および session_set_cookie_params() も参照ください。

注意: 有効期限のタイムスタンプは、サーバーの時刻に基づいて決まります。 クライアントのブラウザの時刻がこれと同じであるとは限りません。

session.cookie_path string
session.cookie_path によりセッションクッキーで設定するパスを指定します。 デフォルトは/です。 session_get_cookie_params()および session_set_cookie_params()も参照ください。
session.cookie_domain string
session.cookie_domain によりセッションクッキーで指定するドメインを指定します。 デフォルトでは指定されません。 この場合は、クッキーの仕様によって、クッキーを作成したサーバーの ホスト名が指定されます。 session_get_cookie_params() および session_set_cookie_params() も参照ください。
session.cookie_secure bool
クッキーはセキュアな接続を通じてのみ送信すべきものです。 このオプションを on にすると、 セッションは HTTPS 接続の場合にのみ動作します。 off の場合には、HTTP と HTTPS 接続の両方で動作します。 デフォルトは off です。
session.cookie_httponly bool
クッキーに対して、HTTP を通してのみアクセスできるようにします。 つまり、JavaScript のようなスクリプト言語からはアクセスできなくなるということです。 この設定を使用すると、XSS 攻撃によって ID を盗まれる危険性を減らせます (が、すべてのブラウザがこの設定をサポートしているというわけではありません)。
session.cookie_samesite string
クロスサイトリクエストで、サーバーにクッキーを送信しないよう指示できるようにします。 これを用いると、ユーザーエージェントによる生成元とは異なる場所への情報漏洩のリスクを軽減できます。 また、CSRF攻撃に対する防御策のひとつにもなります。 この仕組みはすべてのブラウザがサポートしているわけではないことに注意しましょう。 この項目に空の値を設定した場合は、クッキーのSameSite属性は送信されません。 LaxStrict を設定した場合は、 サイトをまたがる POST リクエストではクッキーを送信しません。GET リクエストの場合は、 Lax はサイトをまたがるリクエストでもクッキーを送信しますが、 Strict は送信しません。
session.cache_limiter string
session.cache_limiter により、セッションページにおけるキャッシュ制御の方法を指定します。 nocacheprivateprivate_no_expire あるいは public のいずれかとなります。デフォルトは nocache です。 これらの値の意味については session_cache_limiter() のドキュメントも参照ください。
session.cache_expire int
session.cache_expireによりキャッシュされた セッションページの有効期間を分単位で指定します。 このオプションは、nocacheリミッタに関しては効果がありません。 デフォルトは、180です。 session_cache_expire()も参照ください。
session.use_trans_sid bool
session.use_trans_sidは、透過的なセッション IDの付加をするかどうかを指定します。 デフォルトは、0(無効)です。

注意: URLに基づくセッション管理は、Cookieに基づくセッション管理と比べ てセキュリティリスクが大きくなります。例えば、ユーザーは、emailに より友人にアクティブなセッションIDを含むURLを送信する可能性があ り、また、ユーザーは自分のブックマークにセッションIDを含むURLを保 存し、常に同じセッションIDで使用するサイトにアクセスする可能性 があります。 PHP 7.1.0 以降では、https://php.net/ のような完全な URL パスが、透過的セッションID機能で扱われるようになります。 これより前のバージョンでは、相対 URL パスだけが対象でした。 リライト対象のホストは session.trans_sid_hosts で定義します。

session.trans_sid_tags string
session.trans_sid_tags は、透過的セッションIDのサポートが有効な場合にどの HTML タグをリライトするかを指定します。 デフォルトは a=href,area=href,frame=src,input=src,form= です。 form は特別なタグで、<input hidden="session_id" name="session_name"> がフォーム変数に追加されます。

注意: PHP 7.1.0 より前のバージョンでは、この目的で使われていた設定項目は url_rewriter.tags でした。 PHP 7.1.0 以降は、fieldset が特別なタグとはみなされなくなります。

session.trans_sid_hosts string
session.trans_sid_hosts は、 は、透過的セッションIDのサポートが有効な場合にどのホストをセッションIDつきにリライトするかを指定します。 デフォルトは $_SERVER['HTTP_HOST'] です。 複数のホストを指定する場合は "," で区切ってつなぎます。 ホストとホストの間にスペースを入れることはできません。つまり、たとえば php.net,wiki.php.net,bugs.php.net のように指定します。
session.sid_length int
session.sid_length は、セッション ID 文字列の長さを指定します。 22 から 256 までの値が使えます。 デフォルトは 32 です。互換性を考慮するなら 32 や 40 などを使ってもかまいません。 セッション ID は長ければ長いほど推測されにくくなります。少なくとも 32 を指定することを推奨します。
ヒント

互換性に関するメモ: session.hash_function=0 (MD5) で session.hash_bits_per_character=4 の場合、あるいは session.hash_function=1 (SHA1) で session.hash_bits_per_character=6 の場合は 32 を使います。 session.hash_function=0 (MD5) で session.hash_bits_per_character=5 の場合は、26 を使います。 session.hash_function=0 (MD5) で session.hash_bits_per_character=6 の場合は、22 を使います。 INI 設定で、セッション ID を少なくとも 128 ビットにしておく必要があります。 session.sid_bits_per_character に適切な値を指定することを忘れないようにしましょう。 そうしないと、脆弱なセッション ID を使うことになってしまいます。

注意: この設定は PHP 7.1.0 で導入されました。

session.sid_bits_per_character int
session.sid_bits_per_character エンコードされたセッション ID 文字のビット数を指定します。指定できる値は '4' (0-9, a-f)、'5' (0-9, a-v)、'6' (0-9, a-z, A-Z, "-", ",") です。 デフォルトは 4 です。大きいほどセッション ID が強力になります。 大半のシステムでは、5 を推奨します。

注意: この設定は PHP 7.1.0 で導入されました。

session.hash_function mixed
session.hash_function によりセッション ID を生成するために使用されるハッシュアルゴリズムを指定することが可能です。 '0' は MD5 (128 ビット) で、'1' は SHA-1 (160 ビット) を意味します。

hash 拡張モジュール の任意のアルゴリズムが (この拡張モジュールが使用可能な場合に) 指定できます。たとえば sha512whirlpool などです。 サポートされているアルゴリズムの一覧は、 hash_algos() 関数で取得できます。

注意:

この設定は、PHP 7.1.0 で削除されました。

session.hash_bits_per_character int
session.hash_bits_per_character により バイナリのハッシュデータを何らかの可読なデータに変換する際、 それぞれの文字に何ビットストアさせるかを定義することが可能です。 指定可能な値は、'4' (0-9, a-f)、'5' (0-9, a-v) そして '6' (0-9, a-z, A-Z, "-", ",") です。

注意:

この設定は、PHP 7.1.0 で削除されました。

session.upload_progress.enabled bool
アップロードの進捗を追跡して $_SESSION 変数に格納するかどうか。 デフォルトは 1 で、この機能は有効になっています。
session.upload_progress.cleanup bool
すべての POST データを読み終えた (つまり、アップロードが完了した) 時点ですぐに進捗状況を消去するかどうか。 デフォルトは 1 で、この機能は有効になっています。

注意: この機能を有効にしておくことを強くおすすめします。

session.upload_progress.prefix string
アップロードの進捗を $_SESSION で管理するときに使うキーのプレフィックス。 このキーを $_POST[ini_get("session.upload_progress.name")] の値と連結して、一意なインデックスを作ります。 デフォルトは "upload_progress_" です。
session.upload_progress.name string
進捗情報を $_SESSION に格納するときに使うキーの名前。 session.upload_progress.prefix も参照ください。 $_POST[ini_get("session.upload_progress.name")] が渡されていない場合や存在しない場合は、アップロードの進捗を記録しません。 デフォルトは "PHP_SESSION_UPLOAD_PROGRESS" です。
session.upload_progress.freq mixed
アップロードの進捗を更新する頻度を定義します。 バイト数 (100 バイトごとに進捗を更新するなど) あるいはパーセンテージ (ファイル全体のサイズの 1% ごとに進捗を更新するなど) で指定できます。 デフォルトは "1%" です。
session.upload_progress.min_freq int
更新間隔の最小値。単位は秒。 デフォルトは "1" (1 秒) です。
session.lazy_write bool
session.lazy_write を 1 に設定すると、 セッションのデータが変更されたときにだけ再書き込みを行います。 デフォルトは 1 で、この機能は有効になっています。

アップロードの進捗は、 session.upload_progress.enabled を有効にして $_POST[ini_get("session.upload_progress.name")] を設定するまでは登録されません。 この機能の詳細は セッションのアップロードの進捗 を参照ください。

add a note

User Contributed Notes 25 notes

up
34
Walerian Walawski - https://w87.eu/
5 months ago
Can't find mod_files.sh? Here it is:
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

#!/usr/bin/env bash

if [[ "$2" = "" ]] || [[ "$3" = "" ]]; then
echo "Usage: $0 BASE_DIRECTORY DEPTH BITS_PER_CHAR"
echo "BASE_DIRECTORY will be created if it doesn't exist"
echo "DEPTH must be an integer number >0"
echo "BITS_PER_CHAR(session.sid_bits_per_character) should be one of 4, 5, or 6."
# http://php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character
exit 1
fi

if [[ "$2" = "0" ]] && [[ ! "$4" = "recurse" ]]; then
echo "Can't create a directory tree with depth of 0, exiting."
fi

if [[ "$2" = "0" ]]; then
exit 0
fi

directory="$1"
depth="$2"
bitsperchar="$3"

hash_chars="0 1 2 3 4 5 6 7 8 9 a b c d e f"

if [[ "$bitsperchar" -ge "5" ]]; then
hash_chars="$hash_chars g h i j k l m n o p q r s t u v"
fi

if [[ "$bitsperchar" -ge "6" ]]; then
hash_chars="$hash_chars w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - ,"
fi

while [[ -d $directory ]] && [[ $( ls $directory ) ]]; do
echo "Directory $directory is not empty! What would you like to do?"

options="\"Delete directory contents\" \"Choose another directory\" \"Quit\""
eval set $options
select opt in "$@"; do

if [[ $opt = "Delete directory contents" ]]; then
echo "Deleting $directory contents... "
rm -rf $directory/*
elif [[ $opt = "Choose another directory" ]]; then
echo "Which directory would you like to choose?"
read directory
elif [[ $opt = "Quit" ]]; then
exit 0
fi

break;
done
done

if [[ ! -d $directory ]]; then
mkdir -p $directory
fi

echo "Creating session path in $directory with a depth of $depth for session.sid_bits_per_character = $bitsperchar"

for i in $hash_chars; do
newpath="$directory/$i"
mkdir $newpath || exit 1
bash $0 $newpath `expr $depth - 1` $bitsperchar recurse
done
up
77
Christopher Kramer
9 years ago
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime).

You can adjust the global value in your php.ini (usually /etc/php5/apache2/php.ini). Or you can change the session.save_path so debian's cronjob will not clean up your sessions anymore. Then you need to either do your own garbage collection with your own cronjob or enable PHP's garbage collection (php then needs sufficient privileges on the save_path).

Why does Debian not use PHP's garbarage collection?
For security reasons, they store session data in a place (/var/lib/php5) with very stringent permissions. With the sticky bit set, only root is allowed to rename or delete files there, so PHP itself cannot clean up old session data. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267720 .
up
18
GreenReaper
9 years ago
We found a session.save_path depth of 3 led to excessive wastage of inodes and in fact disk space in storing the directory tree. dir_indexes option on ext2/3/4 makes larger directories more feasible anyway, so we decided to move to a depth of 2 instead.

It took a little puzzling to figure out how to move the existing PHP sessions up one directory tree, but we ended up running this in the root sessions directory:

#!/bin/sh
for a in ./* ; do
cd ./$a
pwd
for b in ./* ; do
cd ./$b
pwd
# Move existing sessions out
find ./* -xdev -type f -print0 | xargs -0 mv -t .
# Remove subdirectories
find ./* -xdev -type d -print0 | xargs -0 rmdir
cd ..
done
cd ..
done

This script may not be the best way to do it, but it got the job done fast. You can modify it for different depths by adding or removing "for" loops.

The documentation gives a depth of 5 as an example, but five is right out. If you're going beyond 2, you're at the scale where you may want to to look at a large memcached or redis instance instead.
up
16
info at thimbleopensource dot com
8 years ago
I found out that if you need to set custom session settings, you only need to do it once when session starts. Then session maintains its settings, even if you use ini_set and change them, original session still will use it's original setting until it expires.

Just thought it might be useful to someone.
up
1
zch1
2 months ago
the pwd should be urlencode when it contanis special chars.
eg:

save_handler:redis
save_path: tcp://127.0.0.1:6739?auth=urlencode('xxxxx')
up
5
boan dot web at outlook dot com
5 years ago
session.cache_limiter may be empty string to disable cache headers entirely.

Quote:
> Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

http://php.net/manual/en/function.session-cache-limiter.php
up
8
Wouter
13 years ago
When setting the session.cookie_lifetime directive in a .htaccess use string format like;

php_value session.cookie_lifetime "123456"

and not

php_value session.cookie_lifetime 123456

Using a integer as stated above dit not work in my case (Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g)
up
7
jlevene at etisoftware dot com
11 years ago
Being unable to find an actual copy of mod_files.sh, and seeing lots of complaints/bug fix requests for it, here's one that works. It gets all its parameters from PHP.INI, so you don't have the opportunity to mess up:

#!/bin/bash
#
# Creates directories for PHP session storage.
# Replaces the one that "comes with" PHP, which (a) doesn't always come with it
# and (b) doesn't work so great.
#
# This version takes no parameters, and uses the values in PHP.INI (if it
# can find it).
#
# Works in OS-X and CentOS (and probably all other) Linux.
#
# Feb '13 by Jeff Levene.

[[ $# -gt 0 ]] && echo "$0 requires NO command-line parameters.
It gets does whatever is called for in the PHP.INI file (if it can find it).
" && exit 1

# Find the PHP.INI file, if possible:
phpIni=/usr/local/lib/php.ini # Default PHP.INI location
[[ ! -f "$phpIni" ]] && phpIni=/etc/php.ini # Secondary location
[[ ! -f "$phpIni" ]] && phpIni= # Found it?

# Outputs the given (as $1) parameter from the PHP.INI file:
# The "empty" brackets have a SPACE and a TAB in them.
#
PhpConfigParam() {
[[ ! "$phpIni" ]] && return
# Get the line from the INI file:
varLine=`grep "^[ ]*$1[ ]*=" "$phpIni"`

# Extract the value:
value=`expr "$varLine" : ".*$1[ ]*=[ ]*['\"]*\([^'\"]*\)"`
echo "$value"
}

if [[ "$phpIni" ]]
then
savePath=`PhpConfigParam session.save_path`
# If there's a number and semicolon at the front, remove them:
dirDepth=`expr "$savePath" : '\([0-9]*\)'`
[[ "$dirDepth" ]] && savePath=`expr "$savePath" : '[0-9]*;\(.*\)'` || dirDepth=0
bits=`PhpConfigParam session.hash_bits_per_character`
case "x$bits" in
x) echo "hash_bits_per_character not defined. Not running." ; exit 2 ;;
x4) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f' ;;
x5) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v' ;;
x6) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v'
alphabet="$alphabet w x y z A B C D E F G H I J K L M N O P Q R S T U V W"
alphabet="$alphabet X Y Z - ,"
;;
*) echo "unrecognized hash_bits_per_character. Not running." ; exit 2 ;;
esac
else
echo "Cannot find the PHP.INI file. Not running. Sorry."
exit 2
fi

# The depth of directories to create is $1. 0 means just create the named
# directory. Directory to start with is $2.
#
# Used recursively, so variables must be "local".

doDir() {
local dir="$2"
if [[ -d "$dir" ]]
then
echo "Directory '$dir' already exists. No problem."
elif [[ -f "$dir" ]]
then
echo "FILE '$dir' exists. Aborting." ; exit 2
else
if mkdir "$dir"
then
echo "Directory '$dir' created."
else
echo "Cannot create directory '$dir'. Aborting." ; exit 2
fi
fi
chmod a+rwx "$dir"
if [[ $1 -gt 0 ]]
then
local depth=$(( $1 - 1 ))
for letter in $alphabet
do doDir $depth "$dir/$letter"
done
fi
}


echo "Running with savePath='$savePath', dirDepth=$dirDepth, and bitsPerCharacter=$bits."
sleep 3

doDir $dirDepth "$savePath"

exit 0
up
7
hassankhodadadeh at NOSPAM dot gmail dot com
11 years ago
max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause php session stops working.
up
2
li-lingjie
6 years ago
Use SessionHandlerInterface interface Custom redis session, found the following:

Use ini_set ('session.save_path', "tcp: //127.0.0.1: 6379? Auth = password"); will be reported:

PHP Fatal error: session_start (): Failed to initialize storage module: user (path: tcp: //127.0.0.1: 6379? Auth = password);

Using session_save_path ("tcp: //127.0.0.1: 6379? Auth = password") will not
up
3
Nicholas
13 years ago
Transient sessions do not appear to be working in 5.3.3

E.g.

<?php
ini_set
("session.use_cookies", 0);
ini_set("session.use_trans_sid", 1);
session_start();

if (isset(
$_SESSION["foo"])) {
echo
"Foo: " . $_SESSION["foo"];
} else {
$_SESSION["foo"] = "Bar";
echo
"<a href=?" . session_name() . "=" . session_id() . ">Begin test</a>";
}
?>

This works in 5.2.5, but not 5.3.3
up
1
theking2(at)king.ma
21 days ago
Please be careful with the 'sid_length' when setting 'sid_bits_per_character' to six.

Setting sid_bits_per_character to 6 includes the character "," to the list of possible characters. A comma will be escaped and transmitted as "%2C" (tested on Chromium Version 119.0.6045.199) adding two extra characters for each comma to the SESSION_ID.
up
0
theking2(at)king.ma
15 days ago
To prevent mitm-attacks you want to make sure the session cookie is only transmitted over a secure channel prefix it with the magic string "__Secure-". [1]

Like :
<?php
session_start
( [ 'name' => '__Secure-Session-ID' ] );
?>

The cookie will not be available on non-secure channel.

(Putting this note it here probably goes unnoticed because of all the noise)

[1]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
up
-1
usrhlp at yahoo dot com
13 days ago
The session.save-path doesn't work in 8.3.3 as it did in previous versions on windows / IIS.

upgrading from 8.1 to 8.3 causes the session save path to be interpreted differently.

To fix this you have to write the absolute path to the session folder location within php.ini.

An example on windows using IIS would be something along the lines of

C:\inetpub\wwwroot\sessiontmp

Leaving the session path line commented out or even specifying "\tmp" within php.ini causes the session path to be incorrectly assigned which prevents all sessions from being created. After manually adding the full local server path for your session temporary folder within PHP.INI, can sessions be created again.

Even creating the folders in the correct location within your inetpub folder fails to fix the issue with the 8.3.3.

Reverting back to PHP 8.1.26 also reverts the behaviour back to previous and all default PHP.INI settings work correctly and sessions can be created as expected. This shows it is an issue with PHP 8.3.3.

I spent 3 hours diagnosing that error hopefully i have saved you time too.
up
0
ohcc at 163 dot com
6 years ago
You should take more care configuring session.gc_maxlifetime when virtual hosts share the same session-saving directory. One host's session data may be gc'ed when another host runs php.
up
-1
AskApache
13 years ago
This is how I set my session.save_path
session.save_path = "1;/home/askapache/tmp/s"
So to create the folder structure you can use this compatible shell script, if you want to create with 777 permissions change the umask to 0000;
sh -o braceexpand -c "umask 0077;mkdir -p s/{0..9}/{a..z} s/{a..z}/{0..9}"

Then you can create a cronjob to clean the session folder by adding this to your crontab which deletes any session files older than an hour:
@daily find /home/askapache/tmp/s -type f -mmin +60 -exec rm -f {} \; &>/dev/null

That will create sessions in folder like:
/home/askapache/tmp/s/b/sess_b1aba5q6io4lv01bpc6t52h0ift227j6

I don't think any non-mega site will need to go more than 1 levels deep. Otherwise you create so many directories that it slows the performance gained by this.
up
-2
00 at f00n dot com
15 years ago
After having many problems with garbage collection not clearing my sessions I have resolved it through the following.

First I found this in the php.ini (not something i noticed as i use phpinfo(); to see my hosting ini).

; NOTE: If you are using the subdirectory option for storing session files
; (see session.save_path above), then garbage collection does *not*
; happen automatically. You will need to do your own garbage

; collection through a shell script, cron entry, or some other method. ; For example, the following script would is the equivalent of
; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
; cd /path/to/sessions; find -cmin +24 | xargs rm

With this is mind there are options.

1. dont use a custom save_path.
** This means if your isp hasnt defaulted your session temp to something safer than install default or you are using a shared directory for session data then you would be wise to use named sessions to keep your session from being viewable in other people's scripts. Creating a unique_id name for this is the common method. **

2. use your custom folder but write a garbage collection script.

3. use a custom handler and a database
up
-2
mikaelkael at php dot net
15 years ago
Recently, I needed to change the session save_path in my program under Windows. With an ini_set('session.save_path', '../data/sessions'); (and session.gc_divisor = 1 for test), I always obtain 'Error #8 session_start(): ps_files_cleanup_dir: opendir(../data/sessions) failed: Result too large'.

I corrected this by changing with ini_set('session.save_path', realpath('../data/sessions'));
up
-3
orbill
13 years ago
apparently the default value for session.use_only_cookies has changed in 5.3.3 from 0 to 1. If you haven't set this in your php.ini or your code to 0 transparent sessions won't work.
up
-4
white-gandalf at web dot de
6 years ago
session.use_strict_mode does very little to strengthen your security: only one very specific variant of attack is migitated by this (where the attacker hands an "empty" sid to the victim to adapt his own browser to that session later) - versus for example the case where he pre-opens a session, handing the sid of that one to the victim, so the victim gets adapted to the pre-opened session. In the latter case this flag does nothing to help. In every other scenario with other vulnerabilities where the session id gets leaked, the flag helps nigher.

But this flag renders the php function session_id() useless in its parameterized variant, thus preventing any php functionality that builds upon this function.
up
-2
polygon dot co dot in at gmail dot com
2 years ago
In php.ini, session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. [Defaults to files.]

By default session.save_handler has support for below

session.save_handler = files
session.save_handler = sqlite
session.save_handler = redis
session.save_handler = memcached

These locks the session by default for any HTTP request using session.
Locking means, a user can't access session related pages until current request is completed.

So, if you are thinking that switching to these will increase performance; the answer is NO! because of locking behaviour.

To overcome/customise the session locking behaviour use as below.

session.save_handler = user
This is for all (including list above) modes of session storage.

For "user" type save_handler, we can ignore locks for better performance (as explained in function session_set_save_handler). But for this we need to take care to use sessions only for authenticity and not for passing data from one script to other.

For passing data accross scripts use GET method to achieve the goal.
up
-1
descartavel1+php at gmail dot com
10 months ago
You should set `session.name` to use either prefix `__Host-` or `__Secure-`. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
up
-6
sony-santos at bol dot com dot br
15 years ago
In response to 00 at f00n, this very page explains:

"(...) if N is used and greater than 0 then automatic garbage collection will not be performed (...)"

So you can actually use custom save_path with automatic garbage collection, since you don't use the subdirectory option (that N subdirectory levels).
up
-16
phpforcharity dot 5 dot pistos at geoshell dot com
15 years ago
To get session IDs to show up in URIs, and not get stored via cookies, you must not only set session.use_cookies to 0, but also set session.use_trans_sid to 1. Otherwise, the session ID goes neither in a cookie nor in URIs!
up
-21
Anonymous
7 years ago
In response to this comment: http://php.net/manual/en/session.configuration.php#107990 where it is claimed that gc_maxlifetime values larger than 65535 break the session system. I cannot reproduce this.

I've set gc_maxlifetime to 31536000 (1 year) and the session system works just fine. I haven't tried how long a session lasts now (I'm in the process of testing this), but it certainly doesn't break PHP sessions.
To Top