Wednesday, January 19, 2011

Some note about PHP functions


1) Error message: "Function ereg() is deprecated"
Add @ sign before ereg to solve the bug.
Example:
if ($depth >= $min_depth && ereg($mask, $file))
Now add @ sign before ereg($mask, $file)
if ($depth >= $min_depth && @ereg($mask, $file))
to solve eereg() deprecated problem.

2) htmlspecialchars
The translations performed are:

  • &' (ampersand) becomes '&'
  • '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
  • ''' (single quote) becomes ''' only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'  

3)continue
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.


4) The explode() function breaks a string into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Result:
Array
(
[0] => Hello
[1] => world.
[2] => It's
[3] => a
[4] => beautiful
[5] => day.
)
5) PHP query string:
http://someurl.com/page.php?a=1&b=2&c=3
Then echo $_SERVER['QUERY_STRING'] will display: a=1&b=2&c=3, such data is no use to us, we need to parse it, or get it thru global array $_GET, in our case we could write:
echo $_GET['a'];
echo $_GET['b'];
echo $_GET['c'];
which would output:
1
2
3
 
6)  PHP variable names are case sensitive, but the names of functions are 
case insensitive.
 
7)  unlinkDeletes a file
 

Description

bool unlink ( string $filename [, resource $context ] )
Deletes filename. Similar to the Unix C unlink() function. A E_WARNING level error will be generated on failure. 

Example #1 Basic unlink() usage
<?php
$fh 
fopen('test.html''a'); 

fwrite($fh'<h1>Hello world!</h1>'); 
fclose($fh);
unlink('test.html'); 

?>
8) stdClass is php's generic empty class
Example:
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
9. Download as Word Document:
 header("Content-Type: application/ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("content-disposition: attachment;filename=test.doc");

print 
"Text Here"


10. Download as pdf:

<?php
 // We'll be outputting a PDF

 header('Content-type: application/pdf');
// It will be called downloaded.pdf 

header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf 

readfile('original.pdf'); 
?>
11.  $_SERVER['PHP_SELF'] 
in a script at the address http://example.com/test.php/foo.php would be /test.php/foo.php

12 .foreach
$employeeAges;
$employeeAges["Tom"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Lida"] = "30";
$employeeAges["Rachel"] = "46";

foreach( $employeeAges as $key => $value){
 echo "Name: $key, Age: $value <br />";
}

Result:
Name: Tom, Age: 28
Name: Jack, Age: 16
Name: Lida, Age: 35
Name: Rachel, Age: 46

13. MySQL, update:
SELECT * FROM cesei_help c;
update cesei_help set type="eP-ER" where type="lms";
(commit; rollback;)

14. Using colon instead of Curly Brackets
You can also use colon instead of curly brackets, this is done like below.
if($RandomNumber == '1'):
  echo 'The number was 1';
elseif($RandomNumber == '2'):
  echo 'The number was 2';
elseif($RandomNumber == '3'):
  echo 'The number was 3';
else:
  echo 'The number was 4';
endif; 
 
 
15.  What the "@" mean in php
The @ surpresses warning and error messages.

For example, if you run the command is_file("myfile.txt") nad myfile.txt does not exist, you get a warning message. If you run @is_file("myfile.txt") you wont get this warning message.

16. The "i" after the pattern delimiter indicates a case-insensitive search
Example:

<?php// The "i" after the pattern delimiter indicates a case-insensitive search
 if (preg_match("/php/i""PHP is the web scripting language of choice.")) {
    echo 
"A match was found.";
} else {
    echo 
"A match was not found.";
}
?>
17. Getting the domain name out of a URL
<?php 
// get host name from URL,@ ignore warningg; i,  case insensitive
 preg_match('@^(?:http://)?([^/]+)@i',
    
"http://www.php.net/index.html"$matches); 

$host $matches[1];
echo "host is $host \n"; //result: www.php.net
// get last two segments of host name

 preg_match('/[^.]+\.[^.]+$/'$host$matches);
echo 
"domain name is: {$matches[0]}\n";?>
The above example will output:
domain name is: php.net
18. pathinfo() 
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/www/htdocs/inc
lib.inc.php
php
lib.inc


19. isset()
<?php
$a = ' ';
$b = NULL;

isset($a); // => TRUE
isset($b); // => FALSE
?>
20 echo
$foo "foobar";
echo 
"foo is $foo"// foo is foobar

// You can also use arrays
$baz = array("value" => "foo");

echo 
"this is {$baz['value']} !"// this is foo !

// Using single quotes will print the variable name, not the value
 

echo 'foo is $foo'// foo is $foo

// If you are not using any other characters, you can just echo variables
 

echo $foo;           
// foobar
 echo $_SESSION['name']; instead of   echo "$_SESSION['name']";
21 session
session_start(); 
 session_id();
session_name();
$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name'); 


A PHP session exists from the time that a PHP web page is opened until the web browser is closed. It is started by using the session_start method. Once the session has been started then variables can be passed from PHP page to PHP page by using the $_SESSION array.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser. 
To pass session variables from paage to page, you need to put  session_start() in each page.

No comments:

Post a Comment