-
Notifications
You must be signed in to change notification settings - Fork 883
Expand file tree
/
Copy pathvariables.xml
More file actions
1128 lines (1006 loc) · 32.4 KB
/
Copy pathvariables.xml
File metadata and controls
1128 lines (1006 loc) · 32.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<chapter xml:id="language.variables" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Variables</title>
<sect1 xml:id="language.variables.basics">
<title>Basics</title>
<simpara>
Variables in PHP are represented by a dollar sign followed by the
name of the variable. The variable name is case-sensitive.
</simpara>
<para>
Variable names follow the same rules as other labels in PHP. A
valid variable name starts with a letter or underscore, followed
by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thus:
<code>^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$</code>
</para>
<note>
<simpara>
For our purposes here, a letter is a-z, A-Z, and the bytes
from 128 through 255 (<literal>0x80-0xff</literal>).
</simpara>
</note>
<note>
<simpara>
<literal>$this</literal> is a special variable that can't be
assigned.
</simpara>
</note>
&tip.userlandnaming;
<para>
For information on variable related functions, see the
<link linkend="ref.var">Variable Functions Reference</link>.
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
By default, variables are always assigned by value. That is to say,
when you assign an expression to a variable, the entire value of
the original expression is copied into the destination
variable. This means, for instance, that after assigning one
variable's value to another, changing one of those variables will
have no effect on the other. For more information on this kind of
assignment, see the chapter on <link
linkend="language.expressions">Expressions</link>.
</para>
<para>
PHP also offers another way to assign values to variables:
<link linkend="language.references">assign by reference</link>.
This means that the new variable simply references (in other words,
"becomes an alias for" or "points to") the original variable.
Changes to the new variable affect the original, and vice versa.
</para>
<para>
To assign by reference, simply prepend an ampersand (&) to the
beginning of the variable which is being assigned (the source
variable). For instance, the following code snippet outputs '<literal>My
name is Bob</literal>' twice:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = 'Bob'; // Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
One important thing to note is that only named variables may be
assigned by reference.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.
function test()
{
return 25;
}
$bar = &test(); // Invalid.
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
It is not necessary to initialize variables in PHP however it is a very
good practice. Uninitialized variables have a default value of their type depending on the context in which they are used
- booleans default to &false;, integers and floats default to zero, strings (e.g. used in <function>echo</function>) are
set as an empty string and arrays become to an empty array.
</para>
<para>
<example>
<title>Default values of uninitialized variables</title>
<programlisting role="php">
<![CDATA[
<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);
// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");
// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);
// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);
// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);
// Array usage; outputs array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);
// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>
]]>
</programlisting>
</example>
</para>
<para>
Relying on the default value of an uninitialized variable is problematic
in the case of including one file into another which uses the same
variable name. It is also a major <link
linkend="security.globals">security risk</link> with <link
linkend="ini.register-globals">register_globals</link> turned on. <link
linkend="errorfunc.constants.errorlevels.e-notice">E_NOTICE</link> level error is issued in case of
working with uninitialized variables, however not in the case of appending
elements to the uninitialized array. <function>isset</function> language
construct can be used to detect if a variable has been already initialized.
</para>
</sect1>
<sect1 xml:id="language.variables.predefined">
<title>Predefined Variables</title>
<para>
PHP provides a large number of predefined variables to any script
which it runs. Many of these variables, however, cannot be fully
documented as they are dependent upon which server is running, the
version and setup of the server, and other factors. Some of these
variables will not be available when PHP is run on the
<link linkend="features.commandline">command line</link>.
For a listing of these variables, please see the section on
<link linkend="reserved.variables">Reserved Predefined Variables</link>.
</para>
<para>
PHP also provides an additional set of predefined arrays
containing variables from the web server (if applicable), the
environment, and user input. These arrays are rather special
in that they are automatically global - i.e., automatically
available in every scope. For this reason, they are often known as
"superglobals". (There is no mechanism in PHP for
user-defined superglobals.) The superglobals can be found
<link linkend="language.variables.superglobals">here</link>;
however, for a listing of their contents and further discussion on
PHP predefined variables and their natures, please see the section
<link linkend="reserved.variables">Reserved Predefined Variables</link>.
</para>
<note>
<para>
Prior to PHP 5.4, the old way of retrieving information
related to the HTTP request with the <literal>HTTP_*_VARS</literal>
variables instead of superglobals was still possible.
This feature could be disabled as of PHP 5.0.0 with the
<link linkend="ini.register-long-arrays">register_long_arrays</link>
directive.
</para>
</note>
<note>
<title>Variable variables</title>
<para>
Superglobals cannot be used as
<link linkend="language.variables.variable">variable variables</link>
inside functions or class methods.
</para>
</note>
<para>
If certain variables in <link
linkend="ini.variables-order">variables_order</link> are not set, their
appropriate PHP predefined arrays are also left empty.
</para>
</sect1>
<sect1 xml:id="language.variables.scope">
<title>Variable scope</title>
<simpara>
The scope of a variable is the context within which it is defined.
For the most part all PHP variables only have a single scope.
This single scope spans included and required files as well. For
example:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 1;
include 'b.inc';
?>
]]>
</programlisting>
</informalexample>
<simpara>
Here the <varname>$a</varname> variable will be available within
the included <filename>b.inc</filename> script. 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:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
]]>
</programlisting>
</informalexample>
<simpara>
This script will not produce any output because the echo statement
refers to a local version of the <varname>$a</varname> 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 global variables must be
declared global inside a function if they are going to be used in
that function.
</simpara>
<sect2 xml:id="language.variables.scope.global">
<title>The <literal>global</literal> keyword</title>
<simpara>
First, an example use of <literal>global</literal>:
</simpara>
<para>
<example>
<title>Using <literal>global</literal></title>
<programlisting role="php">
<![CDATA[
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
]]>
</programlisting>
</example>
</para>
<simpara>
The above script will output <literal>3</literal>. By declaring
<varname>$a</varname> and <varname>$b</varname> global within the
function, all references to either variable will refer to the
global version. There is no limit to the number of global
variables that can be manipulated by a function.
</simpara>
<simpara>
A second way to access variables from the global scope is to use
the special PHP-defined <varname>$GLOBALS</varname> array. The
previous example can be rewritten as:
</simpara>
<para>
<example>
<title>Using <varname>$GLOBALS</varname> instead of global</title>
<programlisting role="php">
<![CDATA[
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
]]>
</programlisting>
</example>
</para>
<simpara>
The <varname>$GLOBALS</varname> array is an associative array with
the name of the global variable being the key and the contents of
that variable being the value of the array element.
Notice how <varname>$GLOBALS</varname> exists in any scope, this
is because <varname>$GLOBALS</varname> is a <link
linkend="language.variables.superglobals">superglobal</link>.
Here's an example demonstrating the power of superglobals:
</simpara>
<para>
<example>
<title>Example demonstrating superglobals and scope</title>
<programlisting role="php">
<![CDATA[
<?php
function test_superglobal()
{
echo $_POST['name'];
}
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Using <literal>global</literal> keyword outside a function is not an
error. It can be used if the file is included from inside a function.
</para>
</note>
</sect2>
<sect2 xml:id="language.variables.scope.static">
<title>Using <literal>static</literal> variables</title>
<simpara>
Another important feature of variable scoping is the
<emphasis>static</emphasis> variable. A static variable exists
only in a local function scope, but it does not lose its value
when program execution leaves this scope. Consider the following
example:
</simpara>
<para>
<example>
<title>Example demonstrating need for static variables</title>
<programlisting role="php">
<![CDATA[
<?php
function test()
{
$a = 0;
echo $a;
$a++;
}
?>
]]>
</programlisting>
</example>
</para>
<simpara>
This function is quite useless since every time it is called it
sets <varname>$a</varname> to <literal>0</literal> and prints
<literal>0</literal>. The <varname>$a</varname>++ which increments the
variable serves no purpose since as soon as the function exits the
<varname>$a</varname> variable disappears. To make a useful
counting function which will not lose track of the current count,
the <varname>$a</varname> variable is declared static:
</simpara>
<para>
<example>
<title>Example use of static variables</title>
<programlisting role="php">
<![CDATA[
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
]]>
</programlisting>
</example>
</para>
<simpara>
Now, <varname>$a</varname> is initialized only in first call of function
and every time the <literal>test()</literal> function is called it will print the
value of <varname>$a</varname> and increment it.
</simpara>
<simpara>
Static variables also provide one way to deal with recursive
functions. A recursive function is one which calls itself. Care
must be taken when writing a recursive function because it is
possible to make it recurse indefinitely. You must make sure you
have an adequate way of terminating the recursion. The following
simple function recursively counts to 10, using the static
variable <varname>$count</varname> to know when to stop:
</simpara>
<para>
<example>
<title>Static variables with recursive functions</title>
<programlisting role="php">
<![CDATA[
<?php
function test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Static variables may be declared as seen in the examples above.
From PHP 5.6 you can assign values to these variables which are the
result of expressions, but you can't use any function here, what will cause a parse error.
</para>
<para>
<example>
<title>Declaring static variables</title>
<programlisting role="php">
<![CDATA[
<?php
function foo(){
static $int = 0; // correct
static $int = 1+2; // correct (as of PHP 5.6)
static $int = sqrt(121); // wrong (as it is a function)
$int++;
echo $int;
}
?>
]]>
</programlisting>
</example>
</para>
</note>
<note>
<para>
Static declarations are resolved in compile-time.
</para>
</note>
</sect2>
<sect2 xml:id="language.variables.scope.references">
<title>References with <literal>global</literal> and <literal>static</literal> variables</title>
<simpara>
PHP implements the
<link linkend="language.variables.scope.static">static</link> and
<link linkend="language.variables.scope.global">global</link> modifier
for variables in terms of <link linkend="language.references">
references</link>. For example, a true global variable
imported inside a function scope with the <literal>global</literal>
statement actually creates a reference to the global variable. This can
lead to unexpected behaviour which the following example addresses:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
function test_global_ref() {
global $obj;
$obj = &new stdclass;
}
function test_global_noref() {
global $obj;
$obj = new stdclass;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
]]>
</programlisting>
</informalexample>
&example.outputs;
<screen>
NULL
object(stdClass)(0) {
}
</screen>
<simpara>
A similar behaviour applies to the <literal>static</literal> statement.
References are not stored statically:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign a reference to the static variable
$obj = &new stdclass;
}
$obj->property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign the object to the static variable
$obj = new stdclass;
}
$obj->property++;
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
]]>
</programlisting>
</informalexample>
&example.outputs;
<screen>
Static object: NULL
Static object: NULL
Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}
</screen>
<simpara>
This example demonstrates that when assigning a reference to a static
variable, it's not <emphasis>remembered</emphasis> when you call the
<literal>&get_instance_ref()</literal> function a second time.
</simpara>
</sect2>
</sect1>
<sect1 xml:id="language.variables.variable">
<title>Variable variables</title>
<simpara>
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:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 'hello';
?>
]]>
</programlisting>
</informalexample>
<simpara>
A variable variable takes the value of a variable and treats that
as the name of a variable. In the above example,
<emphasis>hello</emphasis>, can be used as the name of a variable
by using two dollar signs. i.e.
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$$a = 'world';
?>
]]>
</programlisting>
</informalexample>
<simpara>
At this point two variables have been defined and stored in the
PHP symbol tree: <varname>$a</varname> with contents "hello" and
<varname>$hello</varname> with contents "world". Therefore, this
statement:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo "$a ${$a}";
?>
]]>
</programlisting>
</informalexample>
<simpara>
produces the exact same output as:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo "$a $hello";
?>
]]>
</programlisting>
</informalexample>
<simpara>
i.e. they both produce: <computeroutput>hello world</computeroutput>.
</simpara>
<simpara>
In order to use variable variables with arrays, you have to
resolve an ambiguity problem. That is, if you write
<varname>$$a[1]</varname> then the parser needs to know if you
meant to use <varname>$a[1]</varname> as a variable, or if you
wanted <varname>$$a</varname> as the variable and then the [1]
index from that variable. The syntax for resolving this ambiguity
is: <varname>${$a[1]}</varname> for the first case and
<varname>${$a}[1]</varname> for the second.
</simpara>
<simpara>
Class properties may also be accessed using variable property names. The
variable property name will be resolved within the scope from which the
call is made. For instance, if you have an expression such as
<varname>$foo->$bar</varname>, then the local scope will be examined for
<varname>$bar</varname> and its value will be used as the name of the
property of <varname>$foo</varname>. This is also true if
<varname>$bar</varname> is an array access.
</simpara>
<caution>
<simpara>
Further dereferencing a variable property that is an array has different
semantics between PHP 5 and PHP 7. The
<link linkend="migration70.incompatible.variable-handling.indirect">PHP 7.0 migration guide</link>
includes further details on the types of expressions that have changed,
and how to place curly braces to avoid ambiguity.
</simpara>
</caution>
<simpara>
Curly braces may also be used, to clearly delimit the property
name. They are most useful when accessing values within a property that
contains an array, when the property name is made of multiple parts,
or when the property name contains characters that are not
otherwise valid (e.g. from <function>json_decode</function>
or <link linkend="book.simplexml">SimpleXML</link>).
</simpara>
<para>
<example>
<title>Variable property example</title>
<programlisting role="php">
<![CDATA[
<?php
class foo {
var $bar = 'I am bar.';
var $arr = array('I am A.', 'I am B.', 'I am C.');
var $r = 'I am r.';
}
$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->{$baz[1]} . "\n";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->{$arr[1]} . "\n";
?>
]]>
</programlisting>
&example.outputs;
<screen>
I am bar.
I am bar.
I am bar.
I am r.
</screen>
</example>
</para>
<warning>
<simpara>
Please note that variable variables cannot be used with PHP's
<link linkend="language.variables.superglobals">Superglobal arrays</link>
within functions or class methods. The variable <literal>$this</literal>
is also a special variable that cannot be referenced dynamically.
</simpara>
</warning>
</sect1>
<sect1 xml:id="language.variables.external">
<title>Variables From External Sources</title>
<sect2 xml:id="language.variables.external.form">
<title>HTML Forms (GET and POST)</title>
<simpara>
When a form is submitted to a PHP script, the information from
that form is automatically made available to the script. There
are few ways to access this information, for example:
</simpara>
<para>
<example>
<title>A simple HTML form</title>
<programlisting role="html">
<![CDATA[
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
]]>
</programlisting>
</example>
</para>
<para>
As of PHP 5.4.0, there are only two ways to access data from your HTML forms.
Currently available methods are listed below:
</para>
<para>
<example>
<title>Accessing data from a simple POST HTML form</title>
<programlisting role="php">
<![CDATA[
<?php
echo $_POST['username'];
echo $_REQUEST['username'];
?>
]]>
</programlisting>
</example>
</para>
<para>
There were some other ways of accessing user input in old PHP versions. These
are listed below. See changelog at the bottom of the page for more details.
<example>
<title>Old methods of accessing user input</title>
<programlisting role="php">
<![CDATA[
<?php
// WATCH OUT: these methods ARE NOT supported anymore.
// Valid ones were described above.
// Using import_request_variables() - this function has been removed in PHP 5.4.0
import_request_variables('p', 'p_');
echo $p_username;
// These long predefined variables were removed in PHP 5.4.0
echo $HTTP_POST_VARS['username'];
// Using register_globals. This feature was removed in PHP 5.4.0
echo $username;
?>
]]>
</programlisting>
</example>
</para>
<para>
Using a GET form is similar except you'll use the appropriate
GET predefined variable instead. GET also applies to the
<literal>QUERY_STRING</literal> (the information after the '?' in a URL). So,
for example, <literal>http://www.example.com/test.php?id=3</literal>
contains GET data which is accessible with <varname>$_GET['id']</varname>.
See also <varname>$_REQUEST</varname>.
</para>
<note>
<para>
Dots and spaces in variable names are converted to underscores. For
example <literal><input name="a.b" /></literal> becomes
<literal>$_REQUEST["a_b"]</literal>.
</para>
</note>
<simpara>
PHP also understands arrays in the context of form variables
(see the <link linkend="faq.html">related faq</link>). You may,
for example, group related variables together, or use this
feature to retrieve values from a multiple select input. For
example, let's post a form to itself and upon submission display
the data:
</simpara>
<para>
<example>
<title>More complex form variables</title>
<programlisting role="php">
<![CDATA[
<?php
if ($_POST) {
echo '<pre>';
echo htmlspecialchars(print_r($_POST, true));
echo '</pre>';
}
?>
<form action="" method="post">
Name: <input type="text" name="personal[name]" /><br />
Email: <input type="text" name="personal[email]" /><br />
Beer: <br />
<select multiple name="beer[]">
<option value="warthog">Warthog</option>
<option value="guinness">Guinness</option>
<option value="stuttgarter">Stuttgarter Schwabenbräu</option>
</select><br />
<input type="submit" value="submit me!" />
</form>
]]>
</programlisting>
</example>
</para>
<note>
<simpara>
If an external variable name begins with a valid array syntax, trailing characters
are silently ignored. For example, <literal><input name="foo[bar]baz"></literal>
becomes <literal>$_REQUEST['foo']['bar']</literal>.
</simpara>
</note>
<sect3 xml:id="language.variables.external.form.submit">
<title>IMAGE SUBMIT variable names</title>
<simpara>
When submitting a form, it is possible to use an image instead
of the standard submit button with a tag like:
</simpara>
<informalexample>
<programlisting role="html">
<![CDATA[
<input type="image" src="image.gif" name="sub" />
]]>
</programlisting>
</informalexample>
<simpara>
When the user clicks somewhere on the image, the accompanying
form will be transmitted to the server with two additional
variables, <varname>sub_x</varname> and <varname>sub_y</varname>.
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.
</simpara>
</sect3>
</sect2>
<sect2 xml:id="language.variables.external.cookies">
<title>HTTP Cookies</title>
<simpara>
PHP transparently supports HTTP cookies as defined by <link
xlink:href="&url.rfc;6265">RFC 6265</link>. Cookies are a
mechanism for storing data in the remote browser and thus
tracking or identifying return users. You can set cookies using
the <function>setcookie</function> function. Cookies are part of
the HTTP header, so the SetCookie function must be called before
any output is sent to the browser. This is the same restriction
as for the <function>header</function> function. Cookie data
is then available in the appropriate cookie data arrays, such
as <varname>$_COOKIE</varname> as well as in <varname>$_REQUEST</varname>.
See the <function>setcookie</function> manual page for more details and
examples.
</simpara>
<simpara>
If you wish to assign multiple values to a single cookie variable, you
may assign it as an array. For example:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>
]]>
</programlisting>
</informalexample>
<simpara>
That will create two separate cookies although <varname>MyCookie</varname> will now
be a single array in your script. If you want to set just one cookie
with multiple values, consider using <function>serialize</function> or
<function>explode</function> on the value first.
</simpara>
<simpara>
Note that a cookie will replace a previous cookie by the same
name in your browser unless the path or domain is different. So,
for a shopping cart application you may want to keep a counter
and pass this along. i.e.
</simpara>
<example>
<title>A <function>setcookie</function> example</title>
<programlisting role="php">
<![CDATA[
<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);