id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
196007
|
<?php
namespace Illuminate\Session\Middleware;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Contracts\Session\Middleware\AuthenticatesSessions;
use Illuminate\Http\Request;
class AuthenticateSession implements AuthenticatesSessions
{
/**
* The authentication factory implementation.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* The callback that should be used to generate the authentication redirect path.
*
* @var callable
*/
protected static $redirectToCallback;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(AuthFactory $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $request->hasSession() || ! $request->user() || ! $request->user()->getAuthPassword()) {
return $next($request);
}
if ($this->guard()->viaRemember()) {
$passwordHash = explode('|', $request->cookies->get($this->guard()->getRecallerName()))[2] ?? null;
if (! $passwordHash || ! hash_equals($request->user()->getAuthPassword(), $passwordHash)) {
$this->logout($request);
}
}
if (! $request->session()->has('password_hash_'.$this->auth->getDefaultDriver())) {
$this->storePasswordHashInSession($request);
}
if (! hash_equals($request->session()->get('password_hash_'.$this->auth->getDefaultDriver()), $request->user()->getAuthPassword())) {
$this->logout($request);
}
return tap($next($request), function () use ($request) {
if (! is_null($this->guard()->user())) {
$this->storePasswordHashInSession($request);
}
});
}
/**
* Store the user's current password hash in the session.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function storePasswordHashInSession($request)
{
if (! $request->user()) {
return;
}
$request->session()->put([
'password_hash_'.$this->auth->getDefaultDriver() => $request->user()->getAuthPassword(),
]);
}
/**
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function logout($request)
{
$this->guard()->logoutCurrentDevice();
$request->session()->flush();
throw new AuthenticationException(
'Unauthenticated.', [$this->auth->getDefaultDriver()], $this->redirectTo($request)
);
}
/**
* Get the guard instance that should be used by the middleware.
*
* @return \Illuminate\Contracts\Auth\Factory|\Illuminate\Contracts\Auth\Guard
*/
protected function guard()
{
return $this->auth;
}
/**
* Get the path the user should be redirected to when their session is not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo(Request $request)
{
if (static::$redirectToCallback) {
return call_user_func(static::$redirectToCallback, $request);
}
}
/**
* Specify the callback that should be used to generate the redirect path.
*
* @param callable $redirectToCallback
* @return void
*/
public static function redirectUsing(callable $redirectToCallback)
{
static::$redirectToCallback = $redirectToCallback;
}
}
| |
196009
|
<?php
namespace Illuminate\Session\Console;
use Illuminate\Console\MigrationGeneratorCommand;
use Symfony\Component\Console\Attribute\AsCommand;
use function Illuminate\Filesystem\join_paths;
#[AsCommand(name: 'make:session-table', aliases: ['session:table'])]
class SessionTableCommand extends MigrationGeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:session-table';
/**
* The console command name aliases.
*
* @var array
*/
protected $aliases = ['session:table'];
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a migration for the session database table';
/**
* Get the migration table name.
*
* @return string
*/
protected function migrationTableName()
{
return 'sessions';
}
/**
* Get the path to the migration stub file.
*
* @return string
*/
protected function migrationStubFile()
{
return __DIR__.'/stubs/database.stub';
}
/**
* Determine whether a migration for the table already exists.
*
* @param string $table
* @return bool
*/
protected function migrationExists($table)
{
foreach ([
join_paths($this->laravel->databasePath('migrations'), '*_*_*_*_create_'.$table.'_table.php'),
join_paths($this->laravel->databasePath('migrations'), '0001_01_01_000000_create_users_table.php'),
] as $path) {
if (count($this->files->glob($path)) !== 0) {
return true;
}
}
return false;
}
}
| |
196021
|
[PHP]
;;;;;;;;;;;;;;;;;;;
; About php.ini ;
;;;;;;;;;;;;;;;;;;;
; PHP's initialization file, generally called php.ini, is responsible for
; configuring many of the aspects of PHP's behavior.
; PHP attempts to find and load this configuration from a number of locations.
; The following is a summary of its search order:
; 1. SAPI module specific location.
; 2. The PHPRC environment variable.
; 3. A number of predefined registry keys on Windows
; 4. Current working directory (except CLI)
; 5. The web server's directory (for SAPI modules), or directory of PHP
; (otherwise in Windows)
; 6. The directory from the --with-config-file-path compile time option, or the
; Windows directory (usually C:\windows)
; See the PHP docs for more specific information.
; https://php.net/configuration.file
; The syntax of the file is extremely simple. Whitespace and lines
; beginning with a semicolon are silently ignored (as you probably guessed).
; Section headers (e.g. [Foo]) are also silently ignored, even though
; they might mean something in the future.
; Directives following the section heading [PATH=/www/mysite] only
; apply to PHP files in the /www/mysite directory. Directives
; following the section heading [HOST=www.example.com] only apply to
; PHP files served from www.example.com. Directives set in these
; special sections cannot be overridden by user-defined INI files or
; at runtime. Currently, [PATH=] and [HOST=] sections only work under
; CGI/FastCGI.
; https://php.net/ini.sections
; Directives are specified using the following syntax:
; directive = value
; Directive names are *case sensitive* - foo=bar is different from FOO=bar.
; Directives are variables used to configure PHP or PHP extensions.
; There is no name validation. If PHP can't find an expected
; directive because it is not set or is mistyped, a default value will be used.
; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one
; of the INI constants (On, Off, True, False, Yes, No and None) or an expression
; (e.g. E_ALL & ~E_NOTICE), a quoted string ("bar"), or a reference to a
; previously set variable or directive (e.g. ${foo})
; Expressions in the INI file are limited to bitwise operators and parentheses:
; | bitwise OR
; ^ bitwise XOR
; & bitwise AND
; ~ bitwise NOT
; ! boolean NOT
; Boolean flags can be turned on using the values 1, On, True or Yes.
; They can be turned off using the values 0, Off, False or No.
; An empty string can be denoted by simply not writing anything after the equal
; sign, or by using the None keyword:
; foo = ; sets foo to an empty string
; foo = None ; sets foo to an empty string
; foo = "None" ; sets foo to the string 'None'
; If you use constants in your value, and these constants belong to a
; dynamically loaded extension (either a PHP extension or a Zend extension),
; you may only use these constants *after* the line that loads the extension.
;;;;;;;;;;;;;;;;;;;
; About this file ;
;;;;;;;;;;;;;;;;;;;
; PHP comes packaged with two INI files. One that is recommended to be used
; in production environments and one that is recommended to be used in
; development environments.
; php.ini-production contains settings which hold security, performance and
; best practices at its core. But please be aware, these settings may break
; compatibility with older or less security-conscious applications. We
; recommending using the production ini in production and testing environments.
; php.ini-development is very similar to its production variant, except it is
; much more verbose when it comes to errors. We recommend using the
; development version only in development environments, as errors shown to
; application users can inadvertently leak otherwise secure information.
; This is the php.ini-production INI file.
;;;;;;;;;;;;;;;;;;;
; Quick Reference ;
;;;;;;;;;;;;;;;;;;;
; The following are all the settings which are different in either the production
; or development versions of the INIs with respect to PHP's default behavior.
; Please see the actual settings later in the document for more details as to why
; we recommend these changes in PHP's behavior.
; display_errors
; Default Value: On
; Development Value: On
; Production Value: Off
; display_startup_errors
; Default Value: On
; Development Value: On
; Production Value: Off
; error_reporting
; Default Value: E_ALL
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED
; log_errors
; Default Value: Off
; Development Value: On
; Production Value: On
; max_input_time
; Default Value: -1 (Unlimited)
; Development Value: 60 (60 seconds)
; Production Value: 60 (60 seconds)
; output_buffering
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; register_argc_argv
; Default Value: On
; Development Value: Off
; Production Value: Off
; request_order
; Default Value: None
; Development Value: "GP"
; Production Value: "GP"
; session.gc_divisor
; Default Value: 100
; Development Value: 1000
; Production Value: 1000
; short_open_tag
; Default Value: On
; Development Value: Off
; Production Value: Off
; variables_order
; Default Value: "EGPCS"
; Development Value: "GPCS"
; Production Value: "GPCS"
; zend.assertions
; Default Value: 1
; Development Value: 1
; Production Value: -1
; zend.exception_ignore_args
; Default Value: Off
; Development Value: Off
; Production Value: On
; zend.exception_string_param_max_len
; Default Value: 15
; Development Value: 15
; Production Value: 0
;;;;;;;;;;;;;;;;;;;;
; php.ini Options ;
;;;;;;;;;;;;;;;;;;;;
; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini"
;user_ini.filename = ".user.ini"
; To disable this feature set this option to an empty value
;user_ini.filename =
; TTL for user-defined php.ini files (time-to-live) in seconds. Default is 300 seconds (5 minutes)
;user_ini.cache_ttl = 300
;;;;;;;;;;;;;;;;;;;;
; Language Options ;
;;;;;;;;;;;;;;;;;;;;
; Enable the PHP scripting language engine under Apache.
; https://php.net/engine
engine = On
; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It is
; generally recommended that <?php and ?> should be used and that this feature
; should be disabled, as enabling it may result in issues when generating XML
; documents, however this remains supported for backward compatibility reasons.
; Note that this directive does not control the <?= shorthand tag, which can be
; used regardless of this directive.
; Default Value: On
; Development Value: Off
; Production Value: Off
; https://php.net/short-open-tag
short_open_tag = Off
; The number of significant digits displayed in floating point numbers.
; https://php.net/precision
precision = 14
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; https://php.net/output-buffering
output_buffering = 4096
| |
196032
|
[PHP]
;;;;;;;;;;;;;;;;;;;
; About php.ini ;
;;;;;;;;;;;;;;;;;;;
; PHP's initialization file, generally called php.ini, is responsible for
; configuring many of the aspects of PHP's behavior.
; PHP attempts to find and load this configuration from a number of locations.
; The following is a summary of its search order:
; 1. SAPI module specific location.
; 2. The PHPRC environment variable.
; 3. A number of predefined registry keys on Windows
; 4. Current working directory (except CLI)
; 5. The web server's directory (for SAPI modules), or directory of PHP
; (otherwise in Windows)
; 6. The directory from the --with-config-file-path compile time option, or the
; Windows directory (usually C:\windows)
; See the PHP docs for more specific information.
; https://php.net/configuration.file
; The syntax of the file is extremely simple. Whitespace and lines
; beginning with a semicolon are silently ignored (as you probably guessed).
; Section headers (e.g. [Foo]) are also silently ignored, even though
; they might mean something in the future.
; Directives following the section heading [PATH=/www/mysite] only
; apply to PHP files in the /www/mysite directory. Directives
; following the section heading [HOST=www.example.com] only apply to
; PHP files served from www.example.com. Directives set in these
; special sections cannot be overridden by user-defined INI files or
; at runtime. Currently, [PATH=] and [HOST=] sections only work under
; CGI/FastCGI.
; https://php.net/ini.sections
; Directives are specified using the following syntax:
; directive = value
; Directive names are *case sensitive* - foo=bar is different from FOO=bar.
; Directives are variables used to configure PHP or PHP extensions.
; There is no name validation. If PHP can't find an expected
; directive because it is not set or is mistyped, a default value will be used.
; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one
; of the INI constants (On, Off, True, False, Yes, No and None) or an expression
; (e.g. E_ALL & ~E_NOTICE), a quoted string ("bar"), or a reference to a
; previously set variable or directive (e.g. ${foo})
; Expressions in the INI file are limited to bitwise operators and parentheses:
; | bitwise OR
; ^ bitwise XOR
; & bitwise AND
; ~ bitwise NOT
; ! boolean NOT
; Boolean flags can be turned on using the values 1, On, True or Yes.
; They can be turned off using the values 0, Off, False or No.
; An empty string can be denoted by simply not writing anything after the equal
; sign, or by using the None keyword:
; foo = ; sets foo to an empty string
; foo = None ; sets foo to an empty string
; foo = "None" ; sets foo to the string 'None'
; If you use constants in your value, and these constants belong to a
; dynamically loaded extension (either a PHP extension or a Zend extension),
; you may only use these constants *after* the line that loads the extension.
;;;;;;;;;;;;;;;;;;;
; About this file ;
;;;;;;;;;;;;;;;;;;;
; PHP comes packaged with two INI files. One that is recommended to be used
; in production environments and one that is recommended to be used in
; development environments.
; php.ini-production contains settings which hold security, performance and
; best practices at its core. But please be aware, these settings may break
; compatibility with older or less security-conscious applications. We
; recommending using the production ini in production and testing environments.
; php.ini-development is very similar to its production variant, except it is
; much more verbose when it comes to errors. We recommend using the
; development version only in development environments, as errors shown to
; application users can inadvertently leak otherwise secure information.
; This is the php.ini-development INI file.
;;;;;;;;;;;;;;;;;;;
; Quick Reference ;
;;;;;;;;;;;;;;;;;;;
; The following are all the settings which are different in either the production
; or development versions of the INIs with respect to PHP's default behavior.
; Please see the actual settings later in the document for more details as to why
; we recommend these changes in PHP's behavior.
; display_errors
; Default Value: On
; Development Value: On
; Production Value: Off
; display_startup_errors
; Default Value: On
; Development Value: On
; Production Value: Off
; error_reporting
; Default Value: E_ALL
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED
; log_errors
; Default Value: Off
; Development Value: On
; Production Value: On
; max_input_time
; Default Value: -1 (Unlimited)
; Development Value: 60 (60 seconds)
; Production Value: 60 (60 seconds)
; output_buffering
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; register_argc_argv
; Default Value: On
; Development Value: Off
; Production Value: Off
; request_order
; Default Value: None
; Development Value: "GP"
; Production Value: "GP"
; session.gc_divisor
; Default Value: 100
; Development Value: 1000
; Production Value: 1000
; short_open_tag
; Default Value: On
; Development Value: Off
; Production Value: Off
; variables_order
; Default Value: "EGPCS"
; Development Value: "GPCS"
; Production Value: "GPCS"
; zend.assertions
; Default Value: 1
; Development Value: 1
; Production Value: -1
; zend.exception_ignore_args
; Default Value: Off
; Development Value: Off
; Production Value: On
; zend.exception_string_param_max_len
; Default Value: 15
; Development Value: 15
; Production Value: 0
;;;;;;;;;;;;;;;;;;;;
; php.ini Options ;
;;;;;;;;;;;;;;;;;;;;
; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini"
;user_ini.filename = ".user.ini"
; To disable this feature set this option to an empty value
;user_ini.filename =
; TTL for user-defined php.ini files (time-to-live) in seconds. Default is 300 seconds (5 minutes)
;user_ini.cache_ttl = 300
;;;;;;;;;;;;;;;;;;;;
; Language Options ;
;;;;;;;;;;;;;;;;;;;;
; Enable the PHP scripting language engine under Apache.
; https://php.net/engine
engine = On
; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It is
; generally recommended that <?php and ?> should be used and that this feature
; should be disabled, as enabling it may result in issues when generating XML
; documents, however this remains supported for backward compatibility reasons.
; Note that this directive does not control the <?= shorthand tag, which can be
; used regardless of this directive.
; Default Value: On
; Development Value: Off
; Production Value: Off
; https://php.net/short-open-tag
short_open_tag = Off
; The number of significant digits displayed in floating point numbers.
; https://php.net/precision
precision = 14
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; https://php.net/output-buffering
output_buffering = 4096
| |
196589
|
#if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
#endif
typedef union { double d; ULong L[2]; } U;
#ifdef IEEE_8087
#define word0(x) (x)->L[1]
#define word1(x) (x)->L[0]
#else
#define word0(x) (x)->L[0]
#define word1(x) (x)->L[1]
#endif
#define dval(x) (x)->d
#ifndef STRTOD_DIGLIM
#define STRTOD_DIGLIM 40
#endif
#ifdef DIGLIM_DEBUG
extern int strtod_diglim;
#else
#define strtod_diglim STRTOD_DIGLIM
#endif
/* The following definition of Storeinc is appropriate for MIPS processors.
* An alternative that might be better on some machines is
* #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
*/
#if defined(IEEE_8087) + defined(VAX) + defined(__arm__)
#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
((unsigned short *)a)[0] = (unsigned short)c, a++)
#else
#define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
((unsigned short *)a)[1] = (unsigned short)c, a++)
#endif
/* #define P DBL_MANT_DIG */
/* Ten_pmax = floor(P*log(2)/log(5)) */
/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
#ifdef IEEE_Arith
#define Exp_shift 20
#define Exp_shift1 20
#define Exp_msk1 0x100000
#define Exp_msk11 0x100000
#define Exp_mask 0x7ff00000
#define P 53
#define Nbits 53
#define Bias 1023
#define Emax 1023
#define Emin (-1022)
#define Exp_1 0x3ff00000
#define Exp_11 0x3ff00000
#define Ebits 11
#define Frac_mask 0xfffff
#define Frac_mask1 0xfffff
#define Ten_pmax 22
#define Bletch 0x10
#define Bndry_mask 0xfffff
#define Bndry_mask1 0xfffff
#define LSB 1
#define Sign_bit 0x80000000
#define Log2P 1
#define Tiny0 0
#define Tiny1 1
#define Quick_max 14
#define Int_max 14
#ifndef NO_IEEE_Scale
#define Avoid_Underflow
#ifdef Flush_Denorm /* debugging option */
#undef Sudden_Underflow
#endif
#endif
#ifndef Flt_Rounds
#ifdef FLT_ROUNDS
#define Flt_Rounds FLT_ROUNDS
#else
#define Flt_Rounds 1
#endif
#endif /*Flt_Rounds*/
#ifdef Honor_FLT_ROUNDS
#undef Check_FLT_ROUNDS
#define Check_FLT_ROUNDS
#else
#define Rounding Flt_Rounds
#endif
#else /* ifndef IEEE_Arith */
#undef Check_FLT_ROUNDS
#undef Honor_FLT_ROUNDS
#undef SET_INEXACT
#undef Sudden_Underflow
#define Sudden_Underflow
#ifdef IBM
#undef Flt_Rounds
#define Flt_Rounds 0
#define Exp_shift 24
#define Exp_shift1 24
#define Exp_msk1 0x1000000
#define Exp_msk11 0x1000000
#define Exp_mask 0x7f000000
#define P 14
#define Nbits 56
#define Bias 65
#define Emax 248
#define Emin (-260)
#define Exp_1 0x41000000
#define Exp_11 0x41000000
#define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
#define Frac_mask 0xffffff
#define Frac_mask1 0xffffff
#define Bletch 4
#define Ten_pmax 22
#define Bndry_mask 0xefffff
#define Bndry_mask1 0xffffff
#define LSB 1
#define Sign_bit 0x80000000
#define Log2P 4
#define Tiny0 0x100000
#define Tiny1 0
#define Quick_max 14
#define Int_max 15
#else /* VAX */
#undef Flt_Rounds
#define Flt_Rounds 1
#define Exp_shift 23
#define Exp_shift1 7
#define Exp_msk1 0x80
#define Exp_msk11 0x800000
#define Exp_mask 0x7f80
#define P 56
#define Nbits 56
#define Bias 129
#define Emax 126
#define Emin (-129)
#define Exp_1 0x40800000
#define Exp_11 0x4080
#define Ebits 8
#define Frac_mask 0x7fffff
#define Frac_mask1 0xffff007f
#define Ten_pmax 24
#define Bletch 2
#define Bndry_mask 0xffff007f
#define Bndry_mask1 0xffff007f
#define LSB 0x10000
#define Sign_bit 0x8000
#define Log2P 1
#define Tiny0 0x80
#define Tiny1 0
#define Quick_max 15
#define Int_max 15
#endif /* IBM, VAX */
#endif /* IEEE_Arith */
#ifndef IEEE_Arith
#define ROUND_BIASED
#else
#ifdef ROUND_BIASED_without_Round_Up
#undef ROUND_BIASED
#define ROUND_BIASED
#endif
#endif
#ifdef RND_PRODQUOT
#define rounded_product(a,b) a = rnd_prod(a, b)
#define rounded_quotient(a,b) a = rnd_quot(a, b)
#ifdef KR_headers
extern double rnd_prod(), rnd_quot();
#else
extern double rnd_prod(double, double), rnd_quot(double, double);
#endif
#else
#define rounded_product(a,b) a *= b
#define rounded_quotient(a,b) a /= b
#endif
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
#define Big1 0xffffffff
#ifndef Pack_32
#define Pack_32
#endif
typedef struct BCinfo BCinfo;
struct
BCinfo { int dp0, dp1, dplen, dsign, e0, inexact, nd, nd0, rounding, scale, uflchk; };
#ifdef KR_headers
#define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
#else
#define FFFFFFFF 0xffffffffUL
#endif
#ifdef NO_LONG_LONG
#undef ULLong
#ifdef Just_16
#undef Pack_32
/* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
* This makes some inner loops simpler and sometimes saves work
* during multiplications, but it often seems to make things slightly
* slower. Hence the default is now to store 32 bits per Long.
*/
#endif
#else /* long long available */
#ifndef Llong
#define Llong long long
#endif
#ifndef ULLong
#define ULLong unsigned Llong
#endif
#endif /* NO_LONG_LONG */
#ifndef MULTIPLE_THREADS
#define ACQUIRE_DTOA_LOCK(n) /*nothing*/
#define FREE_DTOA_LOCK(n) /*nothing*/
#endif
#define Kmax ZEND_STRTOD_K_MAX
struct
Bigint {
struct Bigint *next;
int k, maxwds, sign, wds;
ULong x[1];
};
typedef struct Bigint Bigint;
#ifndef Bigint
static Bigint *freelist[Kmax+1];
#endif
static void destroy_freelist(void);
static void free_p5s(void);
#ifdef MULTIPLE_THREADS
static MUTEX_T dtoa_mutex;
static MUTEX_T pow5mult_mutex;
#endif /* ZTS */
ZEND_API int zend_shutdown_strtod(void) /* {{{ */
{
destroy_freelist();
free_p5s();
return 1;
}
/* }}} */
static Bigint *
Balloc
#ifdef KR_headers
(k) int k;
#else
(int k)
#endif
| |
197058
|
--TEST--
Bug #54367 (Use of closure causes problem in ArrayAccess)
--FILE--
<?php
class MyObject implements ArrayAccess
{
public function offsetSet($offset, $value): void { }
public function offsetExists($offset): bool { }
public function offsetUnset($offset): void { }
public function offsetGet($offset): mixed
{
return function ($var) use ($offset) { // here is the problem
var_dump($offset, $var);
};
}
}
$a = new MyObject();
echo $a['p']('foo');
?>
--EXPECT--
string(1) "p"
string(3) "foo"
| |
197311
|
--TEST--
Bug #43483 (get_class_methods() does not list all visible methods)
--FILE--
<?php
class C {
public static function test() {
D::prot();
print_r(get_class_methods("D"));
}
}
class D extends C {
protected static function prot() {
echo "Successfully called D::prot().\n";
}
}
D::test();
?>
--EXPECT--
Successfully called D::prot().
Array
(
[0] => prot
[1] => test
)
| |
197850
|
--TEST--
File with just a <?php tag should be valid
--FILE_EXTERNAL--
php_tag_only.inc
--EXPECT--
| |
199219
|
--TEST--
Using traits to implement interface
--FILE--
<?php
trait foo {
public function abc() {
}
}
interface baz {
public function abc();
}
class bar implements baz {
use foo;
}
new bar;
print "OK\n";
?>
--EXPECT--
OK
| |
199240
|
--TEST--
Bug #55137 (Changing trait static method visibility)
--FILE--
<?php
trait A {
protected static function foo() { echo "abc\n"; }
private static function bar() { echo "def\n"; }
}
class B {
use A {
A::foo as public;
A::bar as public baz;
}
}
B::foo();
B::baz();
?>
--EXPECT--
abc
def
| |
199256
|
--TEST--
Bug #76773 (Traits used on the parent are ignored for child classes)
--FILE--
<?php
trait MyTrait
{
public function hello()
{
echo __CLASS__, "\n";
if (get_parent_class(__CLASS__) !== false) {
parent::hello();
}
}
}
class ParentClass
{
use MyTrait;
}
class ChildClass extends ParentClass
{
use MyTrait;
}
$c = new ChildClass();
$c->hello();
?>
--EXPECT--
ChildClass
ParentClass
| |
199304
|
--TEST--
Checking error message when the trait doesn't implements the interface
--FILE--
<?php
trait foo {
public function a() {
}
}
interface baz {
public function abc();
}
class bar implements baz {
use foo;
}
new bar;
?>
--EXPECTF--
Fatal error: Class bar contains 1 abstract method and must therefore be declared abstract or implement the remaining method (baz::abc) in %s on line %d
| |
199328
|
--TEST--
Abstract Trait Methods should behave like common abstract methods and
implementation may be provided by other traits. Sorting order shouldn't influence result.
--FILE--
<?php
error_reporting(E_ALL);
trait THello {
public abstract function hello();
}
trait THelloImpl {
public function hello() {
echo 'Hello';
}
}
class TraitsTest1 {
use THello;
use THelloImpl;
}
$test = new TraitsTest1();
$test->hello();
class TraitsTest2 {
use THelloImpl;
use THello;
}
$test = new TraitsTest2();
$test->hello();
?>
--EXPECT--
HelloHello
| |
200231
|
--TEST--
002: Import - different syntaxes
--FILE--
<?php
namespace test\ns1;
class Foo {
static function bar() {
echo __CLASS__,"\n";
}
}
class Foo2 {
static function bar() {
echo __CLASS__,"\n";
}
}
namespace xyz;
use test\ns1\Foo;
use test\ns1\Foo as Bar;
use \test\ns1\Foo2;
use \test\ns1\Foo2 as Bar2;
Foo::bar();
Bar::bar();
Foo2::bar();
Bar2::bar();
?>
--EXPECT--
test\ns1\Foo
test\ns1\Foo
test\ns1\Foo2
test\ns1\Foo2
| |
200250
|
--TEST--
065: Multiple names in use statement
--FILE--
<?php
use X\Y as test, X\Z as test2;
require "ns_065.inc";
test\foo();
test2\foo();
?>
--EXPECT--
X\Y\foo
X\Z\foo
| |
200504
|
--TEST--
#[\Override]: On used trait with interface method.
--FILE--
<?php
trait T {
#[\Override]
public function i(): void {}
}
interface I {
public function i(): void;
}
class Foo implements I {
use T;
}
echo "Done";
?>
--EXPECT--
Done
| |
200507
|
--TEST--
#[\Override]: Redeclared trait method with interface.
--FILE--
<?php
interface I {
public function i(): string;
}
trait T {
public function i(): string {
return 'T';
}
}
class C implements I {
use T;
#[\Override]
public function i(): string {
return 'C';
}
}
var_dump((new C())->i());
echo "Done";
?>
--EXPECT--
string(1) "C"
Done
| |
200511
|
--TEST--
#[Override] attribute in trait does not check for parent class implementations
--FILE--
<?php
class A {
public function foo(): void {}
}
interface I {
public function foo(): void;
}
trait T {
#[\Override]
public function foo(): void {
echo 'foo';
}
}
// Works fine
class B implements I {
use T;
}
// Works fine ("copied and pasted into the target class")
class C extends A {
#[\Override]
public function foo(): void {
echo 'foo';
}
}
// Does not work
class D extends A {
use T;
}
echo "Done";
?>
--EXPECT--
Done
| |
200518
|
--TEST--
#[Override] attribute in trait does not check for parent class implementations (Variant with abstract __construct)
--FILE--
<?php
abstract class A {
abstract public function __construct();
}
trait T {
#[\Override]
public function __construct() {
echo 'foo';
}
}
class D extends A {
use T;
}
echo "Done";
?>
--EXPECT--
Done
| |
200526
|
--TEST--
#[Override] attribute in trait does not check for parent class implementations (Variant with protected parent method)
--FILE--
<?php
class A {
protected function foo(): void {}
}
trait T {
#[\Override]
public function foo(): void {
echo 'foo';
}
}
class D extends A {
use T;
}
echo "Done";
?>
--EXPECTF--
Done
| |
201729
|
--TEST--
Closure 002: Lambda with lexical variables (global scope)
--FILE--
<?php
$x = 4;
$lambda1 = function () use ($x) {
echo "$x\n";
};
$lambda2 = function () use (&$x) {
echo "$x\n";
};
$lambda1();
$lambda2();
$x++;
$lambda1();
$lambda2();
echo "Done\n";
?>
--EXPECT--
4
4
4
5
Done
| |
201747
|
--TEST--
Closure 012: Undefined lexical variables
--FILE--
<?php
$lambda = function () use ($i) {
return ++$i;
};
$lambda();
$lambda();
var_dump($i);
$lambda = function () use (&$i) {
return ++$i;
};
$lambda();
$lambda();
var_dump($i);
?>
--EXPECTF--
Warning: Undefined variable $i in %s on line %d
Warning: Undefined variable $i in %s on line %d
NULL
int(2)
| |
201824
|
--TEST--
aliasing imported functions to resolve naming conflicts
--FILE--
<?php
namespace foo {
function baz() {
return 'foo.baz';
}
}
namespace bar {
function baz() {
return 'bar.baz';
}
}
namespace {
use function foo\baz as foo_baz,
bar\baz as bar_baz;
var_dump(foo_baz());
var_dump(bar_baz());
echo "Done\n";
}
?>
--EXPECT--
string(7) "foo.baz"
string(7) "bar.baz"
Done
| |
206812
|
--TEST--
Inline HTML should not be split at partial PHP tags
--EXTENSIONS--
tokenizer
--INI--
short_open_tag=0
--FILE--
<?php
var_dump(token_get_all(<<<'PHP'
Foo<?phpBar
PHP));
?>
--EXPECTF--
array(1) {
[0]=>
array(3) {
[0]=>
int(%d)
[1]=>
string(11) "Foo<?phpBar"
[2]=>
int(1)
}
}
| |
210580
|
--TEST--
Test is_array() function
--FILE--
<?php
echo "*** Testing is_array() on different type of arrays ***\n";
/* different types of arrays */
$arrays = array(
array(),
array(NULL),
array(null),
array(true),
array(""),
array(''),
array(array(), array()),
array(array(1, 2), array('a', 'b')),
array(1 => 'One'),
array("test" => "is_array"),
array(0),
array(-1),
array(10.5, 5.6),
array("string", "test"),
array('string', 'test')
);
/* loop to check that is_array() recognizes different
type of arrays, expected output bool(true) */
$loop_counter = 1;
foreach ($arrays as $var_array ) {
echo "-- Iteration $loop_counter --\n"; $loop_counter++;
var_dump( is_array ($var_array) );
}
echo "\n*** Testing is_array() on non array types ***\n";
// get a resource type variable
$fp = fopen (__FILE__, "r");
$dfp = opendir ( __DIR__ );
// unset variables
$unset_array = array(10);
unset($unset_array);
// other types in a array
$varient_arrays = array (
/* integers */
543915,
-5322,
0x55F,
-0xCCF,
123,
-0654,
/* strings */
"",
'',
"0",
'0',
'string',
"string",
/* floats */
10.0000000000000000005,
.5e6,
-.5E7,
.5E+8,
-.5e+90,
1e5,
/* objects */
new stdclass,
/* resources */
$fp,
$dfp,
/* nulls */
null,
NULL,
/* boolean */
true,
TRUE,
FALSE,
false,
/* unset/undefined arrays */
@$unset_array,
@$undefined_array
);
/* loop through the $varient_array to see working of
is_array() on non array types, expected output bool(false) */
$loop_counter = 1;
foreach ($varient_arrays as $type ) {
echo "-- Iteration $loop_counter --\n"; $loop_counter++;
var_dump( is_array ($type) );
}
echo "Done\n";
/* close resources */
fclose($fp);
closedir($dfp);
?>
--EXPECT--
*** Testing is_array() on different type of arrays ***
-- Iteration 1 --
bool(true)
-- Iteration 2 --
bool(true)
-- Iteration 3 --
bool(true)
-- Iteration 4 --
bool(true)
-- Iteration 5 --
bool(true)
-- Iteration 6 --
bool(true)
-- Iteration 7 --
bool(true)
-- Iteration 8 --
bool(true)
-- Iteration 9 --
bool(true)
-- Iteration 10 --
bool(true)
-- Iteration 11 --
bool(true)
-- Iteration 12 --
bool(true)
-- Iteration 13 --
bool(true)
-- Iteration 14 --
bool(true)
-- Iteration 15 --
bool(true)
*** Testing is_array() on non array types ***
-- Iteration 1 --
bool(false)
-- Iteration 2 --
bool(false)
-- Iteration 3 --
bool(false)
-- Iteration 4 --
bool(false)
-- Iteration 5 --
bool(false)
-- Iteration 6 --
bool(false)
-- Iteration 7 --
bool(false)
-- Iteration 8 --
bool(false)
-- Iteration 9 --
bool(false)
-- Iteration 10 --
bool(false)
-- Iteration 11 --
bool(false)
-- Iteration 12 --
bool(false)
-- Iteration 13 --
bool(false)
-- Iteration 14 --
bool(false)
-- Iteration 15 --
bool(false)
-- Iteration 16 --
bool(false)
-- Iteration 17 --
bool(false)
-- Iteration 18 --
bool(false)
-- Iteration 19 --
bool(false)
-- Iteration 20 --
bool(false)
-- Iteration 21 --
bool(false)
-- Iteration 22 --
bool(false)
-- Iteration 23 --
bool(false)
-- Iteration 24 --
bool(false)
-- Iteration 25 --
bool(false)
-- Iteration 26 --
bool(false)
-- Iteration 27 --
bool(false)
-- Iteration 28 --
bool(false)
-- Iteration 29 --
bool(false)
Done
| |
210672
|
--TEST--
Test array_is_list() function
--FILE--
<?php
function test_is_list(string $desc, $val) : void {
try {
printf("%s: %s\n", $desc, json_encode(array_is_list($val)));
} catch (TypeError $e) {
printf("%s: threw %s\n", $desc, $e->getMessage());
}
}
test_is_list("empty", []);
test_is_list("one", [1]);
test_is_list("two", [1,2]);
test_is_list("three", [1,2,3]);
test_is_list("four", [1,2,3,4]);
test_is_list("ten", range(0, 10));
test_is_list("null", null);
test_is_list("int", 123);
test_is_list("float", 1.23);
test_is_list("string", "string");
test_is_list("object", new stdClass());
test_is_list("true", true);
test_is_list("false", false);
test_is_list("string key", ["a" => 1]);
test_is_list("mixed keys", [0 => 0, "a" => 1]);
test_is_list("ordered keys", [0 => 0, 1 => 1]);
test_is_list("shuffled keys", [1 => 0, 0 => 1]);
test_is_list("skipped keys", [0 => 0, 2 => 2]);
$arr = [1, 2, 3];
unset($arr[0]);
test_is_list("unset first", $arr);
$arr = [1, 2, 3];
unset($arr[1]);
test_is_list("unset middle", $arr);
$arr = [1, 2, 3];
unset($arr[2]);
test_is_list("unset end", $arr);
$arr = [1, "a" => "a", 2];
unset($arr["a"]);
test_is_list("unset string key", $arr);
$arr = [1 => 1, 0 => 0];
unset($arr[1]);
test_is_list("unset into order", $arr);
$arr = ["a" => 1];
unset($arr["a"]);
test_is_list("unset to empty", $arr);
$arr = [1, 2, 3];
$arr[] = 4;
test_is_list("append implicit", $arr);
$arr = [1, 2, 3];
$arr[3] = 4;
test_is_list("append explicit", $arr);
$arr = [1, 2, 3];
$arr[4] = 5;
test_is_list("append with gap", $arr);
?>
--EXPECT--
empty: true
one: true
two: true
three: true
four: true
ten: true
null: threw array_is_list(): Argument #1 ($array) must be of type array, null given
int: threw array_is_list(): Argument #1 ($array) must be of type array, int given
float: threw array_is_list(): Argument #1 ($array) must be of type array, float given
string: threw array_is_list(): Argument #1 ($array) must be of type array, string given
object: threw array_is_list(): Argument #1 ($array) must be of type array, stdClass given
true: threw array_is_list(): Argument #1 ($array) must be of type array, true given
false: threw array_is_list(): Argument #1 ($array) must be of type array, false given
string key: false
mixed keys: false
ordered keys: true
shuffled keys: false
skipped keys: false
unset first: false
unset middle: false
unset end: true
unset string key: true
unset into order: true
unset to empty: true
append implicit: true
append explicit: true
append with gap: false
| |
213274
|
--TEST--
Test array_keys() function (variation - 3)
--FILE--
<?php
echo "*** Testing array_keys() on all the types other than arrays ***\n";
$types_arr = array(
TRUE => TRUE,
FALSE => FALSE,
1 => 1,
0 => 0,
-1 => -1,
"1" => "1",
"0" => "0",
"-1" => "-1",
NULL,
array(),
"php" => "php",
"" => ""
);
$values = array(TRUE, FALSE, 1, 0, -1, "1", "0", "-1", NULL, array(), "php", "");
foreach ($values as $value){
var_dump($value);
var_dump(array_keys($types_arr, $value));
}
echo "Done\n";
?>
--EXPECT--
*** Testing array_keys() on all the types other than arrays ***
bool(true)
array(3) {
[0]=>
int(1)
[1]=>
int(-1)
[2]=>
string(3) "php"
}
bool(false)
array(4) {
[0]=>
int(0)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
string(0) ""
}
int(1)
array(1) {
[0]=>
int(1)
}
int(0)
array(2) {
[0]=>
int(0)
[1]=>
int(2)
}
int(-1)
array(1) {
[0]=>
int(-1)
}
string(1) "1"
array(1) {
[0]=>
int(1)
}
string(1) "0"
array(1) {
[0]=>
int(0)
}
string(2) "-1"
array(1) {
[0]=>
int(-1)
}
NULL
array(3) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
string(0) ""
}
array(0) {
}
array(2) {
[0]=>
int(2)
[1]=>
int(3)
}
string(3) "php"
array(1) {
[0]=>
string(3) "php"
}
string(0) ""
array(2) {
[0]=>
int(2)
[1]=>
string(0) ""
}
Done
| |
213540
|
--TEST--
Test array_filter() function : usage variations - Different types of array for 'input' argument
--FILE--
<?php
/*
* Passing different types of array as 'input' argument.
*/
function always_false($input)
{
return false;
}
// callback function returning always true
function always_true($input)
{
return true;
}
echo "*** Testing array_filter() : usage variations - different types of array for 'input' argument***\n";
// different types of 'input' array
$input_values = array(
array(0, 1, 2, -1, 034, 0X4A), // integer values
array(0.0, 1.2, 1.2e3, 1.2e-3), // float values
array('value1', "value2", '', " ", ""), // string values
array(true, false, TRUE, FALSE), // bool values
array(null, NULL), // null values
array(1 => 'one', 'zero' => 0, -2 => "value"), //associative array
array("one" => 1, null => 'null', 5 => "float", true => 1, "" => 'empty'), // associative array with different keys
array(1 => 'one', 2, "key" => 'value') // combinition of associative and non-associative array
);
// loop through each element of 'input' with default callback
for($count = 0; $count < count($input_values); $count++)
{
echo "-- Iteration ".($count + 1). " --\n";
var_dump( array_filter($input_values[$count]) );
var_dump( array_filter($input_values[$count], 'always_true') );
var_dump( array_filter($input_values[$count], 'always_false') );
}
echo "Done"
?>
--EXPECT--
*** Testing array_filter() : usage variations - different types of array for 'input' argument***
-- Iteration 1 --
array(5) {
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(-1)
[4]=>
int(28)
[5]=>
int(74)
}
array(6) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(-1)
[4]=>
int(28)
[5]=>
int(74)
}
array(0) {
}
-- Iteration 2 --
array(3) {
[1]=>
float(1.2)
[2]=>
float(1200)
[3]=>
float(0.0012)
}
array(4) {
[0]=>
float(0)
[1]=>
float(1.2)
[2]=>
float(1200)
[3]=>
float(0.0012)
}
array(0) {
}
-- Iteration 3 --
array(3) {
[0]=>
string(6) "value1"
[1]=>
string(6) "value2"
[3]=>
string(1) " "
}
array(5) {
[0]=>
string(6) "value1"
[1]=>
string(6) "value2"
[2]=>
string(0) ""
[3]=>
string(1) " "
[4]=>
string(0) ""
}
array(0) {
}
-- Iteration 4 --
array(2) {
[0]=>
bool(true)
[2]=>
bool(true)
}
array(4) {
[0]=>
bool(true)
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
bool(false)
}
array(0) {
}
-- Iteration 5 --
array(0) {
}
array(2) {
[0]=>
NULL
[1]=>
NULL
}
array(0) {
}
-- Iteration 6 --
array(2) {
[1]=>
string(3) "one"
[-2]=>
string(5) "value"
}
array(3) {
[1]=>
string(3) "one"
["zero"]=>
int(0)
[-2]=>
string(5) "value"
}
array(0) {
}
-- Iteration 7 --
array(4) {
["one"]=>
int(1)
[""]=>
string(5) "empty"
[5]=>
string(5) "float"
[1]=>
int(1)
}
array(4) {
["one"]=>
int(1)
[""]=>
string(5) "empty"
[5]=>
string(5) "float"
[1]=>
int(1)
}
array(0) {
}
-- Iteration 8 --
array(3) {
[1]=>
string(3) "one"
[2]=>
int(2)
["key"]=>
string(5) "value"
}
array(3) {
[1]=>
string(3) "one"
[2]=>
int(2)
["key"]=>
string(5) "value"
}
array(0) {
}
Done
| |
213640
|
--TEST--
Test array_intersect() function : usage variations - different arrays for 'arr1' argument
--FILE--
<?php
/*
* Passing different types of arrays to $arr1 argument and testing whether
* array_intersect() behaves in expected way with the other arguments passed to the function
* The $arr2 argument is a fixed array.
*/
echo "*** Testing array_intersect() : Passing different types of arrays to \$arr1 argument ***\n";
/* Different heredoc strings passed as argument to $arr1 */
// heredoc with blank line
$blank_line = <<<EOT
EOT;
// heredoc with multiline string
$multiline_string = <<<EOT
hello world
The big brown fox jumped over;
the lazy dog
This is a double quoted string
EOT;
// heredoc with different whitespaces
$diff_whitespaces = <<<EOT
hello\r world\t
1111\t\t != 2222\v\v
heredoc\ndouble quoted string. with\vdifferent\fwhite\vspaces
EOT;
// heredoc with quoted strings and numeric values
$numeric_string = <<<EOT
11 < 12. 123 >22
'single quoted string'
"double quoted string"
2222 != 1111.\t 0000 = 0000\n
EOT;
// arrays to be passed to $arr1 argument
$arrays = array (
/*1*/ array(1, 2), // array with default keys and numeric values
array(1.1, 2.2), // array with default keys & float values
array(false,true), // array with default keys and boolean values
array(), // empty array
/*5*/ array(NULL), // array with NULL
array("a\v\f","aaaa\r","b","b\tbbb","c","\[\]\!\@\#\$\%\^\&\*\(\)\{\}"), // array with double quoted strings
array('a\v\f','aaaa\r','b','b\tbbb','c','\[\]\!\@\#\$\%\^\&\*\(\)\{\}'), // array with single quoted strings
array($blank_line, $multiline_string, $diff_whitespaces, $numeric_string), // array with heredocs
// associative arrays
/*9*/ array(1 => "one", 2 => "two", 3 => "three"), // explicit numeric keys, string values
array("one" => 1, "two" => 2, "three" => 3 ), // string keys & numeric values
array( 1 => 10, 2 => 20, 4 => 40, 3 => 30), // explicit numeric keys and numeric values
array( "one" => "ten", "two" => "twenty", "three" => "thirty"), // string key/value
array("one" => 1, 2 => "two", 4 => "four"), //mixed
// associative array, containing null/empty/boolean values as key/value
/*14*/ array(NULL => "NULL", null => "null", "NULL" => NULL, "null" => null),
array(true => "true", false => "false", "false" => false, "true" => true),
array("" => "emptyd", '' => 'emptys', "emptyd" => "", 'emptys' => ''),
array(1 => '', 2 => "", 3 => NULL, 4 => null, 5 => false, 6 => true),
array('' => 1, "" => 2, NULL => 3, null => 4, false => 5, true => 6),
// array with repetitive keys
/*19*/ array("One" => 1, "two" => 2, "One" => 10, "two" => 20, "three" => 3)
);
| |
214781
|
Warning: PDOStatement::execute(): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'some_bool_2' cannot be null in %s
array(3) {
[0]=>
string(5) "23000"
[1]=>
int(1048)
[2]=>
string(35) "Column 'some_bool_2' cannot be null"
}
Array
(
[uid] => 6
[0] => 6
[some_bool_1] => 0
[1] => 0
[some_bool_2] => 1
[2] => 1
[some_int] => 2
[3] => 2
)
ok prepare 5
Array
(
[uid] => 6
[0] => 6
[some_bool_1] => 1
[1] => 1
[some_bool_2] => 0
[2] => 0
[some_int] => 5
[3] => 5
)
| |
214823
|
--TEST--
Error during closeCursor() of multi query
--EXTENSIONS--
pdo_mysql
--SKIPIF--
<?php
require_once __DIR__ . '/inc/mysql_pdo_test.inc';
MySQLPDOTest::skip();
?>
--FILE--
<?php
require_once __DIR__ . '/inc/mysql_pdo_test.inc';
$db = MySQLPDOTest::factory();
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
$stmt = $db->query('SELECT 1; SELECT x FROM does_not_exist');
var_dump($stmt->fetchAll());
var_dump($stmt->closeCursor());
?>
--EXPECTF--
array(1) {
[0]=>
array(2) {
[1]=>
string(1) "1"
[0]=>
string(1) "1"
}
}
Warning: PDOStatement::closeCursor(): SQLSTATE[42S02]: Base table or view not found: 1146 Table '%s.does_not_exist' doesn't exist in %s on line %d
bool(false)
| |
215358
|
PHP_FUNCTION(json_decode)
{
char *str;
size_t str_len;
bool assoc = 0; /* return JS objects as PHP objects by default */
bool assoc_null = 1;
zend_long depth = PHP_JSON_PARSER_DEFAULT_DEPTH;
zend_long options = 0;
ZEND_PARSE_PARAMETERS_START(1, 4)
Z_PARAM_STRING(str, str_len)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL_OR_NULL(assoc, assoc_null)
Z_PARAM_LONG(depth)
Z_PARAM_LONG(options)
ZEND_PARSE_PARAMETERS_END();
if (!(options & PHP_JSON_THROW_ON_ERROR)) {
JSON_G(error_code) = PHP_JSON_ERROR_NONE;
}
if (!str_len) {
if (!(options & PHP_JSON_THROW_ON_ERROR)) {
JSON_G(error_code) = PHP_JSON_ERROR_SYNTAX;
} else {
zend_throw_exception(php_json_exception_ce, php_json_get_error_msg(PHP_JSON_ERROR_SYNTAX), PHP_JSON_ERROR_SYNTAX);
}
RETURN_NULL();
}
if (depth <= 0) {
zend_argument_value_error(3, "must be greater than 0");
RETURN_THROWS();
}
if (depth > INT_MAX) {
zend_argument_value_error(3, "must be less than %d", INT_MAX);
RETURN_THROWS();
}
/* For BC reasons, the bool $assoc overrides the long $options bit for PHP_JSON_OBJECT_AS_ARRAY */
if (!assoc_null) {
if (assoc) {
options |= PHP_JSON_OBJECT_AS_ARRAY;
} else {
options &= ~PHP_JSON_OBJECT_AS_ARRAY;
}
}
php_json_decode_ex(return_value, str, str_len, options, depth);
}
/* }}} */
/* {{{ Validates if a string contains a valid json */
PHP_FUNCTION(json_validate)
{
char *str;
size_t str_len;
zend_long depth = PHP_JSON_PARSER_DEFAULT_DEPTH;
zend_long options = 0;
ZEND_PARSE_PARAMETERS_START(1, 3)
Z_PARAM_STRING(str, str_len)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(depth)
Z_PARAM_LONG(options)
ZEND_PARSE_PARAMETERS_END();
if ((options != 0) && (options != PHP_JSON_INVALID_UTF8_IGNORE)) {
zend_argument_value_error(3, "must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)");
RETURN_THROWS();
}
if (!str_len) {
JSON_G(error_code) = PHP_JSON_ERROR_SYNTAX;
RETURN_FALSE;
}
JSON_G(error_code) = PHP_JSON_ERROR_NONE;
if (depth <= 0) {
zend_argument_value_error(2, "must be greater than 0");
RETURN_THROWS();
}
if (depth > INT_MAX) {
zend_argument_value_error(2, "must be less than %d", INT_MAX);
RETURN_THROWS();
}
RETURN_BOOL(php_json_validate_ex(str, str_len, options, depth));
}
/* }}} */
/* {{{ Returns the error code of the last json_encode() or json_decode() call. */
PHP_FUNCTION(json_last_error)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_LONG(JSON_G(error_code));
}
/* }}} */
/* {{{ Returns the error string of the last json_encode() or json_decode() call. */
PHP_FUNCTION(json_last_error_msg)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_STRING(php_json_get_error_msg(JSON_G(error_code)));
}
/* }}} */
| |
215383
|
--TEST--
JSON (http://www.crockford.com/JSON/JSON_checker/test/pass3.json)
--FILE--
<?php
$test = '
{
"JSON Test Pattern pass3": {
"The outermost value": "must be an object or array.",
"In this test": "It is an object."
}
}
';
echo 'Testing:' . $test . "\n";
echo "DECODE: AS OBJECT\n";
$obj = json_decode($test);
var_dump($obj);
echo "DECODE: AS ARRAY\n";
$arr = json_decode($test, true);
var_dump($arr);
echo "ENCODE: FROM OBJECT\n";
$obj_enc = json_encode($obj);
echo $obj_enc . "\n";
echo "ENCODE: FROM ARRAY\n";
$arr_enc = json_encode($arr);
echo $arr_enc . "\n";
echo "DECODE AGAIN: AS OBJECT\n";
$obj = json_decode($obj_enc);
var_dump($obj);
echo "DECODE AGAIN: AS ARRAY\n";
$arr = json_decode($arr_enc, true);
var_dump($arr);
?>
--EXPECTF--
Testing:
{
"JSON Test Pattern pass3": {
"The outermost value": "must be an object or array.",
"In this test": "It is an object."
}
}
DECODE: AS OBJECT
object(stdClass)#%d (1) {
["JSON Test Pattern pass3"]=>
object(stdClass)#%d (2) {
["The outermost value"]=>
string(27) "must be an object or array."
["In this test"]=>
string(16) "It is an object."
}
}
DECODE: AS ARRAY
array(1) {
["JSON Test Pattern pass3"]=>
array(2) {
["The outermost value"]=>
string(27) "must be an object or array."
["In this test"]=>
string(16) "It is an object."
}
}
ENCODE: FROM OBJECT
{"JSON Test Pattern pass3":{"The outermost value":"must be an object or array.","In this test":"It is an object."}}
ENCODE: FROM ARRAY
{"JSON Test Pattern pass3":{"The outermost value":"must be an object or array.","In this test":"It is an object."}}
DECODE AGAIN: AS OBJECT
object(stdClass)#%d (1) {
["JSON Test Pattern pass3"]=>
object(stdClass)#%d (2) {
["The outermost value"]=>
string(27) "must be an object or array."
["In this test"]=>
string(16) "It is an object."
}
}
DECODE AGAIN: AS ARRAY
array(1) {
["JSON Test Pattern pass3"]=>
array(2) {
["The outermost value"]=>
string(27) "must be an object or array."
["In this test"]=>
string(16) "It is an object."
}
}
| |
215392
|
--TEST--
JSON (http://www.crockford.com/JSON/JSON_checker/test/pass2.json)
--FILE--
<?php
$test = '[[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]';
echo 'Testing: ' . $test . "\n";
echo "DECODE: AS OBJECT\n";
$obj = json_decode($test);
var_dump($obj);
echo "DECODE: AS ARRAY\n";
$arr = json_decode($test, true);
var_dump($arr);
echo "ENCODE: FROM OBJECT\n";
$obj_enc = json_encode($obj);
echo $obj_enc . "\n";
echo "ENCODE: FROM ARRAY\n";
$arr_enc = json_encode($arr);
echo $arr_enc . "\n";
echo "DECODE AGAIN: AS OBJECT\n";
$obj = json_decode($obj_enc);
var_dump($obj);
echo "DECODE AGAIN: AS ARRAY\n";
$arr = json_decode($arr_enc, true);
var_dump($arr);
?>
--EXPECT--
Testing: [[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
DECODE: AS OBJECT
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(12) "Not too deep"
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
DECODE: AS ARRAY
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(12) "Not too deep"
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
ENCODE: FROM OBJECT
[[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
ENCODE: FROM ARRAY
[[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
DECODE AGAIN: AS OBJECT
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(12) "Not too deep"
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
DECODE AGAIN: AS ARRAY
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(12) "Not too deep"
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
| |
215453
|
--TEST--
JSON (http://www.crockford.com/JSON/JSON_checker/test/pass1.json)
--INI--
serialize_precision=-1
--FILE--
<?php
$test = "
[
\"JSON Test Pattern pass1\",
{\"object with 1 member\":[\"array with 1 element\"]},
{},
[],
-42,
true,
false,
null,
{
\"integer\": 1234567890,
\"real\": -9876.543210,
\"e\": 0.123456789e-12,
\"E\": 1.234567890E+34,
\"\": 23456789012E666,
\"zero\": 0,
\"one\": 1,
\"space\": \" \",
\"quote\": \"\\\"\",
\"backslash\": \"\\\\\",
\"controls\": \"\\b\\f\\n\\r\\t\",
\"slash\": \"/ & \\/\",
\"alpha\": \"abcdefghijklmnopqrstuvwyz\",
\"ALPHA\": \"ABCDEFGHIJKLMNOPQRSTUVWYZ\",
\"digit\": \"0123456789\",
\"special\": \"`1~!@#$%^&*()_+-={':[,]}|;.</>?\",
\"hex\": \"\\u0123\\u4567\\u89AB\\uCDEF\\uabcd\\uef4A\",
\"true\": true,
\"false\": false,
\"null\": null,
\"array\":[ ],
\"object\":{ },
\"address\": \"50 St. James Street\",
\"url\": \"http://www.JSON.org/\",
\"comment\": \"// /* <!-- --\",
\"# -- --> */\": \" \",
\" s p a c e d \" :[1,2 , 3
,
4 , 5 , 6 ,7 ],
\"compact\": [1,2,3,4,5,6,7],
\"jsontext\": \"{\\\"object with 1 member\\\":[\\\"array with 1 element\\\"]}\",
\"quotes\": \"" \\u0022 %22 0x22 034 "\",
\"\\/\\\\\\\"\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?\"
: \"A key can be any string\"
},
0.5 ,98.6
,
99.44
,
1066
,\"rosebud\"]
";
echo 'Testing:' . $test . "\n";
echo "DECODE: AS OBJECT\n";
$obj = json_decode($test);
var_dump($obj);
echo "DECODE: AS ARRAY\n";
$arr = json_decode($test, true);
var_dump($arr);
echo "ENCODE: FROM OBJECT\n";
$obj_enc = json_encode($obj, JSON_PARTIAL_OUTPUT_ON_ERROR);
echo $obj_enc . "\n";
echo "ENCODE: FROM ARRAY\n";
$arr_enc = json_encode($arr, JSON_PARTIAL_OUTPUT_ON_ERROR);
echo $arr_enc . "\n";
echo "DECODE AGAIN: AS OBJECT\n";
$obj = json_decode($obj_enc);
var_dump($obj);
echo "DECODE AGAIN: AS ARRAY\n";
$arr = json_decode($arr_enc, true);
var_dump($arr);
?>
--EXPECT--
Testing:
[
"JSON Test Pattern pass1",
{"object with 1 member":["array with 1 element"]},
{},
[],
-42,
true,
false,
null,
{
"integer": 1234567890,
"real": -9876.543210,
"e": 0.123456789e-12,
"E": 1.234567890E+34,
"": 23456789012E666,
"zero": 0,
"one": 1,
"space": " ",
"quote": "\"",
"backslash": "\\",
"controls": "\b\f\n\r\t",
"slash": "/ & \/",
"alpha": "abcdefghijklmnopqrstuvwyz",
"ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
"digit": "0123456789",
"special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",
"hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
"true": true,
"false": false,
"null": null,
"array":[ ],
"object":{ },
"address": "50 St. James Street",
"url": "http://www.JSON.org/",
"comment": "// /* <!-- --",
"# -- --> */": " ",
" s p a c e d " :[1,2 , 3
,
4 , 5 , 6 ,7 ],
"compact": [1,2,3,4,5,6,7],
"jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
"quotes": "" \u0022 %22 0x22 034 "",
"\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
: "A key can be any string"
},
0.5 ,98.6
,
99.44
,
1066
| |
220681
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Frank Denis <jedisct1@php.net> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "ext/standard/info.h"
#include "php_libsodium.h"
#include "zend_attributes.h"
#include "zend_exceptions.h"
#include <sodium.h>
#include <stdint.h>
#include <string.h>
#define PHP_SODIUM_ZSTR_TRUNCATE(zs, len) do { ZSTR_LEN(zs) = (len); } while(0)
static zend_class_entry *sodium_exception_ce;
#if (defined(__amd64) || defined(__amd64__) || defined(__x86_64__) || defined(__i386__) || \
defined(_M_AMD64) || defined(_M_IX86) || defined(__aarch64__) || defined(_M_ARM64))
# define HAVE_AESGCM 1
#endif
static zend_always_inline zend_string *zend_string_checked_alloc(size_t len, int persistent)
{
zend_string *zs;
if (ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(len)) < len) {
zend_error_noreturn(E_ERROR, "Memory allocation too large (%zu bytes)", len);
}
zs = zend_string_alloc(len, persistent);
ZSTR_VAL(zs)[len] = 0;
return zs;
}
#ifndef crypto_kdf_BYTES_MIN
# define crypto_kdf_BYTES_MIN 16
# define crypto_kdf_BYTES_MAX 64
# define crypto_kdf_CONTEXTBYTES 8
# define crypto_kdf_KEYBYTES 32
#endif
#ifndef crypto_kx_SEEDBYTES
# define crypto_kx_SEEDBYTES 32
# define crypto_kx_SESSIONKEYBYTES 32
# define crypto_kx_PUBLICKEYBYTES 32
# define crypto_kx_SECRETKEYBYTES 32
#endif
#include "libsodium_arginfo.h"
#ifndef crypto_aead_chacha20poly1305_IETF_KEYBYTES
# define crypto_aead_chacha20poly1305_IETF_KEYBYTES crypto_aead_chacha20poly1305_KEYBYTES
#endif
#ifndef crypto_aead_chacha20poly1305_IETF_NSECBYTES
# define crypto_aead_chacha20poly1305_IETF_NSECBYTES crypto_aead_chacha20poly1305_NSECBYTES
#endif
#ifndef crypto_aead_chacha20poly1305_IETF_ABYTES
# define crypto_aead_chacha20poly1305_IETF_ABYTES crypto_aead_chacha20poly1305_ABYTES
#endif
#if defined(crypto_secretstream_xchacha20poly1305_ABYTES) && SODIUM_LIBRARY_VERSION_MAJOR < 10
# undef crypto_secretstream_xchacha20poly1305_ABYTES
#endif
#ifndef crypto_pwhash_OPSLIMIT_MIN
# define crypto_pwhash_OPSLIMIT_MIN crypto_pwhash_OPSLIMIT_INTERACTIVE
#endif
#ifndef crypto_pwhash_MEMLIMIT_MIN
# define crypto_pwhash_MEMLIMIT_MIN crypto_pwhash_MEMLIMIT_INTERACTIVE
#endif
#ifndef crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN
# define crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE
#endif
#ifndef crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN
# define crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE
#endif
/* Load after the "standard" module in order to give it
* priority in registering argon2i/argon2id password hashers.
*/
static const zend_module_dep sodium_deps[] = {
ZEND_MOD_REQUIRED("standard")
ZEND_MOD_END
};
zend_module_entry sodium_module_entry = {
STANDARD_MODULE_HEADER_EX,
NULL,
sodium_deps,
"sodium",
ext_functions,
PHP_MINIT(sodium),
PHP_MSHUTDOWN(sodium),
NULL,
NULL,
PHP_MINFO(sodium),
PHP_SODIUM_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_SODIUM
ZEND_GET_MODULE(sodium)
#endif
/* Remove argument information from backtrace to prevent information leaks */
static void sodium_remove_param_values_from_backtrace(zend_object *obj) {
zval rv;
zval *trace = zend_read_property_ex(zend_get_exception_base(obj), obj, ZSTR_KNOWN(ZEND_STR_TRACE), /* silent */ false, &rv);
if (trace && Z_TYPE_P(trace) == IS_ARRAY) {
zval *frame;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(trace), frame) {
if (Z_TYPE_P(frame) == IS_ARRAY) {
zval *args = zend_hash_find(Z_ARRVAL_P(frame), ZSTR_KNOWN(ZEND_STR_ARGS));
if (args) {
zval_ptr_dtor(args);
ZVAL_EMPTY_ARRAY(args);
}
}
} ZEND_HASH_FOREACH_END();
}
}
static zend_object *sodium_exception_create_object(zend_class_entry *ce) {
zend_object *obj = zend_ce_exception->create_object(ce);
sodium_remove_param_values_from_backtrace(obj);
return obj;
}
static void sodium_separate_string(zval *zv) {
ZEND_ASSERT(Z_TYPE_P(zv) == IS_STRING);
if (!Z_REFCOUNTED_P(zv) || Z_REFCOUNT_P(zv) > 1) {
zend_string *copy = zend_string_init(Z_STRVAL_P(zv), Z_STRLEN_P(zv), 0);
Z_TRY_DELREF_P(zv);
ZVAL_STR(zv, copy);
}
}
PHP_MINIT_FUNCTION(sodium)
{
if (sodium_init() < 0) {
zend_error_noreturn(E_ERROR, "sodium_init()");
}
sodium_exception_ce = register_class_SodiumException(zend_ce_exception);
sodium_exception_ce->create_object = sodium_exception_create_object;
#if SODIUM_LIBRARY_VERSION_MAJOR > 9 || (SODIUM_LIBRARY_VERSION_MAJOR == 9 && SODIUM_LIBRARY_VERSION_MINOR >= 6)
if (FAILURE == PHP_MINIT(sodium_password_hash)(INIT_FUNC_ARGS_PASSTHRU)) {
return FAILURE;
}
#endif
register_libsodium_symbols(module_number);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(sodium)
{
randombytes_close();
return SUCCESS;
}
PHP_MINFO_FUNCTION(sodium)
{
php_info_print_table_start();
php_info_print_table_row(2, "sodium support", "enabled");
php_info_print_table_row(2, "libsodium headers version", SODIUM_VERSION_STRING);
php_info_print_table_row(2, "libsodium library version", sodium_version_string());
php_info_print_table_end();
}
PHP_FUNCTION(sodium_memzero)
{
zval *buf_zv;
if (zend_parse_parameters(ZEND_NUM_ARGS(),
"z", &buf_zv) == FAILURE) {
sodium_remove_param_values_from_backtrace(EG(exception));
RETURN_THROWS();
}
ZVAL_DEREF(buf_zv);
if (Z_TYPE_P(buf_zv) != IS_STRING) {
zend_throw_exception(sodium_exception_ce, "a PHP string is required", 0);
RETURN_THROWS();
}
if (Z_REFCOUNTED_P(buf_zv) && Z_REFCOUNT_P(buf_zv) == 1) {
char *buf = Z_STRVAL(*buf_zv);
size_t buf_len = Z_STRLEN(*buf_zv);
if (buf_len > 0) {
sodium_memzero(buf, (size_t) buf_len);
}
}
convert_to_null(buf_zv);
}
PHP_FUNCTION(sodium_increment)
{
zval *val_zv;
unsigned char *val;
size_t val_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(),
"z", &val_zv) == FAILURE) {
sodium_remove_param_values_from_backtrace(EG(exception));
RETURN_THROWS();
}
ZVAL_DEREF(val_zv);
if (Z_TYPE_P(val_zv) != IS_STRING) {
zend_throw_exception(sodium_exception_ce, "a PHP string is required", 0);
RETURN_THROWS();
}
sodium_separate_string(val_zv);
val = (unsigned char *) Z_STRVAL(*val_zv);
val_len = Z_STRLEN(*val_zv);
sodium_increment(val, val_len);
}
| |
220710
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Frank Denis <jedisct1@php.net> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_LIBSODIUM_H
#define PHP_LIBSODIUM_H
extern zend_module_entry sodium_module_entry;
#define phpext_sodium_ptr &sodium_module_entry
#define PHP_SODIUM_VERSION PHP_VERSION
#ifdef ZTS
# include "TSRM.h"
#endif
#include <sodium.h>
#define SODIUM_LIBRARY_VERSION() (char *) (void *) sodium_version_string()
#define SODIUM_CRYPTO_BOX_KEYPAIRBYTES() crypto_box_SECRETKEYBYTES + crypto_box_PUBLICKEYBYTES
#define SODIUM_CRYPTO_KX_KEYPAIRBYTES() crypto_kx_SECRETKEYBYTES + crypto_kx_PUBLICKEYBYTES
#define SODIUM_CRYPTO_SIGN_KEYPAIRBYTES() crypto_sign_SECRETKEYBYTES + crypto_sign_PUBLICKEYBYTES
#if SODIUM_LIBRARY_VERSION_MAJOR > 9 || (SODIUM_LIBRARY_VERSION_MAJOR == 9 && SODIUM_LIBRARY_VERSION_MINOR >= 6)
/**
* MEMLIMIT is normalized to KB even though sodium uses Bytes in order to
* present a consistent user-facing API.
*
* Threads are fixed at 1 by libsodium.
*
* When updating these values, synchronize ext/standard/php_password.h values.
*/
#if defined(PHP_PASSWORD_ARGON2_MEMORY_COST)
#define PHP_SODIUM_PWHASH_MEMLIMIT PHP_PASSWORD_ARGON2_MEMORY_COST
#else
#define PHP_SODIUM_PWHASH_MEMLIMIT (64 << 10)
#endif
#if defined(PHP_PASSWORD_ARGON2_TIME_COST)
#define PHP_SODIUM_PWHASH_OPSLIMIT PHP_PASSWORD_ARGON2_TIME_COST
#else
#define PHP_SODIUM_PWHASH_OPSLIMIT 4
#endif
#if defined(PHP_SODIUM_PWHASH_THREADS)
#define PHP_SODIUM_PWHASH_THREADS PHP_SODIUM_PWHASH_THREADS
#else
#define PHP_SODIUM_PWHASH_THREADS 1
#endif
#endif
PHP_MINIT_FUNCTION(sodium);
PHP_MINIT_FUNCTION(sodium_password_hash);
PHP_MSHUTDOWN_FUNCTION(sodium);
PHP_RINIT_FUNCTION(sodium);
PHP_RSHUTDOWN_FUNCTION(sodium);
PHP_MINFO_FUNCTION(sodium);
#endif /* PHP_LIBSODIUM_H */
| |
220726
|
PHP_ARG_WITH([sodium],
[for sodium support],
[AS_HELP_STRING([--with-sodium],
[Include sodium support])])
if test "$PHP_SODIUM" != "no"; then
PKG_CHECK_MODULES([LIBSODIUM], [libsodium >= 1.0.8])
PHP_EVAL_INCLINE([$LIBSODIUM_CFLAGS])
PHP_EVAL_LIBLINE([$LIBSODIUM_LIBS], [SODIUM_SHARED_LIBADD])
AC_DEFINE([HAVE_LIBSODIUMLIB], [1],
[Define to 1 if the PHP extension 'sodium' is available.])
SODIUM_COMPILER_FLAGS=$LIBSODIUM_CFLAGS
dnl Add -Wno-type-limits and -Wno-logical-op as this may arise on 32bits platforms
AC_CHECK_SIZEOF([long])
AS_IF([test "$ac_cv_sizeof_long" -eq 4], [
SODIUM_COMPILER_FLAGS="$SODIUM_COMPILER_FLAGS -Wno-type-limits"
AX_CHECK_COMPILE_FLAG([-Wno-logical-op],
[SODIUM_COMPILER_FLAGS="$SODIUM_COMPILER_FLAGS -Wno-logical-op"],,
[-Werror])
])
PHP_NEW_EXTENSION([sodium],
[libsodium.c sodium_pwhash.c],
[$ext_shared],,
[$SODIUM_COMPILER_FLAGS])
PHP_INSTALL_HEADERS([ext/sodium], [php_libsodium.h])
PHP_SUBST([SODIUM_SHARED_LIBADD])
fi
| |
220741
|
--TEST--
Check for sodium presence
--EXTENSIONS--
sodium
--FILE--
<?php
echo "sodium extension is available";
/*
you can add regression tests for your extension here
the output of your test code has to be equal to the
text in the--EXPECT-- section below for the tests
to pass, differences between the output and the
expected text are interpreted as failure
*/
?>
--EXPECT--
sodium extension is available
| |
222166
|
--TEST--
PDO_DBLIB: Uniqueidentifier column data type stringifying
--EXTENSIONS--
pdo_dblib
--SKIPIF--
<?php
require __DIR__ . '/config.inc';
$db = getDbConnection();
if (in_array($db->getAttribute(PDO::DBLIB_ATTR_TDS_VERSION), ['4.2', '4.6'])) die('skip feature unsupported by this TDS version');
?>
--FILE--
<?php
require __DIR__ . '/config.inc';
$db = getDbConnection();
$testGUID = '82A88958-672B-4C22-842F-216E2B88E72A';
$testGUIDBinary = base64_decode('WImogitnIkyELyFuK4jnKg==');
$sql = "SELECT CAST('$testGUID' as uniqueidentifier) as [guid]";
//--------------------------------------------------------------------------------
// 1. Get and Set the attribute
//--------------------------------------------------------------------------------
$db->setAttribute(PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, true);
var_dump(true === $db->getAttribute(PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER));
$db->setAttribute(PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, false);
var_dump(false === $db->getAttribute(PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER));
//--------------------------------------------------------------------------------
// 2. Binary
//--------------------------------------------------------------------------------
$stmt = $db->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row['guid'] === $testGUIDBinary);
//--------------------------------------------------------------------------------
// 3. PDO::ATTR_STRINGIFY_FETCHES must not affect `uniqueidentifier` representation
//--------------------------------------------------------------------------------
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
$stmt = $db->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
var_dump($row['guid'] === $testGUIDBinary);
//--------------------------------------------------------------------------------
// 4. Stringifying
// ! With TDS protocol version <7.0 binary will be returned and the test will fail !
// TODO: something from PDO::ATTR_SERVER_VERSION, PDO::ATTR_CLIENT_VERSION or PDO::ATTR_SERVER_INFO should be used
// to get TDS version and skip this test in this case.
//--------------------------------------------------------------------------------
$db->setAttribute(PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, true);
$stmt = $db->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row['guid'] === $testGUID);
var_dump($row['guid']);
?>
--EXPECT--
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
string(36) "82A88958-672B-4C22-842F-216E2B88E72A"
| |
225566
|
--TEST--
rfc1867 empty upload
--INI--
file_uploads=1
upload_max_filesize=1024
max_file_uploads=10
--POST_RAW--
Content-Type: multipart/form-data; boundary=---------------------------20896060251896012921717172737
-----------------------------20896060251896012921717172737
Content-Disposition: form-data; name="foo"
-----------------------------20896060251896012921717172737
Content-Disposition: form-data; name="file1"; filename="file1.txt"
Content-Type: text/plain-file1
1
-----------------------------20896060251896012921717172737
Content-Disposition: form-data; name="file2"; filename=""
Content-Type: text/plain-file2
-----------------------------20896060251896012921717172737
Content-Disposition: form-data; name="file3"; filename="file3.txt"
Content-Type: text/plain-file3
3
-----------------------------20896060251896012921717172737--
--FILE--
<?php
var_dump($_FILES);
var_dump($_POST);
if (is_uploaded_file($_FILES["file1"]["tmp_name"])) {
var_dump(file_get_contents($_FILES["file1"]["tmp_name"]));
}
if (is_uploaded_file($_FILES["file3"]["tmp_name"])) {
var_dump(file_get_contents($_FILES["file3"]["tmp_name"]));
}
?>
--EXPECTF--
array(3) {
["file1"]=>
array(6) {
["name"]=>
string(9) "file1.txt"
["full_path"]=>
string(9) "file1.txt"
["type"]=>
string(16) "text/plain-file1"
["tmp_name"]=>
string(%d) "%s"
["error"]=>
int(0)
["size"]=>
int(1)
}
["file2"]=>
array(6) {
["name"]=>
string(0) ""
["full_path"]=>
string(0) ""
["type"]=>
string(0) ""
["tmp_name"]=>
string(0) ""
["error"]=>
int(4)
["size"]=>
int(0)
}
["file3"]=>
array(6) {
["name"]=>
string(9) "file3.txt"
["full_path"]=>
string(9) "file3.txt"
["type"]=>
string(16) "text/plain-file3"
["tmp_name"]=>
string(%d) "%s"
["error"]=>
int(0)
["size"]=>
int(1)
}
}
array(1) {
["foo"]=>
string(0) ""
}
string(1) "1"
string(1) "3"
| |
225783
|
--TEST--
short_open_tag: Off
--INI--
short_open_tag=off
--FILE--
<%= 'so should this' %>
<?php
$a = 'This gets echoed twice';
?>
<?= $a?>
<%= $a%>
<? $b=3; ?>
<?php
echo "{$b}";
?>
<?= "{$b}"?>
--EXPECTF--
<%= 'so should this' %>
This gets echoed twice
<%= $a%>
<? $b=3; ?>
Warning: Undefined variable $b in %s on line %d
Warning: Undefined variable $b in %s on line %d
| |
225826
|
--TEST--
short_open_tag: Off
--INI--
short_open_tag=off
--FILE--
<?
echo "Used a short tag\n";
?>
Finished
--EXPECT--
<?
echo "Used a short tag\n";
?>
Finished
| |
226174
|
/** @return DocCommentTag[] */
function parseDocComments(array $comments): array {
$tags = [];
foreach ($comments as $comment) {
if ($comment instanceof DocComment) {
$tags = array_merge($tags, parseDocComment($comment));
}
}
return $tags;
}
/** @return DocCommentTag[] */
function parseDocComment(DocComment $comment): array {
$commentText = substr($comment->getText(), 2, -2);
$tags = [];
foreach (explode("\n", $commentText) as $commentLine) {
$regex = '/^\*\s*@([a-z-]+)(?:\s+(.+))?$/';
if (preg_match($regex, trim($commentLine), $matches)) {
$tags[] = new DocCommentTag($matches[1], $matches[2] ?? null);
}
}
return $tags;
}
class FramelessFunctionInfo {
public int $arity;
}
function parseFramelessFunctionInfo(string $json): FramelessFunctionInfo {
// FIXME: Should have some validation
$json = json_decode($json, true);
$framelessFunctionInfo = new FramelessFunctionInfo();
$framelessFunctionInfo->arity = $json["arity"];
return $framelessFunctionInfo;
}
function parseFunctionLike(
PrettyPrinterAbstract $prettyPrinter,
FunctionOrMethodName $name,
int $classFlags,
int $flags,
Node\FunctionLike $func,
?string $cond,
bool $isUndocumentable,
?int $minimumPhpVersionIdCompatibility
): FuncInfo {
try {
$comments = $func->getComments();
$paramMeta = [];
$aliasType = null;
$alias = null;
$isDeprecated = false;
$supportsCompileTimeEval = false;
$verify = true;
$docReturnType = null;
$tentativeReturnType = false;
$docParamTypes = [];
$refcount = null;
$framelessFunctionInfos = [];
if ($comments) {
$tags = parseDocComments($comments);
foreach ($tags as $tag) {
switch ($tag->name) {
case 'alias':
case 'implementation-alias':
$aliasType = $tag->name;
$aliasParts = explode("::", $tag->getValue());
if (count($aliasParts) === 1) {
$alias = new FunctionName(new Name($aliasParts[0]));
} else {
$alias = new MethodName(new Name($aliasParts[0]), $aliasParts[1]);
}
break;
case 'deprecated':
$isDeprecated = true;
break;
case 'no-verify':
$verify = false;
break;
case 'tentative-return-type':
$tentativeReturnType = true;
break;
case 'return':
$docReturnType = $tag->getType();
break;
case 'param':
$docParamTypes[$tag->getVariableName()] = $tag->getType();
break;
case 'refcount':
$refcount = $tag->getValue();
break;
case 'compile-time-eval':
$supportsCompileTimeEval = true;
break;
case 'prefer-ref':
$varName = $tag->getVariableName();
if (!isset($paramMeta[$varName])) {
$paramMeta[$varName] = [];
}
$paramMeta[$varName][$tag->name] = true;
break;
case 'undocumentable':
$isUndocumentable = true;
break;
case 'frameless-function':
$framelessFunctionInfos[] = parseFramelessFunctionInfo($tag->getValue());
break;
}
}
}
$varNameSet = [];
$args = [];
$numRequiredArgs = 0;
$foundVariadic = false;
foreach ($func->getParams() as $i => $param) {
if ($param->isPromoted()) {
throw new Exception("Promoted properties are not supported");
}
$varName = $param->var->name;
$preferRef = !empty($paramMeta[$varName]['prefer-ref']);
unset($paramMeta[$varName]);
if (isset($varNameSet[$varName])) {
throw new Exception("Duplicate parameter name $varName");
}
$varNameSet[$varName] = true;
if ($preferRef) {
$sendBy = ArgInfo::SEND_PREFER_REF;
} else if ($param->byRef) {
$sendBy = ArgInfo::SEND_BY_REF;
} else {
$sendBy = ArgInfo::SEND_BY_VAL;
}
if ($foundVariadic) {
throw new Exception("Only the last parameter can be variadic");
}
$type = $param->type ? Type::fromNode($param->type) : null;
if ($type === null && !isset($docParamTypes[$varName])) {
throw new Exception("Missing parameter type");
}
if ($param->default instanceof Expr\ConstFetch &&
$param->default->name->toLowerString() === "null" &&
$type && !$type->isNullable()
) {
$simpleType = $type->tryToSimpleType();
if ($simpleType === null || !$simpleType->isMixed()) {
throw new Exception("Parameter $varName has null default, but is not nullable");
}
}
if ($param->default instanceof Expr\ClassConstFetch && $param->default->class->toLowerString() === "self") {
throw new Exception('The exact class name must be used instead of "self"');
}
$foundVariadic = $param->variadic;
$args[] = new ArgInfo(
$varName,
$sendBy,
$param->variadic,
$type,
isset($docParamTypes[$varName]) ? Type::fromString($docParamTypes[$varName]) : null,
$param->default ? $prettyPrinter->prettyPrintExpr($param->default) : null,
createAttributes($param->attrGroups)
);
if (!$param->default && !$param->variadic) {
$numRequiredArgs = $i + 1;
}
}
foreach (array_keys($paramMeta) as $var) {
throw new Exception("Found metadata for invalid param $var");
}
$returnType = $func->getReturnType();
if ($returnType === null && $docReturnType === null && !$name->isConstructor() && !$name->isDestructor()) {
throw new Exception("Missing return type");
}
$return = new ReturnInfo(
$func->returnsByRef(),
$returnType ? Type::fromNode($returnType) : null,
$docReturnType ? Type::fromString($docReturnType) : null,
$tentativeReturnType,
$refcount
);
return new FuncInfo(
$name,
$classFlags,
$flags,
$aliasType,
$alias,
$isDeprecated,
$supportsCompileTimeEval,
$verify,
$args,
$return,
$numRequiredArgs,
$cond,
$isUndocumentable,
$minimumPhpVersionIdCompatibility,
createAttributes($func->attrGroups),
$framelessFunctionInfos,
createExposedDocComment($comments)
);
} catch (Exception $e) {
throw new Exception($name . "(): " .$e->getMessage());
}
}
/**
* @param array<int, array<int, AttributeGroup> $attributes
*/
function parseConstLike(
PrettyPrinterAbstract $prettyPrinter,
ConstOrClassConstName $name,
Node\Const_ $const,
int $flags,
?Node $type,
array $comments,
?string $cond,
bool $isUndocumentable,
?int $phpVersionIdMinimumCompatibility,
array $attributes
): ConstInfo {
$phpDocType = null;
$deprecated = false;
$cValue = null;
$link = null;
$isFileCacheAllowed = true;
if ($comments) {
$tags = parseDocComments($comments);
foreach ($tags as $tag) {
if ($tag->name === 'var') {
$phpDocType = $tag->getType();
} elseif ($tag->name === 'deprecated') {
$deprecated = true;
} elseif ($tag->name === 'cvalue') {
$cValue = $tag->value;
} elseif ($tag->name === 'undocumentable') {
$isUndocumentable = true;
} elseif ($tag->name === 'link') {
$link = $tag->value;
} elseif ($tag->name === 'no-file-cache') {
$isFileCacheAllowed = false;
}
}
}
if ($type === null && $phpDocType === null) {
throw new Exception("Missing type for constant " . $name->__toString());
}
$constType = $type ? Type::fromNode($type) : null;
$constPhpDocType = $phpDocType ? Type::fromString($phpDocType) : null;
| |
226762
|
--TEST--
Post a file
--SKIPIF--
<?php
include "skipif.inc";
?>
--FILE--
<?php
include "php_cli_server.inc";
php_cli_server_start('var_dump($_FILES);');
$host = PHP_CLI_SERVER_HOSTNAME;
$fp = php_cli_server_connect();
$post_data = <<<POST
-----------------------------114782935826962
Content-Disposition: form-data; name="userfile"; filename="laruence.txt"
Content-Type: text/plain
I am not sure about this.
-----------------------------114782935826962--
POST;
$post_len = strlen($post_data);
if(fwrite($fp, <<<HEADER
POST / HTTP/1.1
Host: {$host}
Content-Type: multipart/form-data; boundary=---------------------------114782935826962
Content-Length: {$post_len}
{$post_data}
HEADER
)) {
while (!feof($fp)) {
echo fgets($fp);
}
}
?>
--EXPECTF--
HTTP/1.1 200 OK
Host: %s
Date: %s
Connection: close
X-Powered-By: PHP/%s
Content-type: text/html; charset=UTF-8
array(1) {
["userfile"]=>
array(6) {
["name"]=>
string(12) "laruence.txt"
["full_path"]=>
string(12) "laruence.txt"
["type"]=>
string(10) "text/plain"
["tmp_name"]=>
string(%d) "%s"
["error"]=>
int(0)
["size"]=>
int(26)
}
}
| |
227378
|
"psr-4": {
"Intervention\\Image\\": "src/Intervention/Image"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Oliver Vogel",
"email": "oliver@intervention.io",
"homepage": "https://intervention.io/"
}
],
"description": "Image handling and manipulation library with support for Laravel integration",
"homepage": "http://image.intervention.io/",
"keywords": [
"gd",
"image",
"imagick",
"laravel",
"thumbnail",
"watermark"
],
"support": {
"issues": "https://github.com/Intervention/image/issues",
"source": "https://github.com/Intervention/image/tree/2.7.2"
},
"funding": [
{
"url": "https://paypal.me/interventionio",
"type": "custom"
},
{
"url": "https://github.com/Intervention",
"type": "github"
}
],
"time": "2022-05-21T17:30:32+00:00"
},
{
"name": "laravel/framework",
"version": "v10.42.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/framework.git",
"reference": "fef1aff874a6749c44f8e142e5764eab8cb96890"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/framework/zipball/fef1aff874a6749c44f8e142e5764eab8cb96890",
"reference": "fef1aff874a6749c44f8e142e5764eab8cb96890",
"shasum": ""
},
"require": {
"brick/math": "^0.9.3|^0.10.2|^0.11",
"composer-runtime-api": "^2.2",
"doctrine/inflector": "^2.0.5",
"dragonmantank/cron-expression": "^3.3.2",
"egulias/email-validator": "^3.2.1|^4.0",
"ext-ctype": "*",
"ext-filter": "*",
"ext-hash": "*",
"ext-mbstring": "*",
"ext-openssl": "*",
"ext-session": "*",
"ext-tokenizer": "*",
"fruitcake/php-cors": "^1.2",
"guzzlehttp/uri-template": "^1.0",
"laravel/prompts": "^0.1.9",
"laravel/serializable-closure": "^1.3",
"league/commonmark": "^2.2.1",
"league/flysystem": "^3.8.0",
"monolog/monolog": "^3.0",
"nesbot/carbon": "^2.67",
"nunomaduro/termwind": "^1.13",
"php": "^8.1",
"psr/container": "^1.1.1|^2.0.1",
"psr/log": "^1.0|^2.0|^3.0",
"psr/simple-cache": "^1.0|^2.0|^3.0",
"ramsey/uuid": "^4.7",
"symfony/console": "^6.2",
"symfony/error-handler": "^6.2",
"symfony/finder": "^6.2",
"symfony/http-foundation": "^6.4",
"symfony/http-kernel": "^6.2",
"symfony/mailer": "^6.2",
"symfony/mime": "^6.2",
"symfony/process": "^6.2",
"symfony/routing": "^6.2",
"symfony/uid": "^6.2",
"symfony/var-dumper": "^6.2",
"tijsverkoyen/css-to-inline-styles": "^2.2.5",
"vlucas/phpdotenv": "^5.4.1",
"voku/portable-ascii": "^2.0"
},
"conflict": {
"carbonphp/carbon-doctrine-types": ">=3.0",
"doctrine/dbal": ">=4.0",
"tightenco/collect": "<5.5.33"
},
"provide": {
"psr/container-implementation": "1.1|2.0",
"psr/simple-cache-implementation": "1.0|2.0|3.0"
},
"replace": {
"illuminate/auth": "self.version",
"illuminate/broadcasting": "self.version",
"illuminate/bus": "self.version",
"illuminate/cache": "self.version",
"illuminate/collections": "self.version",
"illuminate/conditionable": "self.version",
"illuminate/config": "self.version",
"illuminate/console": "self.version",
"illuminate/container": "self.version",
"illuminate/contracts": "self.version",
"illuminate/cookie": "self.version",
"illuminate/database": "self.version",
"illuminate/encryption": "self.version",
"illuminate/events": "self.version",
"illuminate/filesystem": "self.version",
"illuminate/hashing": "self.version",
"illuminate/http": "self.version",
"illuminate/log": "self.version",
"illuminate/macroable": "self.version",
"illuminate/mail": "self.version",
"illuminate/notifications": "self.version",
"illuminate/pagination": "self.version",
"illuminate/pipeline": "self.version",
"illuminate/process": "self.version",
"illuminate/queue": "self.version",
"illuminate/redis": "self.version",
"illuminate/routing": "self.version",
"illuminate/session": "self.version",
"illuminate/support": "self.version",
"illuminate/testing": "self.version",
"illuminate/translation": "self.version",
"illuminate/validation": "self.version",
"illuminate/view": "self.version"
},
"require-dev": {
"ably/ably-php": "^1.0",
"aws/aws-sdk-php": "^3.235.5",
"doctrine/dbal": "^3.5.1",
"ext-gmp": "*",
"fakerphp/faker": "^1.21",
"guzzlehttp/guzzle": "^7.5",
"league/flysystem-aws-s3-v3": "^3.0",
"league/flysystem-ftp": "^3.0",
"league/flysystem-path-prefixing": "^3.3",
"league/flysystem-read-only": "^3.3",
"league/flysystem-sftp-v3": "^3.0",
"mockery/mockery": "^1.5.1",
"nyholm/psr7": "^1.2",
"orchestra/testbench-core": "^8.18",
"pda/pheanstalk": "^4.0",
"phpstan/phpstan": "^1.4.7",
"phpunit/phpunit": "^10.0.7",
"predis/predis": "^2.0.2",
"symfony/cache": "^6.2",
"symfony/http-client": "^6.2.4",
"symfony/psr-http-message-bridge": "^2.0"
},
"suggest": {
"ably/ably-php": "Required to use the Ably broadcast driver (^1.0).",
"aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage, and SES mail driver (^3.235.5).",
"brianium/paratest": "Required to run tests in parallel (^6.0).",
"doctrine/dbal": "Required to rename columns and drop SQLite columns (^3.5.1).",
"ext-apcu": "Required to use the APC cache driver.",
"ext-fileinfo": "Required to use the Filesystem class.",
"ext-ftp": "Required to use the Flysystem FTP driver.",
"ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().",
"ext-memcached": "Required to use the memcache cache driver.",
"ext-pcntl": "Required to use all features of the queue worker and console signal trapping.",
"ext-pdo": "Required to use all database features.",
"ext-posix": "Required to use all features of the queue worker.",
"ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).",
"fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).",
| |
227379
|
"filp/whoops": "Required for friendly error pages in development (^2.14.3).",
"guzzlehttp/guzzle": "Required to use the HTTP Client and the ping methods on schedules (^7.5).",
"laravel/tinker": "Required to use the tinker console command (^2.0).",
"league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^3.0).",
"league/flysystem-ftp": "Required to use the Flysystem FTP driver (^3.0).",
"league/flysystem-path-prefixing": "Required to use the scoped driver (^3.3).",
"league/flysystem-read-only": "Required to use read-only disks (^3.3)",
"league/flysystem-sftp-v3": "Required to use the Flysystem SFTP driver (^3.0).",
"mockery/mockery": "Required to use mocking (^1.5.1).",
"nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).",
"pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).",
"phpunit/phpunit": "Required to use assertions and run tests (^9.5.8|^10.0.7).",
"predis/predis": "Required to use the predis connector (^2.0.2).",
"psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).",
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0|^7.0).",
"symfony/cache": "Required to PSR-6 cache bridge (^6.2).",
"symfony/filesystem": "Required to enable support for relative symbolic links (^6.2).",
"symfony/http-client": "Required to enable support for the Symfony API mail transports (^6.2).",
"symfony/mailgun-mailer": "Required to enable support for the Mailgun mail transport (^6.2).",
"symfony/postmark-mailer": "Required to enable support for the Postmark mail transport (^6.2).",
"symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0)."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "10.x-dev"
}
},
"autoload": {
"files": [
"src/Illuminate/Collections/helpers.php",
"src/Illuminate/Events/functions.php",
"src/Illuminate/Filesystem/functions.php",
"src/Illuminate/Foundation/helpers.php",
"src/Illuminate/Support/helpers.php"
],
"psr-4": {
"Illuminate\\": "src/Illuminate/",
"Illuminate\\Support\\": [
"src/Illuminate/Macroable/",
"src/Illuminate/Collections/",
"src/Illuminate/Conditionable/"
]
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "The Laravel Framework.",
"homepage": "https://laravel.com",
"keywords": [
"framework",
"laravel"
],
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2024-01-23T15:07:56+00:00"
},
{
"name": "laravel/prompts",
"version": "v0.1.15",
"source": {
"type": "git",
"url": "https://github.com/laravel/prompts.git",
"reference": "d814a27514d99b03c85aa42b22cfd946568636c1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/prompts/zipball/d814a27514d99b03c85aa42b22cfd946568636c1",
"reference": "d814a27514d99b03c85aa42b22cfd946568636c1",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"illuminate/collections": "^10.0|^11.0",
"php": "^8.1",
"symfony/console": "^6.2|^7.0"
},
"conflict": {
"illuminate/console": ">=10.17.0 <10.25.0",
"laravel/framework": ">=10.17.0 <10.25.0"
},
"require-dev": {
"mockery/mockery": "^1.5",
"pestphp/pest": "^2.3",
"phpstan/phpstan": "^1.11",
"phpstan/phpstan-mockery": "^1.1"
},
"suggest": {
"ext-pcntl": "Required for the spinner to be animated."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "0.1.x-dev"
}
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Laravel\\Prompts\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"support": {
"issues": "https://github.com/laravel/prompts/issues",
"source": "https://github.com/laravel/prompts/tree/v0.1.15"
},
"time": "2023-12-29T22:37:42+00:00"
},
{
"name": "laravel/sanctum",
"version": "v3.3.3",
"source": {
"type": "git",
"url": "https://github.com/laravel/sanctum.git",
"reference": "8c104366459739f3ada0e994bcd3e6fd681ce3d5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/sanctum/zipball/8c104366459739f3ada0e994bcd3e6fd681ce3d5",
"reference": "8c104366459739f3ada0e994bcd3e6fd681ce3d5",
"shasum": ""
},
"require": {
"ext-json": "*",
"illuminate/console": "^9.21|^10.0",
"illuminate/contracts": "^9.21|^10.0",
"illuminate/database": "^9.21|^10.0",
"illuminate/support": "^9.21|^10.0",
"php": "^8.0.2"
},
"require-dev": {
"mockery/mockery": "^1.0",
"orchestra/testbench": "^7.28.2|^8.8.3",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.6"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
},
"laravel": {
"providers": [
"Laravel\\Sanctum\\SanctumServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Laravel\\Sanctum\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.",
"keywords": [
"auth",
"laravel",
"sanctum"
],
"support": {
"issues": "https://github.com/laravel/sanctum/issues",
"source": "https://github.com/laravel/sanctum"
},
"time": "2023-12-19T18:44:48+00:00"
},
{
"name": "laravel/serializable-closure",
"version": "v1.3.3",
"source": {
"type": "git",
"url": "https://github.com/laravel/serializable-closure.git",
"reference": "3dbf8a8e914634c48d389c1234552666b3d43754"
},
"dist": {
"type": "zip",
| |
227412
|
"openai-php/client": "Require get solutions from OpenAI",
"simple-cache-implementation": "To cache solutions from OpenAI"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.5.x-dev"
}
},
"autoload": {
"psr-4": {
"Spatie\\Ignition\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Spatie",
"email": "info@spatie.be",
"role": "Developer"
}
],
"description": "A beautiful error page for PHP applications.",
"homepage": "https://flareapp.io/ignition",
"keywords": [
"error",
"flare",
"laravel",
"page"
],
"support": {
"docs": "https://flareapp.io/docs/ignition-for-laravel/introduction",
"forum": "https://twitter.com/flareappio",
"issues": "https://github.com/spatie/ignition/issues",
"source": "https://github.com/spatie/ignition"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2024-01-03T15:49:39+00:00"
},
{
"name": "spatie/laravel-ignition",
"version": "2.4.1",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-ignition.git",
"reference": "005e1e7b1232f3b22d7e7be3f602693efc7dba67"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-ignition/zipball/005e1e7b1232f3b22d7e7be3f602693efc7dba67",
"reference": "005e1e7b1232f3b22d7e7be3f602693efc7dba67",
"shasum": ""
},
"require": {
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"illuminate/support": "^10.0|^11.0",
"php": "^8.1",
"spatie/flare-client-php": "^1.3.5",
"spatie/ignition": "^1.9",
"symfony/console": "^6.2.3|^7.0",
"symfony/var-dumper": "^6.2.3|^7.0"
},
"require-dev": {
"livewire/livewire": "^2.11|^3.3.5",
"mockery/mockery": "^1.5.1",
"openai-php/client": "^0.8.1",
"orchestra/testbench": "^8.0|^9.0",
"pestphp/pest": "^2.30",
"phpstan/extension-installer": "^1.2",
"phpstan/phpstan-deprecation-rules": "^1.1.1",
"phpstan/phpstan-phpunit": "^1.3.3",
"vlucas/phpdotenv": "^5.5"
},
"suggest": {
"openai-php/client": "Require get solutions from OpenAI",
"psr/simple-cache-implementation": "Needed to cache solutions from OpenAI"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Spatie\\LaravelIgnition\\IgnitionServiceProvider"
],
"aliases": {
"Flare": "Spatie\\LaravelIgnition\\Facades\\Flare"
}
}
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Spatie\\LaravelIgnition\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Spatie",
"email": "info@spatie.be",
"role": "Developer"
}
],
"description": "A beautiful error page for Laravel applications.",
"homepage": "https://flareapp.io/ignition",
"keywords": [
"error",
"flare",
"laravel",
"page"
],
"support": {
"docs": "https://flareapp.io/docs/ignition-for-laravel/introduction",
"forum": "https://twitter.com/flareappio",
"issues": "https://github.com/spatie/laravel-ignition/issues",
"source": "https://github.com/spatie/laravel-ignition"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2024-01-12T13:14:58+00:00"
},
{
"name": "theseer/tokenizer",
"version": "1.2.2",
"source": {
"type": "git",
"url": "https://github.com/theseer/tokenizer.git",
"reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/theseer/tokenizer/zipball/b2ad5003ca10d4ee50a12da31de12a5774ba6b96",
"reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
"php": "^7.2 || ^8.0"
},
"type": "library",
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Arne Blankerts",
"email": "arne@blankerts.de",
"role": "Developer"
}
],
"description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
"support": {
"issues": "https://github.com/theseer/tokenizer/issues",
"source": "https://github.com/theseer/tokenizer/tree/1.2.2"
},
"funding": [
{
"url": "https://github.com/theseer",
"type": "github"
}
],
"time": "2023-11-20T00:12:19+00:00"
}
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {
"laravel/unfenced": 20
},
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
"php": "^8.1"
},
"platform-dev": [],
"plugin-api-version": "2.6.0"
}
| |
227414
|
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
| |
227417
|
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);
| |
227419
|
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| |
227426
|
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
| |
227430
|
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Torchlight\Middleware\RenderTorchlight::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers:public;max_age=300',
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
| |
227431
|
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}
| |
227432
|
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
| |
227434
|
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
| |
227436
|
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}
| |
227437
|
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
| |
227438
|
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
| |
227442
|
#!/bin/bash
if [ ! -f composer.json ]; then
echo "Please make sure to run this script from the root directory of this repo."
exit 1
fi
composer install
cp .env.example .env
php artisan key:generate
source "$(dirname "$0")/checkout_latest_docs.sh"
npm install
npm run build
| |
227444
|
#!/bin/bash
if [ ! -f composer.json ]; then
echo "Please make sure to run this script from the root directory of this repo."
exit 1
fi
composer install
source "$(dirname "$0")/checkout_latest_docs.sh"
npm install
npm run build
| |
227448
|
<?php
use Illuminate\Support\Facades\Facade;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'Example' => App\Facades\Example::class,
])->toArray(),
];
| |
227451
|
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];
| |
227453
|
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION', null),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc", "memcached", or "dynamodb" session drivers you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
*/
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
];
| |
227454
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];
| |
227458
|
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
| |
227459
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => env('FILESYSTEM_CLOUD', 's3'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'endpoint' => env('AWS_URL'),
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
| |
227462
|
.docs_main {
/* Headers */
& h1, & h2, & h3, & h4, & h5, & h6, & h4 a, & h3 a, & h2 a {
@apply dark:text-gray-200;
}
/* Body text */
& p, & ul:not(:first-of-type) li, & .content-list ul li, & #software-list, & #valet-support {
@apply dark:text-gray-400;
}
/* Table of contents */
& h1 + ul li a {
@apply dark:text-gray-300;
}
/* Links */
& p a, & ul a, & ol a {
@apply dark:text-red-600;
}
/* Tables */
& table th {
@apply dark:text-gray-200;
@apply dark:border-gray-700;
}
& table td {
@apply dark:text-gray-400;
@apply dark:border-gray-700;
}
& table td.support-policy-highlight {
@apply dark:text-black;
}
}
.docs_sidebar {
/* Sidebar links */
& ul li h2, & ul li a {
@apply dark:text-gray-400;
}
}
/* Pound sign before headings */
.dark .docs_main {
& h4 a:before, & h3 a:before, & h2 a:before {
opacity: 1;
}
}
/* Carbon ads */
#carbonads {
@apply dark:bg-dark-600;
& .carbon-text {
@apply dark:text-gray-400;
}
& .carbon-poweredby {
@apply dark:text-gray-500;
}
}
/* Color mode buttons */
#header__sun, #header__moon, #header__indeterminate { display: none; }
html[color-theme="dark"] #header__moon { display: block; }
html[color-theme="light"] #header__sun { display: block; }
html[color-theme="system"] #header__indeterminate { display: block; }
| |
227464
|
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import "./_typography.css";
@import "./_code.css";
@import "./_sidebar_layout.css";
@import "./_search.css";
@import "./_docs.css";
@import "./_carbon_ads.css";
@import "./_accessibility.css";
@import 'tailwindcss/utilities';
@import "./_dark_mode.css";
[x-cloak] {
display: none !important;
}
.bg-radial-gradient {
background-image: radial-gradient(50% 50% at 50% 50%, #EB4432 0%, rgba(255, 255, 255, 0) 100%);
}
.partners_body a {
color: theme('colors.red.600');
text-decoration: underline;
}
.version-colors {
@apply sm:flex dark:text-gray-400 mb-1;
}
.version-colors .color-box {
@apply w-3 h-3 mr-2 ;
}
.version-colors div.end-of-life {
@apply flex items-center mr-4;
}
.version-colors div.end-of-life div:first-child {
@apply bg-red-500;
}
.version-colors div.security-fixes {
@apply flex items-center;
}
.version-colors div.security-fixes div:first-child {
@apply bg-orange-600;
}
| |
227486
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, dashes and underscores.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_equals' => 'The :attribute must be a date equal to :date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'dimensions' => 'The :attribute has invalid image dimensions.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'exists' => 'The selected :attribute is invalid.',
'file' => 'The :attribute must be a file.',
'filled' => 'The :attribute field must have a value.',
'gt' => [
'numeric' => 'The :attribute must be greater than :value.',
'file' => 'The :attribute must be greater than :value kilobytes.',
'string' => 'The :attribute must be greater than :value characters.',
'array' => 'The :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'The :attribute must be greater than or equal :value.',
'file' => 'The :attribute must be greater than or equal :value kilobytes.',
'string' => 'The :attribute must be greater than or equal :value characters.',
'array' => 'The :attribute must have :value items or more.',
],
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
'json' => 'The :attribute must be a valid JSON string.',
'lt' => [
'numeric' => 'The :attribute must be less than :value.',
'file' => 'The :attribute must be less than :value kilobytes.',
'string' => 'The :attribute must be less than :value characters.',
'array' => 'The :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'The :attribute must be less than or equal :value.',
'file' => 'The :attribute must be less than or equal :value kilobytes.',
'string' => 'The :attribute must be less than or equal :value characters.',
'array' => 'The :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'mimetypes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'not_regex' => 'The :attribute format is invalid.',
'numeric' => 'The :attribute must be a number.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values are present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'starts_with' => 'The :attribute must start with one of the following: :values',
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
'uuid' => 'The :attribute must be a valid UUID.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/
'attributes' => [],
];
| |
227517
|
<header
class="lg:hidden"
@keydown.window.escape="navIsOpen = false"
@click.away="navIsOpen = false"
>
<div class="relative mx-auto w-full py-10 bg-white transition duration-200 dark:bg-dark-700">
<div class="mx-auto px-8 sm:px-16 flex items-center justify-between">
<a href="/" class="flex items-center">
<img class="" src="/img/logomark.min.svg" alt="Laravel" width="50" height="52">
<img class="hidden ml-5 sm:block" src="/img/logotype.min.svg" alt="Laravel" width="114" height="29">
</a>
<div class="flex-1 flex items-center justify-end">
<button id="header__sun" onclick="toSystemMode()" title="Switch to system theme" class="relative w-10 h-10 focus:outline-none focus:shadow-outline text-gray-500">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-sun" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<circle cx="12" cy="12" r="4"></circle>
<path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"></path>
</svg>
</button>
<button id="header__moon" onclick="toLightMode()" title="Switch to light mode" class="relative w-10 h-10 focus:outline-none focus:shadow-outline text-gray-500">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="currentColor" d="M17.75,4.09L15.22,6.03L16.13,9.09L13.5,7.28L10.87,9.09L11.78,6.03L9.25,4.09L12.44,4L13.5,1L14.56,4L17.75,4.09M21.25,11L19.61,12.25L20.2,14.23L18.5,13.06L16.8,14.23L17.39,12.25L15.75,11L17.81,10.95L18.5,9L19.19,10.95L21.25,11M18.97,15.95C19.8,15.87 20.69,17.05 20.16,17.8C19.84,18.25 19.5,18.67 19.08,19.07C15.17,23 8.84,23 4.94,19.07C1.03,15.17 1.03,8.83 4.94,4.93C5.34,4.53 5.76,4.17 6.21,3.85C6.96,3.32 8.14,4.21 8.06,5.04C7.79,7.9 8.75,10.87 10.95,13.06C13.14,15.26 16.1,16.22 18.97,15.95M17.33,17.97C14.5,17.81 11.7,16.64 9.53,14.5C7.36,12.31 6.2,9.5 6.04,6.68C3.23,9.82 3.34,14.64 6.35,17.66C9.37,20.67 14.19,20.78 17.33,17.97Z" />
</svg>
</button>
<button id="header__indeterminate" onclick="toDarkMode()" title="Switch to dark mode" class="relative w-10 h-10 focus:outline-none focus:shadow-outline text-gray-500">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="currentColor" d="M12 2A10 10 0 0 0 2 12A10 10 0 0 0 12 22A10 10 0 0 0 22 12A10 10 0 0 0 12 2M12 4A8 8 0 0 1 20 12A8 8 0 0 1 12 20V4Z" />
</svg>
</button>
<button class="ml-2 relative w-10 h-10 p-2 text-red-600 lg:hidden focus:outline-none focus:shadow-outline" aria-label="Menu" @click.prevent="navIsOpen = !navIsOpen">
<svg x-show="! navIsOpen" x-transition.opacity class="absolute inset-0 mt-2 ml-2 w-6 h-6" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
<svg x-show="navIsOpen" x-transition.opacity x-cloak class="absolute inset-0 mt-2 ml-2 w-6 h-6" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
</div>
<span :class="{ 'shadow-sm': navIsOpen }" class="absolute inset-0 z-20 pointer-events-none"></span>
</div>
<div
x-show="navIsOpen"
x-transition:enter="duration-150"
x-transition:leave="duration-100 ease-in"
x-cloak
>
<nav
x-show="navIsOpen"
x-cloak
class="absolute w-full transform origin-top shadow-sm z-10"
x-transition:enter="duration-150 ease-out"
x-transition:enter-start="opacity-0 -translate-y-8 scale-75"
x-transition:enter-end="opacity-100 scale-100"
x-transition:leave="duration-100 ease-in"
x-transition:leave-start="opacity-100 scale-100"
x-transition:leave-end="opacity-0 -translate-y-8 scale-75"
>
<div class="relative p-8 bg-white docs_sidebar dark:bg-dark-600">
{!! $index !!}
</div>
</nav>
</div>
</header>
| |
227597
|
<div id="main-content">
{{ $slot }}
</div>
| |
227598
|
<header
x-trap.inert.noscroll="navIsOpen"
class="main-header relative z-50 text-gray-700"
@keydown.window.escape="navIsOpen = false"
@click.away="navIsOpen = false"
>
<x-header-news-bar />
<div class="relative max-w-screen-2xl mx-auto w-full py-4 bg-white transition duration-200 lg:bg-transparent lg:py-6">
<div class="max-w-screen-xl mx-auto px-5 flex items-center justify-between">
<div class="flex-1">
<a href="/" class="inline-flex items-center">
<img class="w-12" src="/img/logomark.min.svg" alt="Laravel" width="50" height="52">
<img class="ml-5 sm:block" src="/img/logotype.min.svg" alt="Laravel" width="114" height="29">
</a>
</div>
<ul class="relative hidden lg:flex lg:items-center lg:justify-center lg:gap-6 xl:gap-10">
<li><a href="https://forge.laravel.com">Forge</a></li>
<li><a href="https://vapor.laravel.com">Vapor</a></li>
<li x-data="{ expanded: false }" class="relative" @keydown.window.escape="expanded = false">
<button class="flex items-center justify-center" @click="expanded = !expanded">
Ecosystem
<span class="ml-3 shrink-0">
<svg xmlns="http://www.w3.org/2000/svg" :class="{ 'rotate-180': expanded }" class="h-4 w-4 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /></svg>
</span>
</button>
<div
x-show="expanded"
x-cloak
class="absolute left-28 z-20 transition transform -translate-x-1/2"
x-transition:enter="duration-250 ease-out"
x-transition:enter-start="opacity-0 -translate-y-8"
x-transition:enter-end="opacity-100"
x-transition:leave="duration-250 ease-in"
x-transition:leave-start="opacity-100"
x-transition:leave-end="opacity-0 -translate-y-8"
>
<div
class="mt-4 w-224 p-8 bg-white shadow-lg transform transition-transform origin-top"
@click.away="expanded = false"
>
<ul class="grid gap-6 relative sm:grid-cols-2 md:grid-cols-3">
@foreach (App\Ecosystem::items() as $ecosystemItemId => $ecosystemItem)
<li>
<a href="{{ $ecosystemItem['href'] }}" class="flex">
<div class="relative shrink-0 w-12 h-12 bg-{{ $ecosystemItemId }} flex items-center justify-center rounded-lg overflow-hidden">
<span class="absolute inset-0 w-full h-full bg-gradient-to-b from-[rgba(255,255,255,.2)] to-[rgba(255,255,255,0)]"></span>
<img src="/img/ecosystem/{{ $ecosystemItemId }}.min.svg" alt="{{ $ecosystemItem['image-alt'] }}" class="@if ($ecosystemItemId === 'pennant') w-9 h-9 @else w-7 h-7 @endif" @if ($ecosystemItemId === 'pennant') width="36" height="36" @else width="28" height="28" @endif loading="lazy">
</div>
<div class="ml-4 leading-5">
<div class="text-gray-900">{{ $ecosystemItem['name'] }}</div>
<span class="text-gray-700 text-xs">{{ $ecosystemItem['description'] }}</span>
</div>
</a>
</li>
@endforeach
</ul>
</div>
</div>
</li>
<li><a href="https://laravel-news.com">News</a></li>
<li><a href="https://partners.laravel.com">Partners</a></li>
<li><a href="{{ route('careers') }}">Careers</a></li>
{{-- <li><a href="https://laravel.bigcartel.com/">Shop</a></li> --}}
</ul>
<div class="flex-1 flex items-center justify-end">
<button id="docsearch"></button>
<x-button.secondary href="/docs/{{ DEFAULT_VERSION }}" class="hidden lg:ml-4 lg:inline-flex">Documentation</x-button.secondary>
<button
class="ml-2 relative w-10 h-10 inline-flex items-center justify-center p-2 text-gray-700 lg:hidden"
aria-label="Toggle Menu"
@click.prevent="navIsOpen = !navIsOpen"
>
<svg x-show="! navIsOpen" class="w-6" viewBox="0 0 28 12" fill="none" xmlns="http://www.w3.org/2000/svg"><line y1="1" x2="28" y2="1" stroke="currentColor" stroke-width="2"/><line y1="11" x2="28" y2="11" stroke="currentColor" stroke-width="2"/></svg>
<svg x-show="navIsOpen" x-cloak class="absolute inset-0 mt-2.5 ml-2.5 w-5" viewBox="0 0 19 19" fill="none" xmlns="http://www.w3.org/2000/svg"><rect y="1.41406" width="2" height="24" transform="rotate(-45 0 1.41406)" fill="currentColor"/><rect width="2" height="24" transform="matrix(0.707107 0.707107 0.707107 -0.707107 0.192383 16.9707)" fill="currentColor"/></svg>
</button>
</div>
</div>
</div>
<div
x-show="navIsOpen"
class="lg:hidden"
x-transition:enter="duration-150"
x-transition:leave="duration-100 ease-in"
x-cloak
>
<nav
x-show="navIsOpen"
x-transition.opacity
x-cloak
class="fixed inset-0 w-full pt-[4.2rem] z-10 pointer-events-none"
>
<div class="relative h-full w-full py-8 px-5 bg-white pointer-events-auto overflow-y-auto">
<ul>
<li><a class="block w-full py-2" href="https://forge.laravel.com">Forge</a></li>
<li><a class="block w-full py-2" href="https://vapor.laravel.com">Vapor</a></li>
<li><a class="block w-full py-3" href="https://laravel-news.com">News</a></li>
<li><a class="block w-full py-3" href="https://partners.laravel.com">Partners</a></li>
<li><a class="block w-full py-3" href="{{ route('careers') }}">Careers</a></li>
{{-- <li><a class="block w-full py-3" href="https://laravel.bigcartel.com/products">Shop</a></li> --}}
<li class="flex sm:justify-center"><x-button.secondary class="mt-3 w-full max-w-md" href="/docs/{{ DEFAULT_VERSION }}">Documentation</x-button.secondary></li>
</ul>
</div>
</nav>
</div>
</header>
| |
227601
|
<x-tabs>
<x-tabs.tab name="authentication" title="Authentication" icon="lock-closed">
<p>Authenticating users is as simple as adding an authentication middleware to your Laravel route definition:</p>
<pre><x-torchlight-code language="php">
Route::get('/profile', ProfileController::class)
->middleware('auth');
</x-torchlight-code></pre>
<p>Once the user is authenticated, you can access the authenticated user via the <code>Auth</code> facade:</p>
<pre><x-torchlight-code language="php">
use Illuminate\Support\Facades\Auth;
// Get the currently authenticated user...
$user = Auth::user();
</x-torchlight-code></pre>
<p>Of course, you may define your own authentication middleware, allowing you to customize the authentication process.</p>
<p>For more information on Laravel's authentication features, check out the <a href="https://laravel.com/docs/authentication">authentication documentation</a>.</p>
</x-tabs.tab>
<x-tabs.tab name="authorization" title="Authorization" icon="identification">
<p>You'll often need to check whether an authenticated user is authorized to perform a specific action. Laravel's model policies make it a breeze:</p>
<pre><x-torchlight-code language="bash">
php artisan make:policy UserPolicy
</x-torchlight-code></pre>
<p>Once you've defined your authorization rules in the generated policy class, you can authorize the user's request in your controller methods:</p>
<pre><x-torchlight-code language="php">
public function update(Request $request, Invoice $invoice)
{
Gate::authorize('update', $invoice);// [tl! focus]
$invoice->update(/* ... */);
}
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/authorization">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="eloquent" title="Eloquent ORM" icon="table-cells">
<p>Scared of databases? Don't be. Laravel’s Eloquent ORM makes it painless to interact with your application's data, and models, migrations, and relationships can be quickly scaffolded:</p>
<pre><x-torchlight-code language="text">
php artisan make:model Invoice --migration
</x-torchlight-code></pre>
<p>Once you've defined your model structure and relationships, you can interact with your database using Eloquent's powerful, expressive syntax:</p>
<pre><x-torchlight-code language="php">
// Create a related model...
$user->invoices()->create(['amount' => 100]);
// Update a model...
$invoice->update(['amount' => 200]);
// Retrieve models...
$invoices = Invoice::unpaid()->where('amount', '>=', 100)->get();
// Rich API for model interactions...
$invoices->each->pay();
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/eloquent">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="migrations" title="Database Migrations" icon="circle-stack">
<p>Migrations are like version control for your database, allowing your team to define and share your application's database schema definition:</p>
<pre><x-torchlight-code language="php">
public function up(): void
{
Schema::create('flights', function (Blueprint $table) {
$table->uuid()->primary();
$table->foreignUuid('airline_id')->constrained();
$table->string('name');
$table->timestamps();
});
}
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/migrations">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="validation" title="Validation" icon="check-badge">
<p>Laravel has over 90 powerful, built-in validation rules and, using Laravel Precognition, can provide live validation on your frontend:</p>
<pre><x-torchlight-code language="php">
public function update(Request $request)
{
$validated = $request->validate([// [tl! focus:start]
'email' => 'required|email|unique:users',
'password' => Password::required()->min(8)->uncompromised(),
]);// [tl! focus:end]
$request->user()->update($validated);
}
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/validation">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="notifications" title="Notifications & Mail" icon="bell-alert">
<p>Use Laravel to quickly send beautifully styled notifications to your users via email, Slack, SMS, in-app, and more:</p>
<pre><x-torchlight-code language="bash">
php artisan make:notification InvoicePaid
</x-torchlight-code></pre>
<p>Once you have generated a notification, you can easily send the message to one of your application's users:</p>
<pre><x-torchlight-code language="php">
$user->notify(new InvoicePaid($invoice));
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/notifications">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="storage" title="File Storage" icon="archive-box">
<p>Laravel provides a robust filesystem abstraction layer, providing a single, unified API for interacting with local filesystems and cloud based filesystems like Amazon S3:</p>
<pre><x-torchlight-code language="php">
$path = $request->file('avatar')->store('s3');
</x-torchlight-code></pre>
<p>Regardless of where your files are stored, interact with them using Laravel's simple, elegant syntax:</p>
<pre><x-torchlight-code language="php">
$content = Storage::get('photo.jpg');
Storage::put('photo.jpg', $content);
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/filesystem">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="queues" title="Job Queues" icon="queue-list">
<p>Laravel lets you to offload slow jobs to a background queue, keeping your web requests snappy:</p>
<pre><x-torchlight-code language="php">
$podcast = Podcast::create(/* ... */);
ProcessPodcast::dispatch($podcast)->onQueue('podcasts');// [tl! focus]
</x-torchlight-code></pre>
<p>You can run as many queue workers as you need to handle your workload:</p>
<pre><x-torchlight-code language="bash">
php artisan queue:work redis --queue=podcasts
</x-torchlight-code></pre>
<p>For more visibility and control over your queues, <a href="https://laravel.com/docs/horizon">Laravel Horizon</a> provides a beautiful dashboard and code-driven configuration for your Laravel-powered Redis queues.</p>
<p><strong>Learn more</strong></p>
<ul>
<li><a href="https://laravel.com/docs/queues">Job Queues</a></li>
<li><a href="https://laravel.com/docs/horizon">Laravel Horizon</a></li>
</ul>
</x-tabs.tab>
<x-tabs.tab name="scheduling" title="Task Scheduling" icon="clock">
<p>Schedule recurring jobs and commands with an expressive syntax and say goodbye to complicated configuration files:</p>
<pre><x-torchlight-code language="php">
$schedule->job(NotifySubscribers::class)->hourly();
</x-torchlight-code></pre>
<p>Laravel's scheduler can even handle multiple servers and offers built-in overlap prevention:</p>
<pre><x-torchlight-code language="php">
$schedule->job(NotifySubscribers::class)
->dailyAt('9:00')
->onOneServer()
->withoutOverlapping();
</x-torchlight-code></pre>
<p><a href="https://laravel.com/docs/scheduling">Learn more</a></p>
</x-tabs.tab>
<x-tabs.tab name="testing" title="Testing" icon="command-line">
<p>Laravel is built for testing. From unit tests to browser tests, you’ll feel more confident in deploying your application:</p>
<pre><x-torchlight-code language="php">
$user = User::factory()->create();
$this->browse(fn (Browser $browser) => $browser
->visit('/login')
->type('email', $user->email)
->type('password', 'password')
->press('Login')
->assertPathIs('/home')
->assertSee("Welcome {$user->name}")
);
</x-torchlight-code></pre>
| |
227604
|
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
define('LARAVEL_START', microtime(true));
if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) {
require __DIR__.'/../storage/framework/maintenance.php';
}
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
| |
227902
|
<?php
use Illuminate\Foundation\Inspiring;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->describe('Display an inspiring quote');
| |
230086
|
<p>to any links on a page where the user's email address is
known, you may propagate it to the next page. The PHP logging
system will automatically look for this variable and record its
value as the user's e-mail address in the logs. For any users of
PHP1, the above serves the same function as adding
<em>?<!--$email--></em> to the URL used to do in PHP1. It
looks a little bit more complex now, but it is also completely
general allowing you to build your own complex pages.</p>
<p>In the above example you can also see how multiple variables
can be defined right in the GET method data by separating each
with the "&" character. This "&" separated list of
variables must be the last (or only) component of the GET method
data for it to be valid.</p>
<p><a name="selmul" id="selmul"><strong><code>SELECT MULTIPLE</code>
and PHP</strong></a></p>
<p>The SELECT MULTIPLE tag in an HTML construct allows users to
select multiple items from a list. These items are then passed to
the action handler for the form. The problem is that they are all
passed with the same widget name. ie.</p>
<pre>
<SELECT NAME="var" MULTIPLE>
</pre>
<p>Each selected option will arrive at the action handler as:</p>
<p>var=option1<br>
var=option2<br>
var=option3</p>
<p>Each option will overwrite the contents of the previous $var
variable. The solution is to use PHP/FI's non-indexed array
feature. The following should be used:</p>
<pre>
<SELECT NAME="var[]" MULTIPLE>
</pre>
<p>This tells PHP/FI to treat <em>var</em> as an array an each
assignment of a value to var[] adds an item to the array. The
first item becomes $var[0], the next $var[1], etc. The <a href=
"#count">count()</a> function can be used to determine how many
options were selected, and the <a href="#sort">sort()</a>
function can be used to sort the option array if necessary.</p>
<hr>
<a name="imagecoord" id="imagecoord"><strong><code>IMAGE
SUBMIT</code> and PHP</strong></a>
<p>When submitting a form, it is possible to use an image instead
of the standard submit button with a tag like:</p>
<pre>
<input type=image src=image.gif name=sub>
</pre>
<p>When the user clicks somewhere on the image, the accompanying
form will be transmitted to the server with two additional
variables, <em>sub_x</em> and <em>sub_y</em>. These contain the
coordinates of the user click within the image. The experienced
may note that the actual variable names sent by the browser
contains a period rather than an underscore, but PHP converts the
period to an underscore automatically.</p>
<hr>
<h2><a name="gd_support" id="gd_support">GD (a graphics library
for GIF creation) Support in PHP</a></h2>PHP supports the GD
library version 1.2 written by Thomas Boutell. There is no GD
code in PHP itself. If you wish to use the GD support in PHP/FI,
you must obtain the GD library from <a href=
"http://www.boutell.com/gd/http/gd1.3.tar.gz">http://www.boutell.com/gd/http/gd1.3.tar.gz</a>,
install it, and then re-install PHP.
<p>Not all of the GD features are supported by PHP. For a list of
supported functions see the <a href="#funcs">Alphabetical List of
Functions</a>. All the GD functions start with the word,
<em>Image</em>.</p>
<p>More information on the GD package is available at: <a href=
"http://www.boutell.com/gd/">http://www.boutell.com/gd/</a>.</p>
<p><em>GD 1.2 is copyright 1994, 1995 Quest Protein Database
Center, Cold Springs Harbor Labs.</em></p>
<hr>
<h2><a name="virtual_hosts" id="virtual_hosts">PHP/FI and Virtual
Hosts</a></h2>PHP works fine on virtual host setups supported by
some http daemons. The one problem that may occur on such a setup
is related to an inconsistency in the way httpd sets the
SCRIPT_NAME environment variable. Normally it is set to the path
of the current CGI program in relation to the top-level ROOT_DIR
on the httpd server. However, when a virtual domain is used, some
httpd's do not correctly set the SCRIPT_NAME variable as the
relative path from the virtual domain's top level directory as it
should. If the ?config screen gives you an invalid URL error
message, you know that this problem exists on your setup. You
will need to edit the <em>php.h</em> file and set the
VIRTUAL_PATH #define to the path to your <em>php.cgi</em> binary
relative to your top-level directory.
<hr>
<h2><a name="upload" id="upload">File Upload Support</a></h2>
<p>PHP/FI will automatically detect a file upload from a browser
which supports the form-based file upload features as proposed by
<a href="mailto:nebel@xsoft.sd.xerox.com">E. Nebel</a> and
<a href="mailto:masinter@parc.xerox.com">L. Masinter</a> from
Xerox and described in <a href=
"ftp://ds.internic.net/rfc/rfc1867.txt">RFC 1867</a>.</p>
<p>A file upload screen can be built by creating a special form
which looks something like this:</p>
<blockquote>
<pre>
<FORM ENCTYPE="multipart/form-data" ACTION="_URL_" METHOD=POST><br>
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000"><br>
Send this file: <INPUT NAME="userfile" TYPE="file"><br>
<INPUT TYPE="submit" VALUE="Send File"><br>
</FORM>
</pre>
</blockquote>
<p>The _URL_ should point to a php html file. The MAX_FILE_SIZE
hidden field must precede the file input field and its value is
the maximum filesize accepted. The value is in bytes. In this
destination file, the following variables will be defined upon a
successful upload:</p>
<dl>
<dt><strong>$userfile</strong></dt>
<dd>
<p>The temporary filename in which the uploaded file was
stored on the server machine.</p>
</dd>
<dt><strong>$userfile_name</strong></dt>
<dd>
<p>The original name of the file on the sender's system.</p>
</dd>
<dt><strong>$userfile_size</strong></dt>
<dd>
<p>The size of the uploaded file in bytes.</p>
</dd>
<dt><strong>$userfile_type</strong></dt>
<dd>
<p>The mime type of the file if the browser provided this
information. An example would be "image/gif".</p>
</dd>
</dl>
<p>The <em><strong>$userfile</strong></em> basename of the above
variables will match the NAME field in the upload form.</p>
<p>Files will by default be stored in the server's default
temporary directory. This can be changed by setting the
environment variable TMPDIR in the environment in which PHP/FI
runs. Setting it using a PutEnv() call from within a PHP/FI
script will not work though. Alternatively, you may hard-code in
a temporary directory by editing <em>php.h</em> and defining the
<strong>UPLOAD_TMPDIR</strong> variable.</p>
<p>The PHP/FI script which receives the uploaded file should
implement whatever logic is necessary for determining what should
be done with the uploaded file. You can for example use the
$file_size variable to throw away any files that are either too
small or too big. You could use the $file_type variable to throw
away any files that didn't match a certain type criteria.
Whatever the logic, you should either delete the file from the
temporary directory or move it elsewhere.</p>
| |
230091
|
<p>Also inherent to the language is the fact that the type of the
variable determines how certain basic operations will be carried
out. For example:</p>
<pre>
$a = $b + $c;
</pre>
<p>can do a couple of different things. If $b is a number, the
numerical value of $c is added to $b and the sum is stored in $a.
In this case the type of $c is irrelevant. The operation is
guided by the type of the first variable. If $b is a string, then
the string value of $c is appended to $b and the resultant string
is placed in $a. This also leads to some caveats. You should read
the section on <a href="#overload">overloaded operators</a> to
get a better understanding of how to deal with them.</p>
<hr>
<h3><a name="assoc" id="assoc">Associative Arrays</a></h3>
<p>The previous section introduced associative arrays. An
associative array is an array in which the index need not be a
numerically sequential value. The array index can be any number
or string. PHP/FI provides a set of functions to manipulate these
associative arrays. These include, <a href="#next">Next()</a>,
<a href="#prev">Prev()</a>,<a href="#reset">Reset()</a>,<a href=
"#end">End()</a>, and <a href="#key">Key()</a>.</p>
<hr>
<h3><a name="varvars" id="varvars">Variable Variables</a></h3>
<p>Sometimes it is convenient to be able to have variable
variable names. That is, a variable name which can be set and
used dynamically. A normal variable is set with a statement such
as:</p>
<pre>
$a = "hello";
</pre>
<p>A variable variable takes the value of a variable and treats
that as the name of a variable. In the above example,
<strong>hello</strong>, can be used as the name of a variable by
using two dollar signs. ie.</p>
<pre>
$$a = "world";
</pre>
<p>At this point two variables have been defined and stored in
the PHP/FI symbol tree:</p>
<pre>
Variable Name Variable Content
<em>a</em> <em>hello</em>
<em>hello</em> <em>world</em>
</pre>
<p>Therefore, this statement:</p>
<pre>
echo "$a $$a";
</pre>
<p>produces the exact same output as:</p>
<pre>
echo "$a $hello";
</pre>
<p>ie. they both produce: <strong>hello world</strong></p>
<hr>
<h3><a name="lang" id="lang">Language Constructs</a></h3>
<p>As far as language constructs are concerned, the PHP language
is quite simple. The following commands are used to guide the
control flow through a file:</p>
<ul>
<li>if (condition)</li>
<li>else</li>
<li>elseif (condition)</li>
<li>endif</li>
<li>switch(expression)</li>
<li>case expression</li>
<li>default</li>
<li>break</li>
<li>endswitch</li>
<li>while</li>
<li>endwhile</li>
<li>include</li>
<li>exit</li>
</ul>
<p>The syntax of conditions are similar to that of the C
language. <strong>==</strong> tests for equality.
<strong>!=</strong> means not equal. Also supported are:
<strong>></strong>, <strong><</strong>,
<strong>>=</strong>, <strong><=</strong>. Conditional AND
is <strong>&&</strong>, conditional OR is
<strong>||</strong>.</p>
<p>Examples:</p>
<pre>
<?
if($a==5 && $b!=0 );
$c = 100 + $a / $b;
endif;
>
</pre>
<p>The above may also be written in standard C syntax:<br>
In this case, there is no need for a semicolon after the closing
curly brace.</p>
<pre>
<?
if($a==5 && $b!=0) {
$c = 100 + $a / $b;
}
>
</pre>
<p>There is no difference between the two syntaxes. I personally
like to use endif, endswitch and endwhile so I explicitly know
which construct I am ending. However, these ending constructs can
always be replaced with a closing curly brace.</p>
<p>It is important to note that the flow of the language is not
dependent on the organization of the script blocks within the
code. You can start an if expression in one block and have the
end of the expression in another. For example:</p>
<pre>
<?if($a==5 && $b!=0)>
<b>Normal html text</b>
<?endif>
</pre>
<p>In this example it is easy to see why it is sometimes more
desirable to use the <code>endif</code> keyword as opposed to a
closing brace. The above is much more readable than the
following:</p>
<pre>
<?if($a==5 && $b!=0) {>
<b>Normal html text</b>
<? } >
</pre>
<p>Both version are valid and they will do exactly the same
thing.</p>
<hr>
<h3><a name="user_funcs" id="user_funcs">User-Defined
Functions</a></h3>
<p>You may define a function within a PHP script with the
following syntax:</p>
<pre>
<?
Function Test (
echo "This is a test\n";
);
>
</pre>
<p>This function can now be called from anywhere in the script as
long as the call comes after the function definition. A sample
call might be:</p>
<pre>
<?
Test();
>
</pre>
<p>User defined functions like this act exactly like PHP's
internal functions in that you can pass arguments to them and
have them return a value. Here is the syntax for a function
definition of a function which takes 3 arguments and returns the
sum of these arguments:</p>
<pre>
<?
Function Sum $a,$b,$c (
return($a+$b+$c);
);
echo Sum($a,$b,$c);
>
</pre>
<p>The <em>return</em> statement is used to return a value from
the function. Only a single value can be returned using this
mechanism, however, if more values need to be communicated back
and forth between the main code and functions, global variables
can be used. This brings us to the section on the scope of
variables.</p>
<hr>
<h3><a name="scope" id="scope">Scope of Variables</a></h3>
<p>The scope of a variable is the context within which it is
defined. For the most part all PHP/FI variables only have a
single scope. However, within user-defined functions a local
function scope is introduced. Any variable used inside a function
is by default limited to the local function scope. For
example:</p>
<pre>
$a=1; /* global scope */
Function Test (
echo $a; /* reference to local scope variable */
);
Test();
</pre>
<p>This script will not produce any output because the
<em>echo</em> statement refers to a local version of the
<em>$a</em> variable, and it has not been assigned a value within
this scope. You may notice that this is a little bit different
from the C language in that global variables in C are
automatically available to functions unless specifically
overridden by a local definition. This can cause some problems in
that people may inadvertently change a global variable. In PHP/FI
global variables must be declared global inside a function if
they are going to be used in that function. An example:</p>
<pre>
$a=1;
$b=2;
Function Sum $first,$second (
global $a,$b;
| |
230238
|
<orderedlist>
<listitem>
<para>
Obtain the Apache HTTP server from the location listed above,
and unpack it:
</para>
<informalexample>
<screen>
<![CDATA[
tar -xzf httpd-2.x.NN.tar.gz
]]>
</screen>
</informalexample>
</listitem>
<listitem>
<para>
Likewise, obtain and unpack the PHP source:
</para>
<informalexample>
<screen>
<![CDATA[
tar -xzf php-NN.tar.gz
]]>
</screen>
</informalexample>
</listitem>
<listitem>
<para>
Build and install Apache. Consult the Apache install documentation for
more details on building Apache.
</para>
<informalexample>
<screen>
<![CDATA[
cd httpd-2_x_NN
./configure --enable-so
make
make install
]]>
</screen>
</informalexample>
</listitem>
<listitem>
<para>
Now you have Apache 2.x.NN available under /usr/local/apache2,
configured with loadable module support and the standard MPM prefork.
To test the installation use your normal procedure for starting
the Apache server, e.g.:
<informalexample>
<screen>
<![CDATA[
/usr/local/apache2/bin/apachectl start
]]>
</screen>
</informalexample>
and stop the server to go on with the configuration for PHP:
<informalexample>
<screen>
<![CDATA[
/usr/local/apache2/bin/apachectl stop
]]>
</screen>
</informalexample>
</para>
</listitem>
<listitem>
<para>
Now, configure and build PHP. This is where you customize PHP
with various options, like which extensions will be enabled. Run
<command>./configure --help</command> for a list of available options. In our example
we'll do a simple configure with Apache 2 and MySQL support.
</para>
<para>
If you built Apache from source, as described above, the below example will
match your path for <command>apxs</command>, but if you installed Apache some other way, you'll
need to adjust the path to <command>apxs</command> accordingly. Note that some distros may rename
<command>apxs</command> to <command>apxs2</command>.
</para>
<informalexample>
<screen>
<![CDATA[
cd ../php-NN
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-mysql
make
make install
]]>
</screen>
</informalexample>
<para>
If you decide to change your configure options after installation,
you'll need to re-run the <command>configure</command>, <command>make</command>,
and <command>make install</command> steps.
You only need to restart apache for the new module to take effect.
A recompile of Apache is not needed.
</para>
<para>
Note that unless told otherwise, <command>make install</command> will also install
<link xlink:href="&url.php.pear;">PEAR</link>,
various PHP tools such as <link linkend="install.pecl.phpize">phpize</link>,
install the PHP CLI, and more.
</para>
</listitem>
<listitem>
<para>
Setup your <filename>php.ini</filename>.
</para>
<informalexample>
<screen>
<![CDATA[
cp php.ini-development /usr/local/lib/php.ini
]]>
</screen>
</informalexample>
<para>
You may edit your <literal>.ini</literal> file to set PHP options. If you prefer having
<filename>php.ini</filename> in another location,
use <literal>--with-config-file-path=/some/path</literal> in step 5.
</para>
<para>
If you instead choose <filename>php.ini-production</filename>, be certain to read the list
of changes within, as they affect how PHP behaves.
</para>
</listitem>
<listitem>
<para>
Edit your <filename>httpd.conf</filename> to load the PHP module. The path on the right hand
side of the <literal>LoadModule</literal> statement must point to the path of the PHP
module on your system. The <command>make install</command> from above may have already
added this for you, but be sure to check.
</para>
<informalexample>
<para>
For PHP 8:
</para>
<programlisting role="apache-conf">
<![CDATA[
LoadModule php_module modules/libphp.so
]]>
</programlisting>
</informalexample>
<informalexample>
<para>
For PHP 7:
</para>
<programlisting role="apache-conf">
<![CDATA[
LoadModule php7_module modules/libphp7.so
]]>
</programlisting>
</informalexample>
</listitem>
<listitem>
<para>
Tell Apache to parse certain extensions as PHP. For example, let's have
Apache parse <literal>.php</literal> files as PHP. Instead of only using the Apache <literal>AddType</literal>
directive, we want to avoid potentially dangerous uploads and created
files such as <filename>exploit.php.jpg</filename> from being executed as PHP. Using this
example, you could have any extension(s) parse as PHP by simply adding
them. We'll add <literal>.php</literal> to demonstrate.
</para>
<informalexample>
<programlisting role="apache-conf">
<![CDATA[
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
]]>
</programlisting>
</informalexample>
<para>
Or, if we wanted to allow <literal>.php</literal>, <literal>.php2</literal>,
<literal>.php3</literal>, <literal>.php4</literal>, <literal>.php5</literal>,
<literal>.php6</literal>, and <literal>.phtml</literal> files to be
executed as PHP, but nothing else, we'd use this:
</para>
<informalexample>
<programlisting role="apache-conf">
<![CDATA[
<FilesMatch "\.ph(p[2-6]?|tml)$">
SetHandler application/x-httpd-php
</FilesMatch>
]]>
</programlisting>
</informalexample>
<para>
And to allow <literal>.phps</literal> files to be handled by the php source filter, and
displayed as syntax-highlighted source code, use this:
</para>
<informalexample>
<programlisting role="apache-conf">
<![CDATA[
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
]]>
</programlisting>
</informalexample>
<para>
<literal>mod_rewrite</literal> may be used to allow any arbitrary <literal>.php</literal> file to be displayed
as syntax-highlighted source code, without having to rename or copy it
to a <literal>.phps</literal> file:
</para>
<informalexample>
<programlisting role="apache-conf">
<![CDATA[
RewriteEngine On
RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]
]]>
</programlisting>
</informalexample>
<para>
The php source filter should not be enabled on production systems, where
it may expose confidential or otherwise sensitive information embedded in
source code.
</para>
</listitem>
<listitem>
<para>
Use your normal procedure for starting the Apache server, e.g.:
</para>
<informalexample>
<screen>
<![CDATA[
/usr/local/apache2/bin/apachectl start
]]>
</screen>
</informalexample>
<para>OR</para>
<informalexample>
<screen>
<![CDATA[
service httpd restart
]]>
</screen>
</informalexample>
</listitem>
</orderedlist>
<para>
Following the steps above you will have a running Apache2 web server with
support for PHP as a <literal>SAPI</literal> module. Of course, there are
many more configuration options available for Apache and PHP. For more
information type <command>./configure --help</command> in the corresponding
source tree.
</para>
| |
230366
|
<sect1 xml:id="features.file-upload.post-method">
<title>POST method uploads</title>
<simpara>
This feature lets people upload both text and binary files.
With PHP's authentication and file manipulation functions,
you have full control over who is allowed to upload and
what is to be done with the file once it has been uploaded.
</simpara>
<simpara>
PHP is capable of receiving file uploads from any RFC-1867
compliant browser.
</simpara>
<note>
<title>Related Configurations Note</title>
<para>
See also the <link linkend="ini.file-uploads">file_uploads</link>,
<link linkend="ini.upload-max-filesize">upload_max_filesize</link>,
<link linkend="ini.upload-tmp-dir">upload_tmp_dir</link>,
<link linkend="ini.post-max-size">post_max_size</link> and
<link linkend="ini.max-input-time">max_input_time</link> directives
in &php.ini;
</para>
</note>
<para>
PHP also supports PUT-method file uploads as used by
<productname>Netscape Composer</productname> and W3C's
<productname>Amaya</productname> clients. See the <link
linkend="features.file-upload.put-method">PUT Method
Support</link> for more details.
</para>
<para>
<example>
<title>File Upload Form</title>
<para>
A file upload screen can be built by creating a special form which
looks something like this:
</para>
<programlisting role="html">
<![CDATA[
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
]]>
</programlisting>
<para>
The <literal>__URL__</literal> in the above example should be replaced,
and point to a PHP file.
</para>
<para>
The <literal>MAX_FILE_SIZE</literal> hidden field (measured in bytes) must
precede the file input field, and its value is the maximum filesize accepted by PHP.
This form element should always be used as it saves users the trouble of
waiting for a big file being transferred only to find that it was too
large and the transfer failed. Keep in mind: fooling this setting on the
browser side is quite easy, so never rely on files with a greater size
being blocked by this feature. It is merely a convenience feature for
users on the client side of the application. The PHP settings (on the server
side) for maximum-size, however, cannot be fooled.
</para>
</example>
</para>
<note>
<para>
Be sure your file upload form has attribute <literal>enctype="multipart/form-data"</literal>
otherwise the file upload will not work.
</para>
</note>
<para>
The global <varname>$_FILES</varname> will contain all the uploaded file information.
Its contents from the example form is as follows. Note that this assumes the use of
the file upload name <emphasis>userfile</emphasis>, as used in the example
script above. This can be any name.
<variablelist>
<varlistentry>
<term><varname>$_FILES['userfile']['name']</varname></term>
<listitem>
<para>
The original name of the file on the client machine.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>$_FILES['userfile']['type']</varname></term>
<listitem>
<para>
The mime type of the file, if the browser provided this
information. An example would be
<literal>"image/gif"</literal>. This mime type is however
not checked on the PHP side and therefore don't take its value
for granted.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>$_FILES['userfile']['size']</varname></term>
<listitem>
<para>
The size, in bytes, of the uploaded file.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>$_FILES['userfile']['tmp_name']</varname></term>
<listitem>
<para>
The temporary filename of the file in which the uploaded file
was stored on the server.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>$_FILES['userfile']['error']</varname></term>
<listitem>
<para>
The <link linkend="features.file-upload.errors">error code</link>
associated with this file upload.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>$_FILES['userfile']['full_path']</varname></term>
<listitem>
<para>
The full path as submitted by the browser. This value does not always contain a real directory structure, and cannot be trusted.
Available as of PHP 8.1.0.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
<para>
Files will, by default be stored in the server's default temporary
directory, unless another location has been given with the <link
linkend="ini.upload-tmp-dir">upload_tmp_dir</link> directive in
&php.ini;. The server's default directory can
be changed by setting the environment variable
<envar>TMPDIR</envar> in the environment in which PHP runs.
Setting it using <function>putenv</function> from within a PHP
script will not work. This environment variable can also be used
to make sure that other operations are working on uploaded files,
as well.
<example>
<title>Validating file uploads</title>
<para>
See also the function entries for <function>is_uploaded_file</function>
and <function>move_uploaded_file</function> for further information. The
following example will process the file upload that came from a form.
</para>
<programlisting role="php">
<![CDATA[
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
]]>
</programlisting>
</example>
</para>
<simpara>
The PHP script which receives the uploaded file should implement
whatever logic is necessary for determining what should be done
with the uploaded file. You can, for example, use the
<varname>$_FILES['userfile']['size']</varname> variable
to throw away any files that are either too small or too big. You
could use the
<varname>$_FILES['userfile']['type']</varname> variable
to throw away any files that didn't match a certain type criteria, but
use this only as first of a series of checks, because this value
is completely under the control of the client and not checked on the PHP
side.
Also, you could use <varname>$_FILES['userfile']['error']</varname>
and plan your logic according to the <link
linkend="features.file-upload.errors">error codes</link>.
Whatever the logic, you should either delete the file from the
temporary directory or move it elsewhere.
</simpara>
<simpara>
If no file is selected for upload in your form, PHP will return
<varname>$_FILES['userfile']['size']</varname> as 0, and
<varname>$_FILES['userfile']['tmp_name']</varname> as none.
</simpara>
<simpara>
The file will be deleted from the temporary directory at the end
of the request if it has not been moved away or renamed.
</simpara>
| |
230380
|
<sect1 xml:id="functions.anonymous">
<title>Anonymous functions</title>
<simpara>
Anonymous functions, also known as <literal>closures</literal>, allow the
creation of functions which have no specified name. They are most useful as
the value of <type>callable</type>
parameters, but they have many other uses.
</simpara>
<simpara>
Anonymous functions are implemented using the <link linkend="class.closure">
<classname>Closure</classname></link> class.
</simpara>
<example>
<title>Anonymous function example</title>
<programlisting role="php">
<![CDATA[
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>
]]>
</programlisting>
</example>
<simpara>
Closures can also be used as the values of variables; PHP automatically
converts such expressions into instances of the
<classname>Closure</classname> internal class. Assigning a closure to a
variable uses the same syntax as any other assignment, including the
trailing semicolon:
</simpara>
<example>
<title>Anonymous function variable assignment example</title>
<programlisting role="php">
<![CDATA[
<?php
$greet = function($name) {
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
]]>
</programlisting>
</example>
<simpara>
Closures may also inherit variables from the parent scope. Any such
variables must be passed to the <literal>use</literal> language construct.
As of PHP 7.1, these variables must not include &link.superglobals;,
<varname>$this</varname>, or variables with the same name as a parameter.
A return type declaration of the function has to be placed
<emphasis>after</emphasis> the <literal>use</literal> clause.
</simpara>
<example>
<title>Inheriting variables from the parent scope</title>
<programlisting role="php">
<![CDATA[
<?php
$message = 'hello';
// No "use"
$example = function () {
var_dump($message);
};
$example();
// Inherit $message
$example = function () use ($message) {
var_dump($message);
};
$example();
// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
$example();
// Reset message
$message = 'hello';
// Inherit by-reference
$example = function () use (&$message) {
var_dump($message);
};
$example();
// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
$example();
// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
$example("hello");
// Return type declaration comes after the use clause
$example = function () use ($message): string {
return "hello $message";
};
var_dump($example());
?>
]]>
</programlisting>
&example.outputs.similar;
<screen>
<![CDATA[
Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"
string(11) "hello world"
]]>
</screen>
</example>
<para>
As of PHP 8.0.0, the list of scope-inherited variables may include a trailing
comma, which will be ignored.
</para>
<simpara>
Inheriting variables from the parent scope is <emphasis>not</emphasis>
the same as using global variables.
Global variables exist in the global scope, which is the same no
matter what function is executing. The parent scope of a closure is the
function in which the closure was declared (not necessarily the function it
was called from). See the following example:
</simpara>
<example>
<title>Closures and scoping</title>
<programlisting role="php">
<![CDATA[
<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
const PRICE_EGGS = 6.95;
protected $products = array();
public function add($product, $quantity)
{
$this->products[$product] = $quantity;
}
public function getQuantity($product)
{
return isset($this->products[$product]) ? $this->products[$product] :
FALSE;
}
public function getTotal($tax)
{
$total = 0.00;
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
}
$my_cart = new Cart;
// Add some items to the cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);
// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>
]]>
</programlisting>
</example>
<example>
<title>Automatic binding of <literal>$this</literal></title>
<programlisting role="php">
<![CDATA[
<?php
class Test
{
public function testing()
{
return function() {
var_dump($this);
};
}
}
$object = new Test;
$function = $object->testing();
$function();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(Test)#1 (0) {
}
]]>
</screen>
</example>
<para>
When declared in the context of a class, the current class is
automatically bound to it, making <literal>$this</literal> available
inside of the function's scope. If this automatic binding of the current
class is not wanted, then
<link linkend="functions.anonymous-functions.static">static anonymous
functions</link> may be used instead.
</para>
<sect2 xml:id="functions.anonymous-functions.static">
<title>Static anonymous functions</title>
<para>
Anonymous functions may be declared statically. This
prevents them from having the current class automatically bound to
them. Objects may also not be bound to them at runtime.
</para>
<para>
<example>
<title>Attempting to use <literal>$this</literal> inside a static anonymous function</title>
<programlisting role="php">
<![CDATA[
<?php
class Foo
{
function __construct()
{
$func = static function() {
var_dump($this);
};
$func();
}
};
new Foo();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Notice: Undefined variable: this in %s on line %d
NULL
]]>
</screen>
</example>
</para>
<para>
<example>
<title>Attempting to bind an object to a static anonymous function</title>
<programlisting role="php">
<![CDATA[
<?php
$func = static function() {
// function body
};
$func = $func->bindTo(new stdClass);
$func();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Warning: Cannot bind an instance to a static closure in %s on line %d
]]>
</screen>
</example>
</para>
</sect2>
| |
230381
|
<sect2 role="changelog">
&reftitle.changelog;
<para>
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>&Version;</entry>
<entry>&Description;</entry>
</row>
</thead>
<tbody>
<row>
<entry>7.1.0</entry>
<entry>
Anonymous functions may not close over &link.superglobals;,
<varname>$this</varname>, or any variable with the same name as a
parameter.
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</sect2>
<sect2 role="notes">
&reftitle.notes;
<note>
<simpara>
It is possible to use <function>func_num_args</function>,
<function>func_get_arg</function>, and <function>func_get_args</function>
from within a closure.
</simpara>
</note>
</sect2>
</sect1>
<sect1 xml:id="functions.arrow">
<title>Arrow Functions</title>
<simpara>
Arrow functions were introduced in PHP 7.4 as a more concise syntax for
<link linkend="functions.anonymous">anonymous functions</link>.
</simpara>
<simpara>
Both anonymous functions and arrow functions are implemented using the
<link linkend="class.closure"><classname>Closure</classname></link> class.
</simpara>
<simpara>
Arrow functions have the basic form
<code>fn (argument_list) => expr</code>.
</simpara>
<simpara>
Arrow functions support the same features as
<link linkend="functions.anonymous">anonymous functions</link>,
except that using variables from the parent scope is always automatic.
</simpara>
<simpara>
When a variable used in the expression is defined in the parent scope
it will be implicitly captured by-value.
In the following example, the functions <varname>$fn1</varname> and
<varname>$fn2</varname> behave the same way.
</simpara>
<para>
<example>
<title>Arrow functions capture variables by value automatically</title>
<programlisting role="php">
<![CDATA[
<?php
$y = 1;
$fn1 = fn($x) => $x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
return $x + $y;
};
var_export($fn1(3));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
4
]]>
</screen>
</example>
</para>
<simpara>
This also works if the arrow functions are nested:
</simpara>
<para>
<example>
<title>Arrow functions capture variables by value automatically, even when nested</title>
<programlisting role="php">
<![CDATA[
<?php
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
// Outputs 51
var_export($fn(5)(10));
?>
]]>
</programlisting>
</example>
</para>
<simpara>
Similarly to anonymous functions,
the arrow function syntax allows arbitrary function signatures,
including parameter and return types, default values, variadics,
as well as by-reference passing and returning.
All of the following are valid examples of arrow functions:
</simpara>
<para>
<example>
<title>Examples of arrow functions</title>
<programlisting role="php">
<![CDATA[
<?php
fn(array $x) => $x;
static fn($x): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;
?>
]]>
</programlisting>
</example>
</para>
<simpara>
Arrow functions use by-value variable binding.
This is roughly equivalent to performing a <code>use($x)</code> for every
variable <varname>$x</varname> used inside the arrow function.
A by-value binding means that it is not possible to modify any values
from the outer scope.
<link linkend="functions.anonymous">Anonymous functions</link>
can be used instead for by-ref bindings.
</simpara>
<para>
<example>
<title>Values from the outer scope cannot be modified by arrow functions</title>
<programlisting role="php">
<![CDATA[
<?php
$x = 1;
$fn = fn() => $x++; // Has no effect
$fn();
var_export($x); // Outputs 1
?>
]]>
</programlisting>
</example>
</para>
<sect2 role="changelog">
&reftitle.changelog;
<para>
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>&Version;</entry>
<entry>&Description;</entry>
</row>
</thead>
<tbody>
<row>
<entry>7.4.0</entry>
<entry>
Arrow functions became available.
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</sect2>
<sect2 role="notes">
&reftitle.notes;
<note>
<simpara>
It is possible to use <function>func_num_args</function>,
<function>func_get_arg</function>, and <function>func_get_args</function>
from within an arrow function.
</simpara>
</note>
</sect2>
</sect1>
| |
230384
|
<title>Basic syntax</title>
<sect1 xml:id="language.basic-syntax.phptags">
<title>PHP tags</title>
<para>
When PHP parses a file, it looks for opening and closing tags, which are
<literal><?php</literal> and <literal>?></literal> which tell PHP to
start and stop interpreting the code between them. Parsing in this manner
allows PHP to be embedded in all sorts of different documents, as
everything outside of a pair of opening and closing tags is ignored by the
PHP parser.
</para>
<para>
PHP includes a short echo tag <literal><?=</literal> which is a
short-hand to the more verbose <code><?php echo</code>.
</para>
<para>
<example>
<title>PHP Opening and Closing Tags</title>
<programlisting role="php">
<![CDATA[
1. <?php echo 'if you want to serve PHP code in XHTML or XML documents,
use these tags'; ?>
2. You can use the short echo tag to <?= 'print this string' ?>.
It's equivalent to <?php echo 'print this string' ?>.
3. <? echo 'this code is within short tags, but will only work '.
'if short_open_tag is enabled'; ?>
]]>
</programlisting>
</example>
</para>
<para>
Short tags (example three) are available by default but can be disabled
either via the <link linkend="ini.short-open-tag">short_open_tag</link>
&php.ini; configuration file directive, or are disabled by default if
PHP is built with the <option>--disable-short-tags</option> configuration.
</para>
<para>
<note>
<para>
As short tags can be disabled it is recommended to only use the normal
tags (<code><?php ?></code> and <code><?= ?></code>) to
maximise compatibility.
</para>
</note>
</para>
<para>
If a file contains only PHP code, it is preferable to omit the PHP closing tag
at the end of the file. This prevents accidental whitespace or new lines
being added after the PHP closing tag, which may cause unwanted effects
because PHP will start output buffering when there is no intention from
the programmer to send any output at that point in the script.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo "Hello world";
// ... more code
echo "Last statement";
// the script ends here with no PHP closing tag
]]>
</programlisting>
</informalexample>
</para>
</sect1>
<sect1 xml:id="language.basic-syntax.phpmode">
<title>Escaping from HTML</title>
<para>
Everything outside of a pair of opening and closing tags is ignored by the
PHP parser which allows PHP files to have mixed content. This allows PHP
to be embedded in HTML documents, for example to create templates.
<informalexample>
<programlisting role="php">
<![CDATA[
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
]]>
</programlisting>
</informalexample>
This works as expected, because when the PHP interpreter hits the ?> closing
tags, it simply starts outputting whatever it finds (except for the
immediately following newline - see
<link linkend="language.basic-syntax.instruction-separation">instruction separation</link>)
until it hits another opening tag unless in the middle of a conditional
statement in which case the interpreter will determine the outcome of the
conditional before making a decision of what to skip over.
See the next example.
</para>
<para>
Using structures with conditions
<example>
<title>Advanced escaping using conditions</title>
<programlisting role="php">
<![CDATA[
<?php if ($expression == true): ?>
This will show if the expression is true.
<?php else: ?>
Otherwise this will show.
<?php endif; ?>
]]>
</programlisting>
</example>
In this example PHP will skip the blocks where the condition is not met, even
though they are outside of the PHP open/close tags; PHP skips them according
to the condition since the PHP interpreter will jump over blocks contained
within a condition that is not met.
</para>
<para>
For outputting large blocks of text, dropping out of PHP parsing mode is
generally more efficient than sending all of the text through
<function>echo</function> or <function>print</function>.
</para>
<para>
<note>
<para>
If PHP is embeded within XML or XHTML the normal PHP
<code><?php ?></code> must be used to remain compliant
with the standards.
</para>
</note>
</para>
</sect1>
<sect1 xml:id="language.basic-syntax.instruction-separation">
<title>Instruction separation</title>
<para>
As in C or Perl, PHP requires instructions to be terminated
with a semicolon at the end of each statement. The closing tag
of a block of PHP code automatically implies a semicolon; you
do not need to have a semicolon terminating the last line of a
PHP block. The closing tag for the block will include the immediately
trailing newline if one is present.
</para>
<para>
<example>
<title>Example showing the closing tag encompassing the trailing newline</title>
<programlisting role="php">
<![CDATA[
<?php echo "Some text"; ?>
No newline
<?= "But newline now" ?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Some textNo newline
But newline now
]]>
</screen>
</example>
</para>
<para>
Examples of entering and exiting the PHP parser:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo 'This is a test';
?>
<?php echo 'This is a test' ?>
<?php echo 'We omitted the last closing tag';
]]>
</programlisting>
</informalexample>
<note>
<para>
The closing tag of a PHP block at the end of a file is optional,
and in some cases omitting it is helpful when using <function>include</function>
or <function>require</function>, so unwanted whitespace will
not occur at the end of files, and you will still be able to add
headers to the response later. It is also handy if you use output
buffering, and would not like to see added unwanted whitespace
at the end of the parts generated by the included files.
</para>
</note>
</para>
</sect1>
<sect1 xml:id="language.basic-syntax.comments">
<title>Comments</title>
<para>
PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
]]>
</programlisting>
</informalexample>
</para>
<simpara>
The "one-line" comment styles only comment to the end of
the line or the current block of PHP code, whichever comes first.
This means that HTML code after <literal>// ... ?></literal>
or <literal># ... ?></literal> WILL be printed:
?> breaks out of PHP mode and returns to HTML mode, and
<literal>//</literal> or <literal>#</literal> cannot influence that.
</simpara>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<h1>This is an <?php # echo 'simple';?> example</h1>
<p>The header above will say 'This is an example'.</p>
]]>
</programlisting>
</informalexample>
</para>
<simpara>
'C' style comments end at the first <literal>*/</literal> encountered.
Make sure you don't nest 'C' style comments. It is easy to make this
mistake if you are trying to comment out a large block of code.
</simpara>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
/*
echo 'This is a test'; /* This comment will cause a problem */
*/
?>
]]>
</programlisting>
</informalexample>
</para>
</sect1>
| |
230388
|
<sect1 xml:id="language.generators.syntax">
<title>Generator syntax</title>
<para>
A generator function looks just like a normal function, except that instead
of returning a value, a generator &yield;s as many values as it needs to.
Any function containing &yield; is a generator function.
</para>
<para>
When a generator function is called, it returns an object that can be
iterated over. When you iterate over that object (for instance, via a
&foreach; loop), PHP will call the object's iteration methods each time it needs a
value, then saves the state of the generator when the generator yields a
value so that it can be resumed when the next value is required.
</para>
<para>
Once there are no more values to be yielded, then the generator
can simply return, and the calling code continues just as if an array has run
out of values.
</para>
<note>
<para>
A generator can return values, which can be retrieved using
<methodname>Generator::getReturn</methodname>.
</para>
</note>
<sect2 xml:id="control-structures.yield">
<title><command>yield</command> keyword</title>
<para>
The heart of a generator function is the <command>yield</command> keyword.
In its simplest form, a yield statement looks much like a return
statement, except that instead of stopping execution of the function and
returning, yield instead provides a value to the code looping over the
generator and pauses execution of the generator function.
</para>
<example>
<title>A simple example of yielding values</title>
<programlisting role="php">
<![CDATA[
<?php
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
$generator = gen_one_to_three();
foreach ($generator as $value) {
echo "$value\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
1
2
3
]]>
</screen>
</example>
<note>
<para>
Internally, sequential integer keys will be paired with the yielded
values, just as with a non-associative array.
</para>
</note>
<sect3 xml:id="control-structures.yield.associative">
<title>Yielding values with keys</title>
<para>
PHP also supports associative arrays, and generators are no different. In
addition to yielding simple values, as shown above, you can also yield a
key at the same time.
</para>
<para>
The syntax for yielding a key/value pair is very similar to that used to
define an associative array, as shown below.
</para>
<example>
<title>Yielding a key/value pair</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* The input is semi-colon separated fields, with the first
* field being an ID to use as a key.
*/
$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;
function input_parser($input) {
foreach (explode("\n", $input) as $line) {
$fields = explode(';', $line);
$id = array_shift($fields);
yield $id => $fields;
}
}
foreach (input_parser($input) as $id => $fields) {
echo "$id:\n";
echo " $fields[0]\n";
echo " $fields[1]\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
1:
PHP
Likes dollar signs
2:
Python
Likes whitespace
3:
Ruby
Likes blocks
]]>
</screen>
</example>
</sect3>
<sect3 xml:id="control-structures.yield.null">
<title>Yielding null values</title>
<para>
Yield can be called without an argument to yield a &null; value with an
automatic key.
</para>
<example>
<title>Yielding &null;s</title>
<programlisting role="php">
<![CDATA[
<?php
function gen_three_nulls() {
foreach (range(1, 3) as $i) {
yield;
}
}
var_dump(iterator_to_array(gen_three_nulls()));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(3) {
[0]=>
NULL
[1]=>
NULL
[2]=>
NULL
}
]]>
</screen>
</example>
</sect3>
<sect3 xml:id="control-structures.yield.references">
<title>Yielding by reference</title>
<para>
Generator functions are able to yield values by reference as well as by
value. This is done in the same way as
<link linkend="functions.returning-values">returning references from functions</link>:
by prepending an ampersand to the function name.
</para>
<example>
<title>Yielding values by reference</title>
<programlisting role="php">
<![CDATA[
<?php
function &gen_reference() {
$value = 3;
while ($value > 0) {
yield $value;
}
}
/*
* Note that we can change $number within the loop, and
* because the generator is yielding references, $value
* within gen_reference() changes.
*/
foreach (gen_reference() as &$number) {
echo (--$number).'... ';
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
2... 1... 0...
]]>
</screen>
</example>
</sect3>
| |
230418
|
<sect1 xml:id="language.namespaces.importing">
<title>Using namespaces: Aliasing/Importing</title>
<titleabbrev>Aliasing and Importing</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
The ability to refer to an external fully qualified name with an alias, or importing,
is an important feature of namespaces. This is similar to the
ability of unix-based filesystems to create symbolic links to a file or to a directory.
</para>
<para>
PHP can alias(/import) constants, functions, classes, interfaces, traits, enums and namespaces.
</para>
<para>
Aliasing is accomplished with the <literal>use</literal> operator.
Here is an example showing all 5 kinds of importing:
<example>
<title>importing/aliasing with the use operator</title>
<programlisting role="php">
<![CDATA[
<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
// importing a function
use function My\Full\functionName;
// aliasing a function
use function My\Full\functionName as func;
// importing a constant
use const My\Full\CONSTANT;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>
]]>
</programlisting>
</example>
Note that for namespaced names (fully qualified namespace names containing
namespace separator, such as <literal>Foo\Bar</literal> as opposed to global names that
do not, such as <literal>FooBar</literal>), the leading backslash is unnecessary and not
recommended, as import names
must be fully qualified, and are not processed relative to the current namespace.
</para>
<para>
PHP additionally supports a convenience shortcut to place multiple use statements
on the same line
<example>
<title>importing/aliasing with the use operator, multiple use statements combined</title>
<programlisting role="php">
<![CDATA[
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>
]]>
</programlisting>
</example>
</para>
<para>
Importing is performed at compile-time, and so does not affect dynamic class, function
or constant names.
<example>
<title>Importing and dynamic names</title>
<programlisting role="php">
<![CDATA[
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a; // instantiates object of class Another
?>
]]>
</programlisting>
</example>
</para>
<para>
In addition, importing only affects unqualified and qualified names. Fully qualified
names are absolute, and unaffected by imports.
<example>
<title>Importing and fully qualified names</title>
<programlisting role="php">
<![CDATA[
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>
]]>
</programlisting>
</example>
</para>
<sect2 xml:id="language.namespaces.importing.scope">
<title>Scoping rules for importing</title>
<para>
The <literal>use</literal> keyword must be declared in the
outermost scope of a file (the global scope) or inside namespace
declarations. This is because the importing is done at compile
time and not runtime, so it cannot be block scoped. The following
example will show an illegal use of the <literal>use</literal>
keyword:
</para>
<para>
<example>
<title>Illegal importing rule</title>
<programlisting role="php">
<![CDATA[
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish;
// ...
}
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Importing rules are per file basis, meaning included files will
<emphasis>NOT</emphasis> inherit the parent file's importing rules.
</para>
</note>
</sect2>
<sect2 xml:id="language.namespaces.importing.group">
<title>Group <literal>use</literal> declarations</title>
<para>
Classes, functions and constants being imported from
the same &namespace; can be grouped together in a single &use.namespace;
statement.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// is equivalent to the following groupped use declaration
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
]]>
</programlisting>
</informalexample>
</sect2>
</sect1>
<sect1 xml:id="language.namespaces.global">
<title>Global space</title>
<titleabbrev>Global space</titleabbrev>
<?phpdoc print-version-for="namespaces"?>
<para>
Without any namespace definition, all class and function definitions are
placed into the global space - as it was in PHP before namespaces were
supported. Prefixing a name with <literal>\</literal> will specify that
the name is required from the global space even in the context of the
namespace.
<example>
<title>Using global space specification</title>
<programlisting role="php">
<![CDATA[
<?php
namespace A\B\C;
/* This function is A\B\C\fopen */
function fopen() {
/* ... */
$f = \fopen(...); // call global fopen
return $f;
}
?>
]]>
</programlisting>
</example>
</para>
</sect1>
| |
230480
|
<sect2 xml:id="language.types.array.syntax">
<title>Syntax</title>
<sect3 xml:id="language.types.array.syntax.array-func">
<title>Specifying with <function>array</function></title>
<para>
An <type>array</type> can be created using the <function>array</function>
language construct. It takes any number of comma-separated
<literal><replaceable>key</replaceable> => <replaceable>value</replaceable></literal> pairs
as arguments.
</para>
<synopsis>
array(
<optional><replaceable>key</replaceable> => </optional><replaceable>value</replaceable>,
<optional><replaceable>key2</replaceable> => </optional><replaceable>value2</replaceable>,
<optional><replaceable>key3</replaceable> => </optional><replaceable>value3</replaceable>,
...
)</synopsis>
<!-- Do not fix the whitespace for the synopsis end element. A limitation of PhD prevents proper trimming -->
<para>
The comma after the last array element is optional and can be omitted. This is usually done
for single-line arrays, i.e. <literal>array(1, 2)</literal> is preferred over
<literal>array(1, 2, )</literal>. For multi-line arrays on the other hand the trailing comma
is commonly used, as it allows easier addition of new elements at the end.
</para>
<note>
<para>
A short array syntax exists which replaces
<literal>array()</literal> with <literal>[]</literal>.
</para>
</note>
<example>
<title>A simple array</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
]]>
</programlisting>
</example>
<para>
The <replaceable>key</replaceable> can either be an <type>int</type>
or a <type>string</type>. The <replaceable>value</replaceable> can be
of any type.
</para>
<para xml:id="language.types.array.key-casts">
Additionally the following <replaceable>key</replaceable> casts will occur:
<itemizedlist>
<listitem>
<simpara>
<type>String</type>s containing valid decimal <type>int</type>s, unless the number is preceded by a <literal>+</literal> sign, will be cast to the
<type>int</type> type. E.g. the key <literal>"8"</literal> will actually be
stored under <literal>8</literal>. On the other hand <literal>"08"</literal> will
not be cast, as it isn't a valid decimal integer.
</simpara>
</listitem>
<listitem>
<simpara>
<type>Float</type>s are also cast to <type>int</type>s, which means that the
fractional part will be truncated. E.g. the key <literal>8.7</literal> will actually
be stored under <literal>8</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
<type>Bool</type>s are cast to <type>int</type>s, too, i.e. the key
&true; will actually be stored under <literal>1</literal>
and the key &false; under <literal>0</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
<type>Null</type> will be cast to the empty string, i.e. the key
<literal>null</literal> will actually be stored under <literal>""</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
<type>Array</type>s and <type>object</type>s <emphasis>can not</emphasis> be used as keys.
Doing so will result in a warning: <literal>Illegal offset type</literal>.
</simpara>
</listitem>
</itemizedlist>
</para>
<para>
If multiple elements in the array declaration use the same key, only the last one
will be used as all others are overwritten.
</para>
<example>
<title>Type Casting and Overwriting example</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(1) {
[1]=>
string(1) "d"
}
]]>
</screen>
<para>
As all the keys in the above example are cast to <literal>1</literal>, the value will be overwritten
on every new element and the last assigned value <literal>"d"</literal> is the only one left over.
</para>
</example>
<para>
PHP arrays can contain <type>int</type> and <type>string</type> keys at the same time
as PHP does not distinguish between indexed and associative arrays.
</para>
<example>
<title>Mixed <type>int</type> and <type>string</type> keys</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(4) {
["foo"]=>
string(3) "bar"
["bar"]=>
string(3) "foo"
[100]=>
int(-100)
[-100]=>
int(100)
}
]]>
</screen>
</example>
<para>
The <replaceable>key</replaceable> is optional. If it is not specified, PHP will
use the increment of the largest previously used <type>int</type> key.
</para>
<example>
<title>Indexed arrays without key</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(5) "hello"
[3]=>
string(5) "world"
}
]]>
</screen>
</example>
<para>
It is possible to specify the key only for some elements and leave it out for others:
</para>
<example>
<title>Keys not on all elements</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[6]=>
string(1) "c"
[7]=>
string(1) "d"
}
]]>
</screen>
<para>
As you can see the last value <literal>"d"</literal> was assigned the key
<literal>7</literal>. This is because the largest integer key before that
was <literal>6</literal>.
</para>
</example>
| |
230482
|
<sect3 xml:id="language.types.array.syntax.modifying">
<title>Creating/modifying with square bracket syntax</title>
<para>
An existing <type>array</type> can be modified by explicitly setting values
in it.
</para>
<para>
This is done by assigning values to the <type>array</type>, specifying the
key in brackets. The key can also be omitted, resulting in an empty pair of
brackets (<literal>[]</literal>).
</para>
<synopsis>
$arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>;
$arr[] = <replaceable>value</replaceable>;
// <replaceable>key</replaceable> may be an <type>int</type> or <type>string</type>
// <replaceable>value</replaceable> may be any value of any type</synopsis>
<para>
If <varname>$arr</varname> doesn't exist yet or is set to &null; or &false;, it will be created, so this is
also an alternative way to create an <type>array</type>. This practice is
however discouraged because if <varname>$arr</varname> already contains
some value (e.g. <type>string</type> from request variable) then this
value will stay in the place and <literal>[]</literal> may actually stand
for <link linkend="language.types.string.substr">string access
operator</link>. It is always better to initialize a variable by a direct
assignment.
</para>
<note>
<simpara>
As of PHP 7.1.0, applying the empty index operator on a string throws a fatal
error. Formerly, the string was silently converted to an array.
</simpara>
</note>
<note>
<simpara>
As of PHP 8.1.0, creating a new array from &false; value is deprecated.
Creating a new array from &null; and undefined values is still allowed.
</simpara>
</note>
<para>
To change a certain
value, assign a new value to that element using its key. To remove a
key/value pair, call the <function>unset</function> function on it.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
]]>
</programlisting>
</informalexample>
<note>
<para>
As mentioned above, if no key is specified, the maximum of the existing
<type>int</type> indices is taken, and the new key will be that maximum
value plus 1 (but at least 0). If no <type>int</type> indices exist yet, the key will
be <literal>0</literal> (zero).
</para>
<para>
Note that the maximum integer key used for this <emphasis>need not
currently exist in the <type>array</type></emphasis>. It need only have
existed in the <type>array</type> at some time since the last time the
<type>array</type> was re-indexed. The following example illustrates:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);
// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
)
Array
(
[5] => 6
)
Array
(
[0] => 6
[1] => 7
)
]]>
</screen>
</informalexample>
</note>
</sect3>
<sect3 xml:id="language.types.array.syntax.destructuring">
<title>Array destructuring</title>
<para>
Arrays can be destructured using the <literal>[]</literal> (as of PHP 7.1.0) or
<function>list</function> language constructs. These
constructs can be used to destructure an array into distinct variables.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo', 'bar', 'baz'];
[$foo, $bar, $baz] = $source_array;
echo $foo; // prints "foo"
echo $bar; // prints "bar"
echo $baz; // prints "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
Array destructuring can be used in &foreach; to destructure
a multi-dimensional array while iterating over it.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = [
[1, 'John'],
[2, 'Jane'],
];
foreach ($source_array as [$id, $name]) {
// logic here with $id and $name
}
?>
]]>
</programlisting>
</informalexample>
<para>
Array elements will be ignored if the variable is not provided. Array
destructuring always starts at index <literal>0</literal>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[, , $baz] = $source_array;
echo $baz; // prints "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
As of PHP 7.1.0, associative arrays can be destructured too. This also
allows for easier selection of the right element in numerically indexed
arrays as the index can be explicitly specified.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3];
// Assign the element at index 'baz' to the variable $three
['baz' => $three] = $source_array;
echo $three; // prints 3
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[2 => $baz] = $source_array;
echo $baz; // prints "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
Array destructuring can be used for easy swapping of two variables.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 1;
$b = 2;
[$b, $a] = [$a, $b];
echo $a; // prints 2
echo $b; // prints 1
?>
]]>
</programlisting>
</informalexample>
<note>
<para>
The spread operator (<literal>...</literal>) is not supported in assignments.
</para>
</note>
<note>
<para>
Attempting to access an array key which has not been defined is
the same as accessing any other undefined variable:
an <constant>E_WARNING</constant>-level error message
(<constant>E_NOTICE</constant>-level prior to PHP 8.0.0) will be
issued, and the result will be &null;.
</para>
</note>
</sect3>
</sect2><!-- end syntax -->
| |
230527
|
<?xml version="1.0" encoding="utf-8"?>
<sect1 xml:id="language.operators.array">
<title>Array Operators</title>
<titleabbrev>Array</titleabbrev>
<table>
<title>Array Operators</title>
<tgroup cols="3">
<thead>
<row>
<entry>Example</entry>
<entry>Name</entry>
<entry>Result</entry>
</row>
</thead>
<tbody>
<row>
<entry>$a + $b</entry>
<entry>Union</entry>
<entry>Union of <varname>$a</varname> and <varname>$b</varname>.</entry>
</row>
<row>
<entry>$a == $b</entry>
<entry>Equality</entry>
<entry>&true; if <varname>$a</varname> and <varname>$b</varname> have the same key/value pairs.</entry>
</row>
<row>
<entry>$a === $b</entry>
<entry>Identity</entry>
<entry>&true; if <varname>$a</varname> and <varname>$b</varname> have the same key/value pairs in the same
order and of the same types.</entry>
</row>
<row>
<entry>$a != $b</entry>
<entry>Inequality</entry>
<entry>&true; if <varname>$a</varname> is not equal to <varname>$b</varname>.</entry>
</row>
<row>
<entry>$a <> $b</entry>
<entry>Inequality</entry>
<entry>&true; if <varname>$a</varname> is not equal to <varname>$b</varname>.</entry>
</row>
<row>
<entry>$a !== $b</entry>
<entry>Non-identity</entry>
<entry>&true; if <varname>$a</varname> is not identical to <varname>$b</varname>.</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
The <literal>+</literal> operator returns the right-hand array appended
to the left-hand array; for keys that exist in both arrays, the elements
from the left-hand array will be used, and the matching elements from the
right-hand array will be ignored.
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
$a += $b; // Union of $a += $b is $a and $b
echo "Union of \$a += \$b: \n";
var_dump($a);
?>
]]>
</programlisting>
</informalexample>
When executed, this script will print the following:
<screen role="php">
<![CDATA[
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}
Union of $a += $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
]]>
</screen>
</para>
<para>
Elements of arrays are equal for the comparison if they have the
same key and value.
</para>
<para>
<example>
<title>Comparing arrays</title>
<programlisting role="php">
<![CDATA[
<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
]]>
</programlisting>
</example>
</para>
<sect2 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><link linkend="language.types.array">Array type</link></member>
<member><link linkend="ref.array">Array functions</link></member>
</simplelist>
</para>
</sect2>
</sect1>
| |
230555
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.traits" xmlns="http://docbook.org/ns/docbook">
<title>Traits</title>
<para>
PHP implements a way to reuse code called Traits.
</para>
<para>
Traits are a mechanism for code reuse in single inheritance languages such as
PHP. A Trait is intended to reduce some limitations of single inheritance by
enabling a developer to reuse sets of methods freely in several independent
classes living in different class hierarchies. The semantics of the combination
of Traits and classes is defined in a way which reduces complexity, and avoids
the typical problems associated with multiple inheritance and Mixins.
</para>
<para>
A Trait is similar to a class, but only intended to group functionality in a
fine-grained and consistent way. It is not possible to instantiate a Trait on
its own. It is an addition to traditional inheritance and enables horizontal
composition of behavior; that is, the application of class members without
requiring inheritance.
</para>
<example xml:id="language.oop5.traits.basicexample">
<title>Trait example</title>
<programlisting role="php">
<![CDATA[
<?php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
?>
]]>
</programlisting>
</example>
<sect2 xml:id="language.oop5.traits.precedence">
<title>Precedence</title>
<para>
An inherited member from a base class is overridden by a member inserted
by a Trait. The precedence order is that members from the current class
override Trait methods, which in turn override inherited methods.
</para>
<example xml:id="language.oop5.traits.precedence.examples.ex1">
<title>Precedence Order Example</title>
<para>
An inherited method from a base class is overridden by the
method inserted into MyHelloWorld from the SayWorld Trait. The behavior is
the same for methods defined in the MyHelloWorld class. The precedence order
is that methods from the current class override Trait methods, which in
turn override methods from the base class.
</para>
<programlisting role="php">
<![CDATA[
<?php
class Base {
public function sayHello() {
echo 'Hello ';
}
}
trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base {
use SayWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello World!
]]>
</screen>
</example>
<example xml:id="language.oop5.traits.precedence.examples.ex2">
<title>Alternate Precedence Order Example</title>
<programlisting role="php">
<![CDATA[
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
class TheWorldIsNotEnough {
use HelloWorld;
public function sayHello() {
echo 'Hello Universe!';
}
}
$o = new TheWorldIsNotEnough();
$o->sayHello();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello Universe!
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.multiple">
<title>Multiple Traits</title>
<para>
Multiple Traits can be inserted into a class by listing them in the <literal>use</literal>
statement, separated by commas.
</para>
<example xml:id="language.oop5.traits.multiple.ex1">
<title>Multiple Traits Usage</title>
<programlisting role="php">
<![CDATA[
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello World!
]]>
</screen>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.conflict">
<title>Conflict Resolution</title>
<para>
If two Traits insert a method with the same name, a fatal error is produced,
if the conflict is not explicitly resolved.
</para>
<para>
To resolve naming conflicts between Traits used in the same class,
the <literal>insteadof</literal> operator needs to be used to choose exactly
one of the conflicting methods.
</para>
<para>
Since this only allows one to exclude methods, the <literal>as</literal>
operator can be used to add an alias to one of the methods. Note the
<literal>as</literal> operator does not rename the method and it does not
affect any other method either.
</para>
<example xml:id="language.oop5.traits.conflict.ex1">
<title>Conflict Resolution</title>
<para>
In this example, Talker uses the traits A and B.
Since A and B have conflicting methods, it defines to use
the variant of smallTalk from trait B, and the variant of bigTalk from
trait A.
</para>
<para>
The Aliased_Talker makes use of the <literal>as</literal> operator
to be able to use B's bigTalk implementation under an additional alias
<literal>talk</literal>.
</para>
<programlisting role="php">
<![CDATA[
<?php
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.visibility">
<title>Changing Method Visibility</title>
<para>
Using the <literal>as</literal> syntax, one can also adjust the visibility
of the method in the exhibiting class.
</para>
<example xml:id="language.oop5.traits.visibility.ex1">
<title>Changing Method Visibility</title>
<programlisting role="php">
<![CDATA[
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
// Change visibility of sayHello
class MyClass1 {
use HelloWorld { sayHello as protected; }
}
// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
use HelloWorld { sayHello as private myPrivateHello; }
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.composition">
<title>Traits Composed from Traits</title>
<para>
Just as classes can make use of traits, so can other traits. By using one
or more traits in a trait definition, it can be composed partially or
entirely of the members defined in those other traits.
</para>
<example xml:id="language.oop5.traits.composition.ex1">
<title>Traits Composed from Traits</title>
<programlisting role="php">
<![CDATA[
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World!';
}
}
trait HelloWorld {
use Hello, World;
}
class MyHelloWorld {
use HelloWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Hello World!
]]>
</screen>
</example>
</sect2>
| |
230556
|
<sect2 xml:id="language.oop5.traits.abstract">
<title>Abstract Trait Members</title>
<para>
Traits support the use of abstract methods in order to impose requirements
upon the exhibiting class. Public, protected, and private methods are supported.
Prior to PHP 8.0.0, only public and protected abstract methods were supported.
</para>
<caution>
<simpara>
As of PHP 8.0.0, the signature of a concrete method must follow the
<link linkend="language.oop.lsp">signature compatibility rules</link>.
Previously, its signature might be different.
</simpara>
</caution>
<example xml:id="language.oop5.traits.abstract.ex1">
<title>Express Requirements by Abstract Methods</title>
<programlisting role="php">
<![CDATA[
<?php
trait Hello {
public function sayHelloWorld() {
echo 'Hello'.$this->getWorld();
}
abstract public function getWorld();
}
class MyHelloWorld {
private $world;
use Hello;
public function getWorld() {
return $this->world;
}
public function setWorld($val) {
$this->world = $val;
}
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.static">
<title>Static Trait Members</title>
<para>
Traits can define static variables, static methods and static properties.
</para>
<note>
<para>
As of PHP 8.1.0, calling a static method, or accessing a static property directly on a trait is deprecated.
Static methods and properties should only be accessed on a class using the trait.
</para>
</note>
<example xml:id="language.oop5.traits.static.ex1">
<title>Static Variables</title>
<programlisting role="php">
<![CDATA[
<?php
trait Counter {
public function inc() {
static $c = 0;
$c = $c + 1;
echo "$c\n";
}
}
class C1 {
use Counter;
}
class C2 {
use Counter;
}
$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.traits.static.ex2">
<title>Static Methods</title>
<programlisting role="php">
<![CDATA[
<?php
trait StaticExample {
public static function doSomething() {
return 'Doing something';
}
}
class Example {
use StaticExample;
}
Example::doSomething();
?>
]]>
</programlisting>
</example>
<example xml:id="language.oop5.traits.static.ex3">
<title>Static Properties</title>
<programlisting role="php">
<![CDATA[
<?php
trait StaticExample {
public static $static = 'foo';
}
class Example {
use StaticExample;
}
echo Example::$static;
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.properties">
<title>Properties</title>
<para>
Traits can also define properties.
</para>
<example xml:id="language.oop5.traits.properties.example">
<title>Defining Properties</title>
<programlisting role="php">
<![CDATA[
<?php
trait PropertiesTrait {
public $x = 1;
}
class PropertiesExample {
use PropertiesTrait;
}
$example = new PropertiesExample;
$example->x;
?>
]]>
</programlisting>
</example>
<para>
If a trait defines a property then a class can not define a property with
the same name unless it is compatible (same visibility and type,
readonly modifier, and initial value), otherwise a fatal error is issued.
</para>
<example xml:id="language.oop5.traits.properties.conflicts">
<title>Conflict Resolution</title>
<programlisting role="php">
<![CDATA[
<?php
trait PropertiesTrait {
public $same = true;
public $different1 = false;
public bool $different2;
public bool $different3;
}
class PropertiesExample {
use PropertiesTrait;
public $same = true;
public $different1 = true; // Fatal error
public string $different2; // Fatal error
readonly protected bool $different3; // Fatal error
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 xml:id="language.oop5.traits.constants">
<title>&Constants;</title>
<para>
Traits can, as of PHP 8.2.0, also define constants.
</para>
<example xml:id="language.oop5.traits.constants.example">
<title>Defining Constants</title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}
class ConstantsExample {
use ConstantsTrait;
}
$example = new ConstantsExample;
echo $example::FLAG_MUTABLE; // 1
?>
]]>
</programlisting>
</example>
<para>
If a trait defines a constant then a class can not define a constant with
the same name unless it is compatible (same visibility, initial value, and
finality), otherwise a fatal error is issued.
</para>
<example xml:id="language.oop5.traits.constants.conflicts">
<title>Conflict Resolution</title>
<programlisting role="php">
<![CDATA[
<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}
class ConstantsExample {
use ConstantsTrait;
public const FLAG_IMMUTABLE = 5; // Fatal error
}
?>
]]>
</programlisting>
</example>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
230665
|
<?xml version="1.0" encoding="utf-8"?>
<reference xml:id="class.deprecated" role="class" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude">
<title>The Deprecated attribute</title>
<titleabbrev>Deprecated</titleabbrev>
<partintro>
<section xml:id="deprecated.intro">
&reftitle.intro;
<simpara>
This attribute is used to mark functionality as deprecated.
Using deprecated functionality will cause an <constant>E_USER_DEPRECATED</constant> error to be emitted.
</simpara>
</section>
<section xml:id="deprecated.synopsis">
&reftitle.classsynopsis;
<classsynopsis class="class">
<ooclass>
<modifier>final</modifier>
<classname>Deprecated</classname>
</ooclass>
<classsynopsisinfo role="comment">&Properties;</classsynopsisinfo>
<fieldsynopsis>
<modifier>public</modifier>
<modifier>readonly</modifier>
<type class="union"><type>string</type><type>null</type></type>
<varname linkend="deprecated.props.message">message</varname>
</fieldsynopsis>
<fieldsynopsis>
<modifier>public</modifier>
<modifier>readonly</modifier>
<type class="union"><type>string</type><type>null</type></type>
<varname linkend="deprecated.props.since">since</varname>
</fieldsynopsis>
<classsynopsisinfo role="comment">&Methods;</classsynopsisinfo>
<xi:include xpointer="xmlns(db=http://docbook.org/ns/docbook) xpointer(id('class.deprecated')/db:refentry/db:refsect1[@role='description']/descendant::db:constructorsynopsis[@role='Deprecated'])">
<xi:fallback/>
</xi:include>
</classsynopsis>
</section>
<section xml:id="deprecated.props">
&reftitle.properties;
<variablelist>
<varlistentry xml:id="deprecated.props.message">
<term><varname>message</varname></term>
<listitem>
<para>
An optional message explaining the reason for the deprecation and possible replacement functionality.
Will be included in the emitted deprecation message.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="deprecated.props.since">
<term><varname>since</varname></term>
<listitem>
<para>
An optional string indicating since when the functionality is deprecated.
The contents are not validated by PHP and may contain a version number,
a date or any other value that is considered appropriate.
Will be included in the emitted deprecation message.
</para>
<para>
Functionality that is part of PHP will use Major.Minor as the <varname>since</varname> value,
for example <literal>'8.4'</literal>.
</para>
</listitem>
</varlistentry>
</variablelist>
</section>
<section>
&reftitle.examples;
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
#[\Deprecated(message: "use safe_replacement() instead", since: "1.5")]
function unsafe_function()
{
echo "This is unsafe", PHP_EOL;
}
unsafe_function();
?>
]]>
</programlisting>
&example.outputs.84.similar;
<screen>
<![CDATA[
Deprecated: Function unsafe_function() is deprecated since 1.5, use safe_replacement() instead in example.php on line 9
This is unsafe
]]>
</screen>
</informalexample>
</section>
<section xml:id="deprecated.seealso">
&reftitle.seealso;
<simplelist>
<member><link linkend="language.attributes">Attributes overview</link></member>
<member><methodname>ReflectionFunctionAbstract::isDeprecated</methodname></member>
<member><methodname>ReflectionClassConstant::isDeprecated</methodname></member>
<member><constant>E_USER_DEPRECATED</constant></member>
</simplelist>
</section>
</partintro>
&language.predefined.attributes.deprecated.construct;
</reference>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
230752
|
<para>
<variablelist>
<varlistentry xml:id="ini.short-open-tag">
<term>
<parameter>short_open_tag</parameter>
<type>bool</type>
</term>
<listitem>
<para>
Tells PHP whether the short form (<userinput><? ?></userinput>)
of PHP's open tag should be allowed. If you want to use PHP in
combination with XML, you can disable this option in order to
use <userinput><?xml ?></userinput> inline. Otherwise, you
can print it with PHP, for example: <userinput><?php echo '<?xml
version="1.0"?>'; ?></userinput>. Also, if disabled, you must use the
long form of the PHP open tag (<userinput><?php ?></userinput>).
</para>
<note>
<para>
This directive does not affect the shorthand
<userinput><?=</userinput>, which is always available.
</para>
</note>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.precision">
<term>
<parameter>precision</parameter>
<type>int</type>
</term>
<listitem>
<simpara>
The number of significant digits displayed in floating point numbers.
<literal>-1</literal> means that an enhanced algorithm for rounding
such numbers will be used.
</simpara>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.serialize-precision">
<term>
<parameter>serialize_precision</parameter>
<type>int</type>
</term>
<listitem>
<simpara>
The number of significant digits stored while serializing floating point numbers.
<literal>-1</literal> means that an enhanced algorithm for rounding
such numbers will be used.
</simpara>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.expose-php">
<term>
<parameter>expose_php</parameter>
<type>bool</type>
</term>
<listitem>
<para>
Exposes to the world that PHP is installed on the server, which includes the
PHP version within the HTTP header (e.g., X-Powered-By: PHP/5.3.7).
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.disable-functions">
<term>
<parameter>disable_functions</parameter>
<type>string</type>
</term>
<listitem>
<simpara>
This directive allows disables certain functions.
It takes on a comma-delimited list of function names.
As of PHP 8.0.0, disabling a function removes it definition
allowing userland to redefine it.
Prior to PHP 8.0.0, disabling a function just prevent invoking the function.
</simpara>
<simpara>
Only <link linkend="functions.internal">internal functions</link> can
be disabled using this directive.
<link linkend="functions.user-defined">User-defined functions</link>
are unaffected.
</simpara>
<simpara>
This directive must be set in &php.ini;.
It cannot be set in &httpd.conf;.
</simpara>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.disable-classes">
<term>
<parameter>disable_classes</parameter>
<type>string</type>
</term>
<listitem>
<para>
This directive allows disables certain classes.
It takes on a comma-delimited list of class names.
Disabling a class just prevent instantiating the class.
</para>
<para>
Only internal classes can be disabled using this directive.
User-defined classes are unaffected.
</para>
<simpara>
This directive must be set in &php.ini;.
It cannot be set in &httpd.conf;.
</simpara>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.zend.assertions">
<term>
<parameter>zend.assertions</parameter>
<type>int</type>
</term>
<listitem>
<simpara>
When set to <literal>1</literal>, assertion code will be generated and
executed (development mode). When set to <literal>0</literal>,
assertion code will be generated but it will be skipped (not executed)
at runtime. When set to <literal>-1</literal>, assertion code will not
be generated, making the assertions zero-cost (production mode).
</simpara>
<note>
<para>
If a process is started in production mode, <link linkend="ini.zend.assertions">zend.assertions</link>
cannot be changed at runtime, since the code for assertions was not generated.
</para>
<para>
If a process is started in development mode, <link linkend="ini.zend.assertions">zend.assertions</link>
cannot be set to <literal>-1</literal> at runtime.
</para>
</note>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.zend.exception-string-param-max-len">
<term>
<parameter>zend.exception_string_param_max_len</parameter>
<type>int</type>
</term>
<listitem>
<simpara>
The maximum length of string function arguments in stringified stack traces.
Must range between <literal>"0"</literal> and <literal>"1000000"</literal>.
</simpara>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.hard-timeout">
<term>
<parameter>hard_timeout</parameter>
<type>int</type>
</term>
<listitem>
<para>
When the timeout set in <link linkend="ini.max-execution-time">max_execution_time</link>
has been hit, the PHP runtime will tear down resources gracefully. If
something gets stuck while this happens, the hard timeout will tick
for the set amount of seconds. When the hard timeout is hit, PHP will
exit ungracefully. When set to 0, the hard timeout will never activate.
</para>
<para>
When PHP stops from a hard timeout, it will look something like this:
<screen>
<![CDATA[
Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0
]]>
</screen>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.zend.exception-ignore-args">
<term>
<parameter>zend.exception_ignore_args</parameter>
<type>bool</type>
</term>
<listitem>
<para>
Excludes arguments from stack traces generated from exceptions.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.zend.multibyte">
<term>
<parameter>zend.multibyte</parameter>
<type>bool</type>
</term>
<listitem>
<para>
Enables parsing of source files in multibyte encodings. Enabling zend.multibyte
is required to use character encodings like SJIS, BIG5, etc that contain special
characters in multibyte string data. ISO-8859-1 compatible encodings like UTF-8,
EUC, etc do not require this option.
</para>
<para>
Enabling zend.multibyte requires the mbstring extension to be available.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="ini.zend.script-encoding">
<term>
<parameter>zend.script_encoding</parameter>
<type>string</type>
</term>
<listitem>
<para>
This value will be used unless a
<link linkend="control-structures.declare.encoding">declare(encoding=...)</link>
directive appears at the top of the script. When ISO-8859-1 incompatible encoding
is used, both zend.multibyte and zend.script_encoding must be used.
</para>
<para>
Literal strings will be transliterated from zend.script_encoding to
mbstring.internal_encoding, as if
<function>mb_convert_encoding</function> would have been called.
</para>
</listitem>
</varlistentry>
| |
232889
|
<refentry xml:id="function.simdjson-decode" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>simdjson_decode</refname>
<refpurpose>Decodes a JSON string</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>mixed</type><methodname>simdjson_decode</methodname>
<methodparam><type>string</type><parameter>json</parameter></methodparam>
<methodparam choice="opt"><type>bool</type><parameter>associative</parameter><initializer>&false;</initializer></methodparam>
<methodparam choice="opt"><type>int</type><parameter>depth</parameter><initializer>512</initializer></methodparam>
</methodsynopsis>
<para>
Takes a JSON encoded string and converts it into a PHP value.
This uses a faster Simultaneous Instruction, Multiple Data implementation
than <function>json_decode</function> when it is supported by the computer architecture.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<variablelist>
<varlistentry>
<term><parameter>json</parameter></term>
<listitem>
<para>
The <parameter>json</parameter> <type>string</type> being decoded.
</para>
<para>
This function only works with UTF-8 encoded strings.
</para>
<para>
This function parses valid inputs which
<function>json_decode</function> can decode,
provided that they are less than 4 GiB long.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>associative</parameter></term>
<listitem>
<para>
When &true;, JSON objects will be returned as
associative &array;s; when &false;, JSON objects will be returned as &object;s.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>depth</parameter></term>
<listitem>
<para>
Maximum nesting depth of the structure being decoded.
The value must be greater than <literal>0</literal>,
and less than or equal to <literal>2147483647</literal>.
Callers should use reasonably small values,
because larger depths require more buffer space and will
increase the recursion depth, unlike the current <function>json_decode</function> implementation.
</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns the value encoded in <parameter>json</parameter> in appropriate
PHP type. Values <literal>true</literal>, <literal>false</literal> and
<literal>null</literal> are returned as &true;, &false; and &null;
respectively.
</para>
</refsect1>
<refsect1 role="errors">
&reftitle.errors;
<para>
If <parameter>json</parameter> is invalid, a <classname>SimdJsonException</classname> is thrown as of PECL simdjson 2.1.0,
while previously, a <classname>RuntimeException</classname> was thrown.
</para>
<para>
If <parameter>depth</parameter> is outside the allowed range,
a <classname>SimdJsonValueError</classname> is thrown as of PECL simdjson 3.0.0,
while previously, an error of level <constant>E_WARNING</constant> was raised.
</para>
</refsect1>
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title><function>simdjson_decode</function> examples</title>
<programlisting role="php">
<![CDATA[
<?php
$json = '{"a":1,"b":2,"c":3}';
var_dump(simdjson_decode($json));
var_dump(simdjson_decode($json, true));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(stdClass)#1 (3) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
}
array(3) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
}
]]>
</screen>
</example>
<example>
<title>Accessing invalid object properties</title>
<simpara>
Accessing elements within an object that contain characters not
permitted under PHP's naming convention (e.g. the hyphen) can be
accomplished by encapsulating the element name within braces and the apostrophe.
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$json = '{"foo-bar": 12345}';
$obj = simdjson_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
]]>
</programlisting>
</example>
<example>
<title>common mistakes using <function>simdjson_decode</function></title>
<programlisting role="php">
<![CDATA[
<?php
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
simdjson_decode($bad_json); // Throws SimdJsonException
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
simdjson_decode($bad_json); // Throws SimdJsonException
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
simdjson_decode($bad_json); // Throws SimdJsonException
?>
]]>
</programlisting>
</example>
<example>
<title><parameter>depth</parameter> errors</title>
<programlisting role="php">
<![CDATA[
<?php
// Encode some data with a maximum depth of 4
// (array -> array -> array -> string)
$json = json_encode(
[
1 => [
'English' => [
'One',
'January'
],
'French' => [
'Une',
'Janvier'
]
]
]
);
// Show the errors for different depths.
var_dump(simdjson_decode($json, true, 4));
try {
var_dump(simdjson_decode($json, true, 3));
} catch (SimdJsonException $e) {
echo "Caught: ", $e->getMessage(), "\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(1) {
[1]=>
array(2) {
["English"]=>
array(2) {
[0]=>
string(3) "One"
[1]=>
string(7) "January"
}
["French"]=>
array(2) {
[0]=>
string(3) "Une"
[1]=>
string(7) "Janvier"
}
}
}
Caught: The JSON document was too deep (too many nested objects and arrays)
]]>
</screen>
</example>
<example>
<title><function>simdjson_decode</function> of large integers</title>
<programlisting role="php">
<![CDATA[
<?php
$json = '{"number": 12345678901234567890}';
var_dump(simdjson_decode($json));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(stdClass)#1 (1) {
["number"]=>
float(1.2345678901235E+19)
}
]]>
</screen>
</example>
</para>
</refsect1>
<refsect1 role="notes">
&reftitle.notes;
<note>
<para>
The JSON spec is not JavaScript, but a subset of JavaScript.
</para>
</note>
<note>
<para>
In the event of a failure to decode,
a <classname>SimdJsonException</classname> is thrown
and <methodname>SimdJsonException::getCode</methodname> and
<methodname>SimdJsonException::getMessage</methodname> can be used
to determine the exact nature of the error.
</para>
</note>
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>json_encode</function></member>
<member><function>json_decode</function></member>
</simplelist>
</para>
</refsect1>
</refentry>
| |
234373
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="function.array" xmlns="http://docbook.org/ns/docbook">
<refnamediv>
<refname>array</refname>
<refpurpose>Create an array</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>array</type><methodname>array</methodname>
<methodparam rep="repeat"><type>mixed</type><parameter>values</parameter></methodparam>
</methodsynopsis>
<para>
Creates an array. Read the section on the
<link linkend="language.types.array">array type</link> for more information
on what an array is.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>values</parameter></term>
<listitem>
<para>
Syntax "index => values", separated by commas, define index
and values. index may be of type string or integer. When index is
omitted, an integer index is automatically generated, starting
at 0. If index is an integer, next generated index will
be the biggest integer index + 1. Note that when two identical
indices are defined, the last overwrites the first.
</para>
<para>
Having a trailing comma after the last defined array entry, while
unusual, is a valid syntax.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns an array of the parameters. The parameters can be given
an index with the <literal>=></literal> operator. Read the section
on the <link linkend="language.types.array">array type</link> for more
information on what an array is.
</para>
</refsect1>
<refsect1 role="examples">
&reftitle.examples;
<para>
The following example demonstrates how to create a
two-dimensional array, how to specify keys for associative
arrays, and how to skip-and-continue numeric indices in normal
arrays.
<example>
<title><function>array</function> example</title>
<programlisting role="php">
<![CDATA[
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
]]>
</programlisting>
</example>
</para>
<para>
<example>
<title>Automatic index with <function>array</function></title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
?>
]]>
</programlisting>
&example.outputs;
<screen role="php">
<![CDATA[
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 13
[4] => 1
[8] => 1
[9] => 19
)
]]>
</screen>
</example>
</para>
<para>
Note that index '3' is defined twice, and keep its final value of 13.
Index 4 is defined after index 8, and next generated index (value 19)
is 9, since biggest index was 8.
</para>
<para>
This example creates a 1-based array.
<example>
<title>1-based index with <function>array</function></title>
<programlisting role="php">
<![CDATA[
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Array
(
[1] => January
[2] => February
[3] => March
)
]]>
</screen>
</example>
</para>
<para>
As in Perl, you can access a value from the array inside double quotes.
However, with PHP you'll need to enclose your array between curly braces.
<example>
<title>Accessing an array inside double quotes</title>
<programlisting role="php">
<![CDATA[
<?php
$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!
?>
]]>
</programlisting>
</example>
</para>
</refsect1>
<refsect1 role="notes">
&reftitle.notes;
<para>
<note>
<para>
<function>array</function> is a language construct used to
represent literal arrays, and not a regular function.
</para>
</note>
</para>
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>array_pad</function></member>
<member><function>list</function></member>
<member><function>count</function></member>
<member><function>range</function></member>
<member>&foreach;</member>
<member>The <link linkend="language.types.array">array</link> type</member>
</simplelist>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
234433
|
<?xml version="1.0" encoding="utf-8"?>
<refentry xml:id="function.array-is-list" xmlns="http://docbook.org/ns/docbook">
<refnamediv>
<refname>array_is_list</refname>
<refpurpose>Checks whether a given <parameter>array</parameter> is a list</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>bool</type><methodname>array_is_list</methodname>
<methodparam><type>array</type><parameter>array</parameter></methodparam>
</methodsynopsis>
<para>
Determines if the given <parameter>array</parameter> is a list.
An &array; is considered a list if its keys consist of consecutive numbers
from <literal>0</literal> to <literal>count($array)-1</literal>.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>array</parameter></term>
<listitem>
<para>
The &array; being evaluated.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns &true; if <parameter>array</parameter> is a list, &false;
otherwise.
</para>
</refsect1>
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title><function>array_is_list</function> example</title>
<programlisting role="php">
<![CDATA[
<?php
array_is_list([]); // true
array_is_list(['apple', 2, 3]); // true
array_is_list([0 => 'apple', 'orange']); // true
// The array does not start at 0
array_is_list([1 => 'apple', 'orange']); // false
// The keys are not in the correct order
array_is_list([1 => 'apple', 0 => 'orange']); // false
// Non-integer keys
array_is_list([0 => 'apple', 'foo' => 'bar']); // false
// Non-consecutive keys
array_is_list([0 => 'apple', 2 => 'bar']); // false
?>
]]>
</programlisting>
</example>
</para>
</refsect1>
<refsect1 role="notes">
&reftitle.notes;
<note>
<para>
This function returns &true; on empty arrays.
</para>
</note>
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>array_values</function></member>
</simplelist>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
236194
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.mkdir">
<refnamediv>
<refname>mkdir</refname>
<refpurpose>Makes directory</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>bool</type><methodname>mkdir</methodname>
<methodparam><type>string</type><parameter>directory</parameter></methodparam>
<methodparam choice="opt"><type>int</type><parameter>permissions</parameter><initializer>0777</initializer></methodparam>
<methodparam choice="opt"><type>bool</type><parameter>recursive</parameter><initializer>&false;</initializer></methodparam>
<methodparam choice="opt"><type class="union"><type>resource</type><type>null</type></type><parameter>context</parameter><initializer>&null;</initializer></methodparam>
</methodsynopsis>
<para>
Attempts to create the directory specified by <parameter>directory</parameter>.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>directory</parameter></term>
<listitem>
<para>
The directory path.
&tip.fopen-wrapper;
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>permissions</parameter></term>
<listitem>
<para>
The permissions are 0777 by default, which means the widest possible
access. For more information on permissions, read the details
on the <function>chmod</function> page.
</para>
<note>
<para>
<parameter>permissions</parameter> is ignored on Windows.
</para>
</note>
<para>
Note that you probably want to specify the <parameter>permissions</parameter> as an octal number,
which means it should have a leading zero. The <parameter>permissions</parameter> is also modified
by the current umask, which you can change using
<function>umask</function>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>recursive</parameter></term>
<listitem>
<para>
If &true;, then any parent directories to the <parameter>directory</parameter> specified will
also be created, with the same permissions.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>context</parameter></term>
<listitem>
¬e.context-support;
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
&return.success;
</para>
<note>
<para>
If the directory to be created already exists, that is considered an error
and &false; will still be returned. Use <function>is_dir</function> or
<function>file_exists</function> to check if the directory already exists
before trying to create it.
</para>
</note>
</refsect1>
<refsect1 role="errors">
&reftitle.errors;
<para>
Emits an <constant>E_WARNING</constant> level error if the directory
already exists.
</para>
<para>
Emits an <constant>E_WARNING</constant> level error if the relevant
permissions prevent creating the directory.
</para>
</refsect1>
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title><function>mkdir</function> example</title>
<programlisting role="php">
<![CDATA[
<?php
mkdir("/path/to/my/dir", 0700);
?>
]]>
</programlisting>
</example>
</para>
<para>
<example>
<title><function>mkdir</function> using the <parameter>recursive</parameter> parameter</title>
<programlisting role="php">
<![CDATA[
<?php
// Desired directory structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create directories...');
}
// ...
?>
]]>
</programlisting>
</example>
</para>
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>is_dir</function></member>
<member><function>rmdir</function></member>
<member><function>umask</function></member>
</simplelist>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
236213
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.copy">
<refnamediv>
<refname>copy</refname>
<refpurpose>Copies file</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>bool</type><methodname>copy</methodname>
<methodparam><type>string</type><parameter>from</parameter></methodparam>
<methodparam><type>string</type><parameter>to</parameter></methodparam>
<methodparam choice="opt"><type class="union"><type>resource</type><type>null</type></type><parameter>context</parameter><initializer>&null;</initializer></methodparam>
</methodsynopsis>
<para>
Makes a copy of the file <parameter>from</parameter> to
<parameter>to</parameter>.
</para>
<para>
If you wish to move a file, use the <function>rename</function> function.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>from</parameter></term>
<listitem>
<para>
Path to the source file.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>to</parameter></term>
<listitem>
<para>
The destination path. If <parameter>to</parameter> is a URL, the
copy operation may fail if the wrapper does not support overwriting of
existing files.
</para>
<warning>
<para>
If the destination file already exists, it will be overwritten.
</para>
</warning>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>context</parameter></term>
<listitem>
<para>
A valid context resource created with
<function>stream_context_create</function>.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
&return.success;
</para>
</refsect1>
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title><function>copy</function> example</title>
<programlisting role="php">
<![CDATA[
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
]]>
</programlisting>
</example>
</para>
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>move_uploaded_file</function></member>
<member><function>rename</function></member>
<member>The section of the manual about <link
linkend="features.file-upload">handling file uploads</link></member>
</simplelist>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
237116
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<section xml:id="mongodb.tutorial.library" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Using the PHP Library for MongoDB (PHPLIB)</title>
<para>
After the initial extension set-up, we will continue explaining how to get
started with the corresponding userland library to write our first project.
</para>
<section>
<title>Installing the PHP Library with Composer</title>
<para>
The last thing we still need to install to get started on the application
itself, is the PHP library.
</para>
<para>
The library needs to be installed with
<link xlink:href="&url.mongodb.composer;">Composer</link>, a package manager
for PHP. Instructions for installing Composer on various platforms may be
found on its website.
</para>
<para>
Install the library by running:
<programlisting role="shell">
<![CDATA[
$ composer require mongodb/mongodb
]]>
</programlisting>
</para>
<para>
It will output something akin to:
<programlisting role="text">
<![CDATA[
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing mongodb/mongodb (1.0.0)
Downloading: 100%
Writing lock file
Generating autoload files
]]>
</programlisting>
</para>
<para>
Composer will create several files: <code>composer.json</code>,
<code>composer.lock</code>, and a <code>vendor</code> directory that will
contain the library and any other dependencies your project might require.
</para>
</section>
<section>
<title>Using the PHP Library</title>
<para>
In addition to managing your dependencies, Composer will also provide you
with an autoloader (for those dependencies' classes). Ensure that it is
included at the start of your script or in your application's bootstrap
code:
<programlisting role="php">
<![CDATA[
<?php
// This path should point to Composer's autoloader
require 'vendor/autoload.php';
]]>
</programlisting>
</para>
<para>
With this done, you can now use any of the functionality as described in the
<link xlink:href="&url.mongodb.library.docs;">library documentation</link>.
</para>
<para>
If you have used MongoDB drivers in other languages, the library's API
should look familiar. It contains a
<link xlink:href="&url.mongodb.library.apidocs;/class/MongoDBClient/">Client</link>
class for connecting to MongoDB, a
<link xlink:href="&url.mongodb.library.apidocs;/class/MongoDBDatabase/">Database</link>
class for database-level operations (e.g. commands, collection management),
and a
<link xlink:href="&url.mongodb.library.apidocs;/class/MongoDBCollection">Collection</link>
class for collection-level operations (e.g.
<link xlink:href="&url.mongodb.wiki.crud;">CRUD</link> methods, index management).
</para>
<para>
As an example, this is how you insert a document into the
<emphasis>beers</emphasis> collection of the <emphasis>demo</emphasis>
database:
<programlisting role="php">
<![CDATA[
<?php
require 'vendor/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;
$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>
]]>
</programlisting>
</para>
<para>
Since the inserted document did not contain an <code>_id</code> field, the
extension will generate an <classname>MongoDB\BSON\ObjectId</classname> for
the server to use as the <code>_id</code>. This value is also made available
to the caller via the result object returned by the <code>insertOne</code>
method.
</para>
<para>
After insertion, you can query for the data that you have just inserted.
For that, you use the <code>find</code> method, which returns an iterable
cursor:
<programlisting role="php">
<![CDATA[
<?php
require 'vendor/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;
$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
?>
]]>
</programlisting>
</para>
<para>
While it may not be apparent in the examples, BSON documents and arrays are
unserialized as special classes in the library by default. These classes
extend <classname>ArrayObject</classname> for usability and implement the
extension's <interfacename>MongoDB\BSON\Serializable</interfacename> and
<interfacename>MongoDB\BSON\Unserializable</interfacename> interfaces to
ensure that values preserve their type when serialized back into BSON. This
avoids a caveat in the legacy <code>mongo</code> extension where arrays
might turn into documents, and vice versa. See the
<xref linkend="mongodb.persistence"/> specification for more information on
how values are converted between PHP and BSON.
</para>
</section>
</section>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| |
238688
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="function.json-decode" xmlns="http://docbook.org/ns/docbook">
<refnamediv>
<refname>json_decode</refname>
<refpurpose>Decodes a JSON string</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>mixed</type><methodname>json_decode</methodname>
<methodparam><type>string</type><parameter>json</parameter></methodparam>
<methodparam choice="opt"><type class="union"><type>bool</type><type>null</type></type><parameter>associative</parameter><initializer>&null;</initializer></methodparam>
<methodparam choice="opt"><type>int</type><parameter>depth</parameter><initializer>512</initializer></methodparam>
<methodparam choice="opt"><type>int</type><parameter>flags</parameter><initializer>0</initializer></methodparam>
</methodsynopsis>
<para>
Takes a JSON encoded string and converts it into a PHP value.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>json</parameter></term>
<listitem>
<para>
The <parameter>json</parameter> <type>string</type> being decoded.
</para>
<para>
This function only works with UTF-8 encoded strings.
</para>
&json.implementation.superset;
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>associative</parameter></term>
<listitem>
<para>
When &true;, JSON objects will be returned as
associative &array;s; when &false;, JSON objects will be returned as &object;s.
When &null;, JSON objects will be returned as associative &array;s or
&object;s depending on whether <constant>JSON_OBJECT_AS_ARRAY</constant>
is set in the <parameter>flags</parameter>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>depth</parameter></term>
<listitem>
<para>
Maximum nesting depth of the structure being decoded.
The value must be greater than <literal>0</literal>,
and less than or equal to <literal>2147483647</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>flags</parameter></term>
<listitem>
<para>
Bitmask of
<constant>JSON_BIGINT_AS_STRING</constant>,
<constant>JSON_INVALID_UTF8_IGNORE</constant>,
<constant>JSON_INVALID_UTF8_SUBSTITUTE</constant>,
<constant>JSON_OBJECT_AS_ARRAY</constant>,
<constant>JSON_THROW_ON_ERROR</constant>.
The behaviour of these constants is described on the
<link linkend="json.constants">JSON constants</link> page.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns the value encoded in <parameter>json</parameter> as an appropriate
PHP type. Unquoted values <literal>true</literal>, <literal>false</literal>
and <literal>null</literal> are returned as &true;,
&false; and &null; respectively. &null; is returned if the
<parameter>json</parameter> cannot be decoded or if the encoded data is
deeper than the nesting limit.
</para>
</refsect1>
<refsect1 role="errors">
&reftitle.errors;
<para>
If <parameter>depth</parameter> is outside the allowed range,
a <classname>ValueError</classname> is thrown as of PHP 8.0.0,
while previously, an error of level <constant>E_WARNING</constant> was raised.
</para>
</refsect1>
<refsect1 role="changelog">
&reftitle.changelog;
<para>
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>&Version;</entry>
<entry>&Description;</entry>
</row>
</thead>
<tbody>
<row>
<entry>7.3.0</entry>
<entry>
<constant>JSON_THROW_ON_ERROR</constant>
<parameter>flags</parameter> was added.
</entry>
</row>
<row>
<entry>7.2.0</entry>
<entry>
<parameter>associative</parameter> is nullable now.
</entry>
</row>
<row>
<entry>7.2.0</entry>
<entry>
<constant>JSON_INVALID_UTF8_IGNORE</constant>, and
<constant>JSON_INVALID_UTF8_SUBSTITUTE</constant>
<parameter>flags</parameter> were added.
</entry>
</row>
<row>
<entry>7.1.0</entry>
<entry>
An empty JSON key ("") can be encoded to the empty object property
instead of using a key with value <literal>_empty_</literal>.
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</refsect1>
| |
238689
|
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title><function>json_decode</function> examples</title>
<programlisting role="php">
<![CDATA[
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
]]>
</screen>
</example>
<example>
<title>Accessing invalid object properties</title>
<simpara>
Accessing elements within an object that contain characters not
permitted under PHP's naming convention (e.g. the hyphen) can be
accomplished by encapsulating the element name within braces and the apostrophe.
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
]]>
</programlisting>
</example>
<example>
<title>common mistakes using <function>json_decode</function></title>
<programlisting role="php">
<![CDATA[
<?php
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
?>
]]>
</programlisting>
</example>
<example>
<title><parameter>depth</parameter> errors</title>
<programlisting role="php">
<![CDATA[
<?php
// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode(
array(
1 => array(
'English' => array(
'One',
'January'
),
'French' => array(
'Une',
'Janvier'
)
)
)
);
// Show the errors for different depths.
var_dump(json_decode($json, true, 4));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
var_dump(json_decode($json, true, 3));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(1) {
[1]=>
array(2) {
["English"]=>
array(2) {
[0]=>
string(3) "One"
[1]=>
string(7) "January"
}
["French"]=>
array(2) {
[0]=>
string(3) "Une"
[1]=>
string(7) "Janvier"
}
}
}
Last error: No error
NULL
Last error: Maximum stack depth exceeded
]]>
</screen>
</example>
<example>
<title><function>json_decode</function> of large integers</title>
<programlisting role="php">
<![CDATA[
<?php
$json = '{"number": 12345678901234567890}';
var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
object(stdClass)#1 (1) {
["number"]=>
float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
["number"]=>
string(20) "12345678901234567890"
}
]]>
</screen>
</example>
</para>
</refsect1>
<refsect1 role="notes">
&reftitle.notes;
<note>
<para>
The JSON spec is not JavaScript, but a subset of JavaScript.
</para>
</note>
<note>
<para>
In the event of a failure to decode, <function>json_last_error</function>
can be used to determine the exact nature of the error.
</para>
</note>
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>json_encode</function></member>
<member><function>json_last_error</function></member>
<member><function>json_last_error_msg</function></member>
</simplelist>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.