Archive for php

Redirect Web Page

Redirect HTML page

 
<html>
<head>
<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/index.html">
</head>
</html>
 

Redirect PHP page

 
<?php
header('location: http://url/f.html');
exit();
?>
 

or:

 
<?php
echo "<script>document.location.href='news.php'</script>";
?>

PHP MySql

Safe query
Against sql injection attack.

 
$query = sprintf("INSERT INTO products (
`name`, `description`, `user_id`)
VALUES ('%s', '%s', %d)",
mysql_real_escape_string($product_name, $link),
mysql_real_escape_string($product_description, $link),
$_POST['user_id']);
 

References
PHP Manual
Tutorial

PHP Web

PHP Web

§EGPCS Variables

$HTTP_ENV_VARS
$_ENV
 
$HTT_GET_VARS
$_GET
 
$HTTP_POST_VARS
$_POST
 
$HTTP_POST_FILES
$_FILES
 
$HTTP_COOKIE_VARS
$_COOKIE
 
$HTTP_SERVER_VARS
$_SERVER
 
$_REQUEST
//when register_globals is on
$_GET + $_POST + $_COOKIE
 
$PHP_SELF
 

§Processinq Forms
•Autoquotinq parameters
-set magic_quotes_qpc to true

$value=init_get('magic_quotes_gpc') ?
stripslashes($_GET['param']) : $_GET['param'];

•Self processing

 
<form action="<?php echo $_SERVER['PHP_SELF'] ?>"
  method="POST">

•Multivalued parameters

 
<select name="language[]">

•File upload
-file limits
hard limit: upload_max_filesize
soft limit:

 
<input type="hidden" name="MAX_FILE_SIZE" value="10240">

-form

 
<form enctype="multipart/form-data" action="<?= PHP_SELF ?>"
  method="POST">

-Process

if (is_uploaded_file( $_FILES['toProcess']['tmp_name']) {
	//success
}

•Redirection

<?php
header('location: http://url/f.html');
exit();
?>
or:
<?php
echo "<script>document.location.href='news.php'</script>";
?>

•Authentication

$_SERVER['PHP_AUTH_USER'];
$_SERVER['PHP_AUTH_PW'];

•Cookie

<?php
$page_accesses=$_COOKIE['access'];
setcookie('accesses', ++$page_accesses);
?>

•Sessions

See PHP Manual

<?php
 
Use auto start
-In php.ini set
session.auto_start = 1
 
Otherwise use
session_start();
// This has to be the first line of the page
// Unless you store object in the session
// in which case, you need to include the class first.
 
if (empty($_SESSION['count'])) {
 $_SESSION['count'] = 1;
} else {
 $_SESSION['count']++;
}
?>
 

PHP Funpamentals

Basic syntax

Comments
// for single line
/* */ for multiple line
# for shell style comments

Variables
-starts with $
-may contain
strings
numbers
arrays
-is case sensitive

Variable variables
$foo = 'bar';
$$foo = 'baz';

Variable reference
$black = & $white
-unset a variable that is aliased
unset($white);
//$black still = "snow"

Global variables inside a fxn
function foo(){
global $a;
$a += 2;
}

Static variable

exit and return
-exit("db fail");
-die("db fail");
-$db = @mysql_connect("localhost", $USERNAME,$PASS)
or die("db fail");

Constants
-define('PUBLISHER', "O'Reily");

Strings

String concat
'therer were' . $n . ' ducks.' ;
Quotes
'some'
"some"

Here document
$s = <<< END
Foo
END;

Print strings

echo "hello";
print("hello") //returns bool
printf()
'%.2f', 27.452 //27.45
'%d %x', 214,214 //214 d6
'%03d',7 //007
'%02d/%04y' //15/2004
'%.2f%%',2.1//2.10%
'$%5.2f',4.1 //$% 4.10
sprintf: save instead print
print_r()
var_dump

String manipulation

strlen()
trim()/ltrim/rtrim
strtolower() strtoupper()
ucfirst() ucwords()
String fxn fon html
htmlspecialchars()
htmlentities()
strip_tags()
get_meta_tags()
raw_url_encode()
raw_url_decode()
url_encode()
url_decode()
For sql
add_slash()

Comparison
$1 == $2
strcmp($1,$2); //retuns -1,0,1
strcasecmp() //conv to lower case
strnatcmp() //natural order
soundex($str) //sounds alike
metaphone($str)
similar_text($str1,$str2[,pcnt]);
levenshtein($str1,$str2[,$cost_ins, $cost_rep,$cost_del]);

Manipulate string
substr(string,start[, lengh]);
substr_count(big_str, small_str);
substr_replace(ori, new, start[, len]);
strrev($str); //reverse string
str_repeat($str, count);
str_pad(topad,len[,with[,padtype]]};

Decomp string
$array=explode(sep,str[,limit]};
implode(sep,array); //same join

Tokenizing
$str="fred,flint,35,wilma";
$token=strtok($str,",");
while($token != false){
echo ("$token ");
$token = strtok(",");
}
// fred flint 35 wilma
sscanf(str,temp[, var1,var2...]);

String search
strpos(large_str, small_str);
strrpos(large_str, small_str);
strstr(large_str, small_str);

Decompose url
$array=parse_url(url);

Arrays
-define
$person[0] = 'Edison';
$person['1'] = 'Wankel';
$person = array(
'Edison','Wankel');
$person = array(
'0' => 'Edison',
'1' => 'Winkel');
-use
foreach ($person as $name){
echo "Hello, $name\n";
}

Class

Define Class
class Person {
var $name = '';
function name($new = null) {
if (! is_null($new)){
$this->name = $new;
}
return $this->name;
}
}

Use Class
$ed = new Person;
$ed->name('Edison');
printf("Hello, %s\n",$ed->name;

Operators
-Arithmetic
+
-
*
/
%
++
--
-Assignment
=
+=
-=
*=
/=
%=

-Comparison
==
=== // of same type
!=
!== // of same type
>
<
>=
<=

-Logical
&&
||
!

Condition
-if
if (condition) {
statements;
}else{
statements;
}

-switch
switch (expression) {
case label1:
statements;
break;
case label2:
statements;
break;
default:
statements;
break;
}

Looping
-while
while (condition) {
statements;
}

-do while
do {
statements;
} while (condition);

-for
for (int i=0; i<5; i++) {
statements;
}

exit and return
-exit("db fail");
-die("db fail");
-$db = @mysql_connect("localhost", $USERNAME,$PASS)
or die("db fail");

Include code

header(); ?>
content

-allow_url_fopen in php.ini
-include_once/require_once
-qet_included_files()

Embedding in web pages
-Use echo

 
<?php echo "hello"; ?>
 

-Use PHP Script

 
<script lanquage="php">
  echo "hello!";
<!script>
 

-echo directly

 
<?= "hello"; ?>