PHP Learning Notes

Source: Internet
Author: User
Tags explode fread http file upload http post image filter imagecopy time and date type null

Organize from brother to learn video

<!--type: Non-type NULL case Sensitive boolean bool boolean numeric integer integer decimal octal hexadecimal floating-point float 1.234 1.2e3 7E-10 When the integral type is too large, it is automatically converted to a floating-point string single-quote double-quote delimiter such as $string = << <edd ...        EDD resource type special variable, which holds a reference variable to the external resource PHP, the type of the variable can be arbitrarily converted, the variable definition does not require explicit type definition, the use of the variable type is determined by the context. Note: $foo = 5 + "Little piggies"; the output is 15 allowable casts have Boolean: (BOOL) (Boolean) Integer: (int) (integer) floating point type: (Flo        at) (double) (real) variable variable: The variable name of a variable can be set and used dynamically, and a mutable variable gets the value of an ordinary variable as its variable name, which is called a variable variable.            such as: $a = "Hello";    $ $a = "world";            Var_dump ($ $a);            echo "$ $a";        Output: String ("World" string (5) "$hello" NOTE: Hyper global variable cannot be made variable variable predefined variable $_server server variable, contains array of header information, path, script location, etc. An array of $_ENV environment variables that contain information about the operating system type, software version, etc. $_cookie httpcookies variable An array of variables passed by HTTP cookies $_get HTT The P get variable, an array of variables passed by the HTTP GET method, $_post the HTTP POST variable, passed to the current script by the HTTP POST method.       $_files http File upload variable, an array of uploaded file items passed through the HTTP POST method $_request the REQUEST variable, which contains all of the $_get,$_post, $COOKIE The content $_session session variable, containing the variables in the current script session array $GLOBALS Global variables, which are made up of all the variables that are defined in the array external variable HTTP Cookies in the form Also the external variable variable is referenced with the $ start variable to destroy unset ($a)//Destroy variable constant definition using define function definition such as: define ("CONSTANT", "he    Llo World ");    Note: Constants that do not precede the $ symbol variable can only be defined with the define definition and access to the current line number of the Magic variable __line__ file once defined and cannot be changed any more __file__ The full path and file name of the file, if contained in a file, the name of the __FUNCTION__ function, returns the name of the __class__ class when the type is defined, returns the name of the class when it is defined, and returns the method that is defined by the __method__ class. When the name operator, expression, statement arithmetic operator +-*/(return always floating-point number) modulo% negation value negation (-) assignment operator self-operator + =-    =%= *=/= Increment decrement operation + +----string operator. . = comparison operator logical operator! (not) && (and) | |  (OR) Xor Bitwise Operators & | ^ << >> execute operator ' PHP attempts to execute the contents of the execution operator (back quotation marks) as a shell command and return its output information (for example, you can assign a variable instead of a simpleto standard output), typically used to perform operating system command error control operator @ when put in front of a PHP expression, any error messages that an expression can produce are ignored NOTE: @ is valid only for expressions, for example, in variables, functions, and Includ E () call, constant, etc. before, but cannot be placed before the definition of a function or class, nor can it be used before a conditional structure expression statement semicolon comment//single line comment # single line comment */Multiline comment */sequential process bar Branch if If...else?          : If...elseif...else switch...case (variable can only be numeric and string type) loop while do...while for (;;)        foreach (array only) keyword break continue return exception handling try{}catch (Exception e) {} Declare statement Usually used for debugging, currently only accept an instruction function built-in function custom functions are defined in PHP with function functions that are global and can be referenced anywhere in the program, where the function can be set anywhere in the program, where it can be placed in another function.                    Inside such as <?php function foo () {echo "This is Foo <br>";                    function bar () {echo "This is bar function <br>";                }} etc ();                function etc () {echo "This is etc functions <br>";           } foo ();     Bar (); ?> Note: In the above example, if the bar () function is called first, can it be run? No! Because the fun () is not executed at this time, bar () has not been defined, can not be called if, according to Foo (), Fun (), bar () in the order of execution?    There will still be errors, because when the call to Fun () will be defined on bar, so call two fun (), will be defined on bar () two times, it will also appear in the definition in summary, rarely in the function definition function, unless you are sure that the outer function is only called once!!!            Pass-through reference pass for function parameter value: & $var If you want the function to modify a variable outside the function, use a reference to pass the default value: The function parameter can set a default value, the default value must be a constant expression Note: If you have more than one parameter when you use the default value for a function parameter, you need to put the default value parameter after any non-default value parameter to return the value just precede the function with the symbol "&" Dynamic Call function PHP allows variable and function with the same name, so , when there are arguments behind the variable, PHP attempts to invoke the same function as the variable value, such as: $functionName = "Strlower" String = "Abgg" $functionName ($string)    ;                The scope of a variable's local scope variable is the function of its own curly braces {}, but does not work in nested curly braces to use outside variables in nested curly braces, use global $var such as                    <?php $ABC = 123;                        function Fun () {global $abc;                    Echo $abc;       ?> only add global to use ABC in fun. Global scope whenever a variable is defined with a global property, the variable can be accessed with a "$GLOBAL [' Variable name ']", regardless of when and where, a variable with a global property usually refers to a variable that is not defined under any condition or structure.            string function int strlen ();            Computes a UTF-8 encoded string in which the length of the individual text is calculated as 3 int Mb_strlen ();            MB_STR (String str[,string encoding]); Before use, you must ensure that the Php_mbstring.dll string substr (String str,int start[, int length]) int Strpos (string hays) is loaded in php.ini            Tack,mixed needle[,int offset]);        Returns the position of the first occurrence in haystack and returns a false array explode (string separator, string str[,int limit] if not found);            String implode (string glue,array pieces);            Glue is the connector used when merging array elements into strings, pieces is the array string iconv (string in_charset,string out_charset,string str) that needs to be merged;            Set character encoding time and date string date (string $format [, int $timestamp]) year y 1999 y 99 months            F January,february,march,april,may,june,july,august,september,october,november,december M 01-12 M Jan-dec Day D 00-31           D Week: Mon-sun N weeks: 1-7 hours H: 00-23 h: 01-12 g,g Small                Time: No preamble 0 I minute: 00-59 s seconds: 00-59 function: Time () returns timestamp mktime () generates a timestamp for the specified date time The specified time must be before 2038 hours ()-mktime () can be used to calculate the legality of the Age checkdate () test date, the parameter is, month, day, year as : Checkdate (4,31,2010)//Detection April 31, 2010 Modify the default time zone of PHP date_default_timezone_set () date_default_timezone_set ("Asi        A/shanghai "); Date_default_timezone_set ("PRC");//PRC the abbreviation of the People's Republic of China uses a subtle calculation of the time Microtime () of a PHP script execution;//returns a timestamp and a subtle number of parameters before returning directly to a            Time value floating-point image (1) Create canvas--resource type--height, Width (2) Draw the image to develop a variety of color rectangles, circles, dots, segments, sectors, words (characters, strings, FreeType), Each image corresponds to a function (3) Output image or save processed picture, (4) Release resource One, draw verification code, chart, install GD library 1, create canvas re Source Imagecreatetruecolor (width, height) Note that when you use the Imagefttext () function to draw a font, you specify the font as the Utf-8 format, otherwise the garbled Imagefttext is written ($re SouRce, $fontsize, $degree, $x, $y, $color, $freetypefont, $string); Second, processing image picture scaling, watermark, electronic album, processing format, GIF PNG JPG xpn, specifically to see if their server installed the corresponding image processing support fonts: FreeType cropping,            Sharpen, zoom, flip, rotate, clear one, create resource gif,jpg,png, Imagecreatefromgif ($filename);            Imagecreatefromjpeg ($filename);            Draw various shapes (circle, Rectangle, segment, text) Two, get picture resources $width = Imagesx ($image);            $height = Imagesy ($image);                $array = getimagesize ($filename); Returns an array of arrays consisting of Width,height,type, index 0 contains the pixel value of the image width, and index 1 contains the pixel value of the image height. Index 2 is a marker of the image type: 1 = gif,2 = jpg,3 = png,4 = swf,5 = psd,6 = bmp,7 = TIFF (Intel byte order), 8 = TIFF (Motorola byte order), 9 = jpc,10 = jp2,11 = jpx,12 = jb2,13 = swc,14 = iff,15 = wbmp,16 = XBM. These tags correspond to the newly added IMAGETYPE constants of PHP 4.3.0.        Index 3 is a text string with the content "height=" yyy "width=" xxx ", which can be used directly with the IMG tag.    Three, transparent processing phg,jpeg transparent color display normal, GIF is not normal imagecolortransparent (); WillA color is defined as a transparent color imagecolorstotal ();        Gets the number of colors in the palette imagecolorsforindex (); Four, the picture of the Crop imagecopyresized () imagecopyresampled () Five, plus watermark text watermark Imagettf            Text (); Picture watermark bool Imagecopy (Resource $DST _im, resource $src _im, int $dst _x, int $dst _y, int $src _x, int $src                _y, int $src _w, int $src _h);         Starts the coordinates in the src_im image from Src_x,src_y, with a width of src_w, and a portion of the height of Src_h copied to the Dst_im and dst_x locations in the dst_y image.  Six, the picture of the rotation imagerotate ();  Rotates resource imagerotate with a given angle (resource $image, float $angle, int $bgd _color [, int $ignore _transparent = 0 ]) Seven, picture flips along the y axis along the x axis thought: Still using the imagecopy () function, reverse copy Picture eight, sharpen Imagecolor            Sforindex ();        Imagecolorst (); Output picture imagegif (, image position)//can save File Imagepng () imagejpeg () Destroy Resource Imagedestroy ($      image); Third, develop the verification code IMAGecreatetruecolor ($width, $height);        Generate Image Resource Imagecolorallocate ($image, Reb);     Generate Color Imagefill ($image, $color); Fill Background imagerectangle ($image, $xletftop, $yletftop, $xrightButtom, $yrightButtom, $color);//Draw the periphery of the rectangular box Imagesetpixe L ($image, $x, $y, $color);  Draw interference pixels Imagechar ($image, $size, $x, $y, $char, $color); Draw characters Imagettftext ($image, $fontsize, $x, $y, $color, $fontface, $text);//Draw the text imageshow () {header of a specific font ("Content        -type:image/gif "), Imagegif ($image)};//output image, can be gif,jpeg,png MD5 encryption and decryption MD5 MD5 ($string) simple MD5 encryption Mcrypt The encapsulation of the commonly used cryptographic algorithms needs to be opened in php.ini Extension=php_mcrypt.dll crypt Cellar, Chapel basement An array of PHP arrays is actually an ordered graph, a diagram that maps values to the KE            The type of Ys three classes: array of numeric arrays array of multidimensional arrays create numeric array 1, $name =array ("Zhang San", "John Doe", "Harry"), and no element of a numeric array is stored with a digital ID key 2, $name [0]= "Zhangsan", $name [1]= "Li", $name [2]= "Wang" associative array 1, $ages =array ("Zhagn" =>32, "li" =            , "Wang" =>34); 2, $ages ["Zhang""]=", $ages ["Li"]= "P", $ages ["Wang"]= "34"; Multidimensional array $familly =array ("Brother" =>array ("Daming", "Xoiao", "DSF"), "sister" =>ar    Ray ("Dsfas", "SD"), "Uncle" =>array ("sad", "DSS", "DSGs", "Dsfs"));            Read Print to use Print_r ($arrayName) add through the assignment can add elements such as: $fruit =array ("Apple", "banana");            One way, $fruit []= "Orange";    Another way, $fruit ["New"]= "Orange"; Delete uses unset (), example, unset ($fruit [0]), so that the Apple element is removed using the Array_push () pressed into the array element using the Array_pop () popup array element of the function    The last element of the array is ejected and returned, and if the array is empty or not an array, null In_array ($STR, $array) is returned;            Traversal array print_r ();            You can use <pre></pre> to achieve the original format output print_r will move the pointer to the far right of the array, using reset () to get the pointer back to the beginning of the foreach ();        You can use the $key=> output key, and when the value is executed, the pointer inside the array automatically points to the first cell, without having to call Reset () before foreach;            for (); The Count function calculates an array of lengths, facilitates looping through arrays sorted sort in-place sort, i.e. does not return any arrays, directly modifies the original array automatically reset keys RSORT reverse order, also in-place sort reset key shuffle random sort used to scramble the array will delete the original function's key name and automatically generate            Array_reverse () Reverses the array to the first dimension only, and if the first dimension has an array, the invariant key name will remain unchanged Array_merge ()            Merges one or more arrays of cells, and the values in an array are appended to the previous array if the joined array has the same key, it will be overwritten in the order in which it appears, followed by an array that overwrites the preceding array array_slice ()        Split fraction Group Array array_slice (array arrayname,int offset[,int length[,bool Preserve_keys]) file FileSystem BaseName ();    Returns the file name in the path Chgrp ();    Change file group chmod ();    Change file mode Chown ();     Change the file owner copy ();   Copy file Delete ();  Delete file dirname ();   Returns the directory name part of the path Fflush ();   Output buffered content to an open file Fgetss ();     Reads a row from the open file and filters the HTML and PHP tag file (); Reads the file into an array file_exists () file exists Fileatime () returns the file's last Access file Filectime () returns the last changed time of the file Filemtime () return     Back to the last modified time of the file Fileowner () returns the file's owner Fileperms () returns the file's permissions filetype () return file type Is_dir ()   Is_executable () Is_file () Is_link () is_readable () Is_uploaded_file () is_writeable () Realpath () returns the absolute path rename () rmdir delete empty Records stat () returns information about the file Umask () changes the file                   File function fopen (); Open a file, <?php $myfile = fopen ("Webdictionary.txt", "R") or Die ("Unable to open file!"                    );                    Echo fread ($myfile, FileSize ("Webdictionary.txt"));                Fclose ($myfile); The?> fopen () function is also used to create files.            It may be a bit confusing, but in PHP, the function used to create the file is the same as the open file.                Fwrite ();                Write the file, the first parameter is the file name, the second is the string to be written ReadFile ();                Reads a file, returns the number of bytes; fread ();            The first parameter of Fread () contains the file name of the file to be read, and the second parameter specifies the maximum number of bytes to be read.                FileSize ();                Returns the file size Fgers ();                Reads a row of fgetc ();                Reads a single character feof ();            Check if it is the end of the file;Fclose ();                 Close file Directory traversal directory mkdir () Opendir () Open a directory resource Readdir () Use Opendir Open Resource Closedir () to close the resource Rewinddir () to return to the beginning of the directory, the first file GD Graph ICS Draw 4 Steps to create an image • Create a background and future operations are based on this background • Draw outlines on images or enter text • Output final graphics • Clear all resources in memory browser and input/output detection The browser version and language of the visitor $_server a special PHP reserved variable that contains all the information provided by the Web server, called an automatic global variable (or Hyper global variable) array key: HT Tp_user_agent Browser version Information Http_accept_language client system language processing form submitted arrays $_post $_get $ _request upload file 1 single file upload 2 file upload one, upload form note Two, PHP configuration file and upload files related options file_uploads= on upload_max_filesize = 2M; maximum no more than system memory Upload_tmp_dir = "" Temporary path to upload files upload       _max_size = 250M must be greater than Upload_max_filesize = 2M three, PHP processing upload data method= "POST"; get Max is 8192K     Form uploads need to use the type of file to suggest adding a hidden form max_file_size, the value is in bytes to ensure that the properties of the file upload form are enctype= "Multipart/form-data" $_files["UserFile" ["Name"] the original name of the client machine file $_files[The MIME type of "UserFile" ["type"] File $_files["UserFile" ["s ize "] File size $_files[" UserFile "[" Tmp_name "] file is uploaded after the server-side storage of temporary file name $_files[" UserFile "[" Error "] and the file upload phase        The error code of the shutdown. After the file is uploaded, the default is stored in the default temp directory of the server, unless Upload_tmp_dir in php.ini is set to a different path.        The default temp directory on the server side can be reset by changing the environment variable tmpdir of the PHP runtime, but it does not work from within the PHP script by running the PUTENV function. BOOL Move_uploaded_file (string filename,string destination) checks and ensures that the file specified by the filename is a valid file (that is, a file uploaded by the post mechanism), which is legal, then moved to Destination, if the file exists, it is overwritten; return false//STEP1//use $_files["filename" ["Error"] to check for errors//if ($_files[' filename ' [' ERROR '] ; 0) {//switch ($_files[' filename '] [' ERROR ']) {//Case 1://exceeds the maximum specified in php.ini        File value//break;          Case 2://    The file size specified in the HTML hidden form is exceeded//Case 3://Only partially uploaded//4:// No files were uploaded//default:////}////}//s      TEP2//Use $_files[' filename ' [' size '] to limit size per byte//STEP3//Use $_files[' filename ' [' type ']        Restriction type MIME type, shaped like image/jpg//list ($DL, $XL) = Explode ("/", $_files[' filename ' [' type ']); For the picture, the GD library can only handle some types of pictures, such as, png,jpd,gif, so use the image Filter//can also use//STEP4//will upload the name of the filename//Is_upload Ed_file (); Determine if the/if (Is_uploaded_file ($_files[' userfile ' [' tmp_name ']) is uploaded via http POST) {//if (Move_uplo        Aded_file ($_files[' userfile ' [' Tmp_name '], "destination")) {//echo "Upload succeeded"; }//}//Rand (START,END);//Can be used to randomize the file name session handler session refers to the user when browsing a website, from entering the site to close the site        This period of time, that is, the user to browse the site spent time. The concept of a session needs to include specific clients, specific server-side, and non-The operation time of the interrupt.        A session where the user and the C server are connected when the session is established with the B user and the C server are two different sessions.            How the session works (1) When a session is first enabled, a unique identifier is stored in a local cookie.            (2) First, using the Session_Start () function, PHP loads the stored session variables from the session repository.            (3) When executing a PHP script, register the session variable by using the Session_register () function.        (4) When the PHP script executes, the non-destroyed session variable is automatically saved in the session library under the local path, which can be specified by the Session.save_path in the php.ini file and can be loaded the next time the page is browsed. The start session session_start () must precede the 

PHP Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.