Directory
Web Design
Blog Details for "Php how to"
Php how toPhp how toPhp programming language tips, how to information. Articles
Some useful file functions
2007-07-18 09:35:00 There are some useful file functions in php. Here are some of them:check whether a file exists or notWhen you need to check whether a file (or directory) exists or not you can use the function file_exists() . its prototype is : bool file_exists ( string $filename )The parameter $filename is the path of a file or directory.get the size of a fileYou can use the function filesize() to get the size of a file. its prototype: int filesize ( string $filename )This function gets the filename as its parameter and returns the size of that file.delete a fileRemoving a file is done by using the function unlink() bool unlink ( string $filename [, resource $context] )unlink() tries to delete the file and returns TRUE when successful or FALSE otherwise.move inside a fileYou can get or change the position of the file pointer using functions rewind() , fseek() , and ftell() .rewind() sets the file pointer to the beginning of the file.ftell() returns the position of the file pointer.fseek() ... More About: File , Functions , Useful , Function , Some
Read from a file
2007-06-07 07:05:00 There are some functions in php to read data from a file. Some of these functions are:fgets() , fgetss() , fgetcsv() , readfile() , fpassthru() , file() , fgetc() , fread()fgets() is used for reading a line at a time. its prototype is:string fgets ( resource $handle [, int $length] )the function fgets() returns a string of up to length - 1 bytes read from the file pointed to by handle. Read ing ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.string fgetss ( resource $handle [, int $length [, string $allowable_tags]] )fgetss() is similar to fgets except that fgetss attempts to strip any HTML and PHP tags from the text it reads. You can use the optional third parameter to specify tags which should not be stripped.array fgetcsv ( resource $handle [, int $length [, string $delim... More About: File
Close a file
2007-03-29 14:35:00 When you are done with the file you have opened you need to close it. This is done with the function fclose which is used like that:fclose($fp);The function fclose will return true if closing the file is successful or false otherwise. You generally don't need to test if a file could be closed or not as you were successful to open it before. (You can usually be sure that there won't be a problem with file permissions or disk space for closing a file.) More About: General , File , Close
Write to a file
2007-03-29 14:06:00 Writing to a file in php is not a difficult thing. We simply use the functions fwrite or fputs to write into a file. (fwrite: file write , fputs: file put string)In fact fputs is another name for fwrite. The use of the fwrite function is:fwrite($fp, $data);The parameter $fp is the file pointing variable that is returned by the fopen function. The second parameter is the data to be written to the file that is usually a string. You can use an optional third parameter that is used for limiting the size of bytes written to the file. The prototype for fwrite is:int fwrite ( int fp, string string, [, int length] ) ;If the length parameter is used, the writing process will end whenever the string ends or the limit supplied by length is reached in terms of bytes (whichever comes first).While writing to a file you will generally want to use a format especially when adding records into the file. For example you can separate different records by using a newline character ( ) and separate d... More About: General , Write , File , Functions
Open a file ( fopen )
2007-03-22 07:03:00 While using php you will sometimes need to store data somewhere that you can access later. There are some ways of this (using a database or using a flat file). I will mention about file processing now.First of all you need to open a file to make something with it. You can open a file in different modes. The decisions you need to make are:Open ing the file in Read, Write, Read & Write file modes.Overwrite the existing data or append to the end of file.Choose file type as binary or text if this is important for the system.You may use a combination of these three options. We simply use the fopen() function to open a file.$fp=fopen("$DOCUMENT_ROOT/../data/da tafile.txt","w");This function takes two or three parameters. General ly two parameters are enough. The first parameter is the file name that you want to open. The file name may include the full path if you want. The $DOCUMENT_ROOT variable in this example is an assigned copy of the php built in variable $HTTP_SERVER_VARS['DOCUMENT_R... More About: File , Functions
break, continue, exit
2007-03-08 11:21:00 When you are in a loop, you may want to quit the loop at any time or skip the current iteration and go on the next iteration. For this purposes break and continue statements are used:$i=0;while (1) { $i++; echo $i ; if ($i>=10) break; }This loop may seem to be an infinite loop when you see the while condition but it will quit when $i is 10. the break statement here makes the loop end whatever the situation is. You may use break when there is no need to continue a loop or use it as a way to limit the iterations. Another useful statement is continue which skips the current iteration instead of ending the loop.$i=0;while (1) { $i++; if ($i==7) continue; echo $i ; if ($i>=10) break; }The difference of this example from the first one is that the loop won't echo 7 and skip to the next iteration where $i is 8.The exit statement is used for ending the current php script. For example when you realize that there is an error about user input you may wa... More About: General , Break , Brea , Conti
Iterations (Loops)
2007-03-06 08:01:00 Loops are used to repeat some code in a php program. There are some types of loops in php:while :This type of loop is used to do something as long as a condition is true.while ( loop_condition ) {//things to doecho 'print this line as long as the condition is true' ;//...}In while loops, first the condition is checked and if it is false the loop ends. The program will continue after the end of the loop.for :For loop is a way of practically doing something before and/or after the loop statements are run. For loop is especially used in counter based loops where you need to set an initial value for a counter variable and change it at the end of each cycle checking a condition each time. The general for loop structure:for ( expression1 ; condition ; expression2 )expression3;expression1 is run only once at the beginning of the loop.condition is checked and if it is false the loop ends.expression3 is run at each iteration. this may be a single statement or a code block.expression2 is ru... More About: General , Loops , Tera , Loop
Conditionals
2007-02-27 13:01:00 Like all programming languages php has conditional statements for controlling the flow of the program. You may know these if you already know any other language in C syntax.if statementsif statements are used to run a piece of code when a condition (or a combination of conditions) is true.if ( $exam_result echo 'Your exam result is not good';In this if statement you decide whether the variable $exam_result is less than 50 or not and print a message if it is. You see that the condition is in ( ) brackets followed by the conditional statement. But when you want to run more than one statement for an if condition you should use a code block to separate this part from the remaining of your code.if ( $exam_result echo 'Your exam result is not good' ; echo 'and you should study more to be successful' ;}If you don't make a code block by using { } surrounding your statements in this example, only the first statement will be affected by the condition and the second statement... More About: General , Condition , Condi
Variable value type modifying
2007-02-27 08:41:00 To change the value types of variables in php, there are some functions that are generally used. These are:int intval(mixed var);float doubleval(mixed var);string strval(mixed var);These functions convert the value of the parameter to a type. Forcing the variable value type to int or float may be used for security. If you get user input and use it in your script, you can't know whether the input is something you expect or a piece of code to attack your web site. When you get a parameter as page number for a script that lists records, you should be sure that this input is an integer. A way of doing this is using the intval() function before you continue.$pageno=$_GET['p'];$pageno=intva l($pageno); //be sure that the input is a number// ... More About: Functions , Vari , Aria , Type , Varia
Mixed variable
2007-02-27 08:35:00 You may have seen the word mixed in some function prototypes so far. There is no such a variable type. This is used to indicate that the function parameter may be of more than one variable type. For ex:void foo(mixed var);This function prototype shows us that the parameter variable may be int, string or sth. else. More About: Vari , Aria , Varia , Mixed , Mixe
Variable status
2007-02-26 16:59:00 bool isset(mixed $var)This function tests whether a variable is set or not. It returns true is it exists.void unset(mixed $var)This one makes a variable unset.bool empty ( mixed $var )and this function checks if $var is empty or not. it returns true if $var is empty or has a zero value. More About: Functions , Vari , Tatu , Aria , Status
Testing variable types
2007-02-26 16:43:00 There are functions in php used to test and set the types of variables: gettype() and settype() The prototypes are:string gettype ( mixed $var )bool settype ( mixed &$var, string $type )And there are some other functions that test whether a variable is of some type or not. These are:is_array()is_double() , is_float() , is_real() : all of these are equivalentis_long(), is_int(), is_integer() : all of these are equivalentis_string()is_object()These functions take one argument and return true if the type of the parameter is of the kind that they test. More About: Testing , Functions , Vari , Aria , Type
Other operators
2007-02-19 12:01:00 , (comma) : used to seperate function arguments and lists.new : used when creating new class members.-> : used for accessing class members.[] : used for accessing array elements.=> : used in some array contexts.?: (ternary operator) : condition ? value1 : value2this operator returns value1 if the condition is true and value2 if the condition is false.@ (error suppression): this operator suppresses the possible error of the following statement.`` (execution operator): This operator is composed of two backticks. This operator is used to execute the operand as a command to run at the command line of server. The expression value is the output of the command. More About: Operators , Operator
Bitwise operators
2007-02-19 11:46:00 Bitwise operators are used for changing the bits of a value. They are not used very much in php. Here is a list of them:& (bitwise AND) : bits set in both the operands are set in the result. $x & $y| (bitwise OR ) : bits set in at least one operand is set in the result. $x | $y~ (bitwise NOT) : bits are opposite in the result. ~$x^ (bitwise XOR) : bits that are different are set high in the result. $x ^ $y (left shift) : shift $x left $y bits. $x >> (right shift) : shift $x right $y bits. $x >> $ynote: set means that the value of bit is 1 More About: Operators , Operator , Wise
Logical operators
2007-02-07 10:10:00 Logical operators are used for combining conditions. Logical operators supported in php are:! (NOT) returns true if the operand is false. ex: !$x&& (AND) returns true when both operands are true. ex: $x && $y|| (OR) returns true when at least one operand is true. ex: $x || $yand the same of && but with lower precedence. ex: $x and $yor the same of || but with lower precedence. ex: $x or $y More About: Operators , Operator , Logic , Logical , Logi
Comparison Operators
2007-02-07 09:41:00 Comparison operators are used for comparing variables or values. The result of a comparison is either true or false which are logical values. == (Equals)This operator tests if two values are equal and returns true if they are or false when they are different.This operator may be confused with the assignment operator (=). If you use = instead of == the result will be true unless the resulting value is zero.An example:$x=3;$y=4;if( $x=$y ){...}The condition will be true although these variables are different because the if condition used here is an assignment in fact and the logical result is true because of the assignment result 4. This kind of errors are difficult to find if you're not careful enough. Your compiler gives no error or warning because it assumes you want to use the assignment result as the testing condition.=== (identical)This operator was introduced in PHP version 4. It tests both the value and the type of two operands. It'll will return false when the types are di... More About: Operators , Comparison , Operator , Riso , Compa
PHP hosting
2007-01-31 16:02:00 Once you have decided to make a web site with PHP you'll need a hosting service supporting PHP. You may search the web and find a web host easily but you should care about the features of the hosting service that you need. There are many hosting companies giving php hosting services but as you know they are not all the same. Php language has many versions so you should decide the lowest version you will use. I think php versions 4.3 and later are enough generally. You may prefer free or paid hosting services. There are many free web hosts on the net but they generally have some restrictions. There's no problem if you prefer free hosting when you don't need a high traffic and high capacity hosting service. A simple search on google would take you to some free hosting companies. Another thing you should consider is the database system. There are many different database systems (RDBMS) that you can use. I prefer MySQL with php and glad of using it. Others may be MsSql, Oracle etc... More About: Hosting , Host , Sting
References
2007-01-18 08:55:00 The reference operator & was added to PHP in version 4. Refer ence s are useful when you want to refer to a variable by using a name other than its original one.$x = 3 ;$y = &$x ;The second statement creates a reference for $x named as $y. After now we can access the variable by using its original one or the reference. As we assign a value to one of them, the other has the same value. In fact a reference has not a memory for the value. It only references the original variable.$x = 5 ;$x and $y are both 5 after this statement. The reference operator may remind you pointers in the C language. The function is similar but you can't assign the address of a reference manually. More About: Operators , References , Ferenc
Pre and post increment decrement
2007-01-18 08:32:00 These operators increment/decrement and assign to another value. The order of these two operations differ for pre and post operations.++ is the increment and -- is the decrement operator.$x = 3 ;$y = ++$x ;The second statement has a pre increment operator because ++ is before $x. So after the statement $x and $y are both 4 because $x is first incremented and then assigned to $y.$x = 3 ;$y = $x++ ;This time we have used a post increment operator. In this case first $x is assigned to $y and then $x is incremented so $y is 3 and $x is 4 after this statement.What i mentioned above is also valid for the decrement operator (--) . More About: Post , Operators , Creme
Assignment operators
2006-12-29 07:08:00 The main assignment operator is = which is used to assing the right side value to the left. It doesn't mean 'equal to' as in maths. It means 'set to' . This operator returns the result of the assignment.$x=18;This statement has the value 18 . A better example:$x= ($y=3) + ($z=$y-1) ;This statement assigns 3 to $y, substracts 1 from $y and assigns it to $z and then adds them to assign the result to $x . There are some combined assignment operators too:operator example equivalent+= $x+=$y $x=$x+$y-= $x-=$y $x=$x-$y*= $x*=$y $x=$x*$y/= $x/=$y $x=$x/$y%= $x%=$y $x=$x%$y.= $x.=$y $x=$x.$y More About: Operators , Operator
String Operators
2006-12-27 07:47:00 There is only one string operator in Php (string concatenating operator). For details: http://phphowto.blogspot.com/2006/12/conc atenate-strings.html More About: Operators , Operator , String , Tring
Arithmetic Operators
2006-12-27 07:24:00 Arithmetic Operator s in Php are just like the ones you use in mathematics.+ addition $x + $y- subtraction $x - $y* multiplication $x * $y/ division $x / $y% modulus $x % $yThese operators are binary (they take two operands) but the subtraction (-) operator is also unary when used with negative numbers. The modulus operator returns the remainder of dividing its operands.$mod_result=18 % 4;This statement has the value 2 as a result. If you try to use arithmetic operators with strings php will try to convert the strings to numbers starting from the first character. If there are no digits at the beginning of the string the value of it will be zero.
Constants
2006-12-22 07:02:00 Constants are like variables but their values can't be changed after they are set. Constants are defined like that:define( 'MY_CONSTANT' , 298 );this statement defines a constant named as MY_CONSTANT . you don't need to write the constant names with all capital letters but i can say that this is common (or traditional) for defining constants in some other languages too.while using a constant in the rest of your code you just write its name anywhere that you want its value to be.echo "my constant is: ";echo MY_CONSTANT;you see that we put no $ sign before the constant name. that's because a constant is not a variable. constants will be very useful when you have a constant value in your code that is used many times in the code and you frequently change it. by using a constant you don't need to change every statement that has the value you want to change. you only change the definition of the constant. you may also want to use constants when you want to keep some special values t... More About: General , Ants , Const , Cons
Variable variables
2006-12-19 14:59:00 in php you can use "variable variables" to reference the name of a variable by using another variable. this may remind you pointers if you are familiar with C/C++ languages but actually its not the same. variable variables allow you to change the name of a variable. C and C++ don't support this.$var_name='my_variable';$$var_name=" value"; //equal to: $my_variable="value";in this example $$var_name is equal to $my_variable . the second statement assigns the string "value" to $my_variable . (simply put 'my_variable' instead of $var_name). this way you can change the variable name dynamically and use the same expression$$var_name="value";for accessing different variables. this feature is sometimes very useful. (for ex: when you keep variable names in an array and use them in a loop.) More About: General , Vari , Aria , Variables , Varia
Variables
2006-12-13 07:19:00 variables are data symbols carrying a value. in php variables are defined by using a $ sign before an identifier. identifiers are the names of variables. identifiers can't begin with a digit and may include letters, numbers, underscores and the $ sign. using the $ sign has a special meaning for variables (i won't mention about it now.) the name of a variable is case sensitive and you can't use function names as variable names. unlike the c language, in php you don't have to declare a variable before using it. the variable will be created when you first use it.$myvariable=0;this is a simple assignment to a variable named as 'myvariable'. php supports these data types:integerdoublestringbooleanarrayobje ctdouble is used for real numbers, string is a set of characters, boolean is a logical variable for values true and false, arrays are used for multiple number of variables of the same type and objects are used to store class instances. since php 4 the types NULL, boolean and reso... More About: General , Vari , Aria , Variables , Varia
concatenate strings
2006-12-04 08:46:00 when you need printing more than one strings where there may be variables or other things between them, it would be annoying to write a new statement to echo all the parts. php has a nice way of doing this for you, string concatenatinglet me show you an example:echo "you have " . $msg_num . "messages!" ;the . operator is the string concatenation operator and is very useful for situations like this. ( i left spaces after and before '.' operators to make them more visible. this is not needed in fact. )you could also write the statement above like that without string concatenating :echo "you have $msg_num messages!" ;this will give an output like:you have 3 messages!depending on the variable $msg_num .be careful that you can do this only inside double quotes. if you use a statement like that:echo 'you have $msg_num messages! ' ;you 'll get html output exactly as in the quotes:you have $msg_num messages!there should be a value instead of $msg_num here so we should use double quotes... More About: General , Ring , Rings , Strings , String
access form variables
2006-12-04 08:07:00 An aim of using php for you may be processing html forms. its easy to access form variables in php. i wont write a sample html form code here. i suppose you already have an html form where each input has a name value. There are general 3 ways of accessing form variables in php. Lets suppose that you have an input field in your form named as input_var :$input_var //short style$_POST['input_var'] //middle style$HTTP_POST_VARS['input_var'] //long stylethe short style is valid only if the register_globals configuration is on. since php version 4.2.0 this configuration is off as default. this style is not recommended.middle style is the recommended style that is valid since php version 4.1.0long style was portable in the past but now requires the register_long_arrays configuration.i always use the middle style. it is easy, not confusing and also portable. if you dont want to access your form variable like this everywhere needed in your code then you can just assign it to another vari... More About: General , Vari , Aria , Access , Variables
redirect to another page
2006-11-17 10:03:00 sometimes you may need to redirect your visitors from a web page to another. for example you may have moved your web site or changed the file name. then you can easily redirect to another page from your current page. this is how it's done:<?phpheader('Location: http://www.mynewwebsite.com');?>this code sends http header to your visitor. but be careful about not to give any output before this. because when you output anything to the visitors browser, the headers are sent. so you cant send header again. if you want to redirect to another page dont put any html output or other scripts before redirecting script. even if you write <html> before the script above you won't be able to redirect. More About: Tips , Page , Another , Redirect , Dire
Php comments
2006-11-13 11:53:00 sometimes you may need to add some explanations to your code. you can write comments for that. php engine ignores everything written as comments. there are some styles for comments.C style: this style is a multiline comment type. it comes from the c language./* this is a multiline comment written in C style. php engine will ignore this comment.*/comments like that (multiline - C style) start with /* and end with */ . this kind of comments can't be written nested.C++ style: this is a one line commenting style as used in the C++ language. in this style comments start with //echo "there's a comment after that"; //this is a c++ style commentShell script style: the only difference of this style from the C++ style is that the sign # is used instead of // .echo "there's a comment after that"; # a shell script style commentfor one line commenting styles , the comments end at the end of the line or at the end of the php ending tag (whichever comes first).// this is a comment but ... More About: Comments , Comment , Comm
Php statements
2006-11-11 12:50:00 Php codes are composed of statements. Stat e ments end with a semicolon. Here is a sample statement:echo "this is a statement";This statement prints the string (character array) after echo. The output on the page will be:this is a statementIf you don't use a semicolon at the end of a statement it's not a statement anymore and you'll get an error. But this is a simple error you can find easily.Statement s are parts of php codes and can be freely placed in the file. I mean if you leave a space or more between two statements there won't be any difference for the output. Whitespace characters (space, tab, carriage return etc.) are ignored by the php engine. Anyway you should have a style while coding to make it more readable. Intendations are commonly used for that reason. You can write all your code on a line but think how difficult it will be to write and edit. More About: Introduction , Temen |



