Create Dynamic Database Access Objects

Some simple PHP that makes for a surprisingly robust script

<?php
require_once( "DB.php" );
$dsn = 'mysql://root:password@localhost/books';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class DBRecord
{
  var $h;

  public function DBRecord( $table, $id )
  {
   global $db;
   $res = $db->query( "SELECT * from $table WHERE id=?", array( $id ) );
   $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
 $this->{'h'} = $row;
  }
  public function _ _call( $method, $args )
  {
 return $this->{'h'}[strtolower($method)];
  }
  public function _ _get( $id )
  {
 return $this->{'h'}[strtolower($id)];
  }
}
?> 
 
 
 

A simple script that tests the database access script
<?php require_once( "DBrecord.php" );
 $rec = new DBRecord( "author", 2 );
print $rec->Name()."\n";
?>

PHP 5 represents a substantial upgrade in terms of object-oriented support in the PHP language. Along with a number of upgrades in performance, PHP 5 has a major upgrade in the ability to create dynamic classes. These are classes where the methods and attributes change from object to object. This can be very handy in building database applications.
 

Convert CSV to PHP

Every once in a while, I have a static list of values that I don't want to put into a database, but that I do want to use in my PHP application. That static data can come from a variety of sources, but often it's in a spreadsheet. This handy hack converts any CSV data (one of the easiest formats to pull from a spreadsheet) to PHP code that I can then copy and paste into my PHP page.
<html>
<body>
<form method="post" action="commaconv.php" />
<table>
<tr><td>CSV Data:</td>
<td><textarea name="data" cols="40" rows="10">
"Alabama",4530182
"Alaska",655435
"Arizona",5743834
"Arkansas",2752629
"California",35893799
"Colorado",4601403
"Connecticut",3503604 
"Delaware",830364 
"District of Columbia",553523 
"Florida",17397161 
"Georgia",8829383 
"Hawaii",1262840 
"Idaho",1393262 
"Illinois",12713634 
"Indiana",6237569

"Iowa",2954451
"Kansas",2735502 
"Kentucky",4145922 
"Louisiana",4515770 
"Maine",1317253 
"Maryland",5558058 
"Massachusetts",6416505 
"Michigan",10112620 
"Minnesota",5100958 
"Mississippi",2902966 
"Missouri",5754618 
"Montana",926865 
"Nebraska",1747214 
"Nevada",2334771 
"New Hampshire",1299500 
"New Jersey",8698879 
"New Mexico",1903289 
"New York",19227088 
"North Carolina",8541221 
"North Dakota",634366 
"Ohio",11459011 
"Oklahoma",3523553 
"Oregon",3594586 
"Pennsylvania",12406292 
"Rhode Island",1080632 
"South Carolina",4198068 
"South Dakota",770883 
"Tennessee",5900962 
"Texas",22490022 
"Utah",2389039 
"Vermont",621394 
"Virginia",7459827 
"Washington",6203788 
"West Virginia",1815354 
"Wisconsin",5509026 
"Wyoming",506529</textarea></td></tr>
<tr><td> Field Name 1:</td><td><input name="field0" value="state" /></td></tr>
<tr><td> Field Name 2:</td><td><input name="field1" value="population" /></td>
		  </tr>
<tr><td> Field Name 3:</td><td><input name="field2" value="" /></td></tr>
<tr><td> Field Name 4:</td><td><input name="field3" value="" /></td></tr>
<tr><td> Field Name 5:</td><td><input name="field4" value="" /></td></tr>
</table>
<input type="submit" />
</form>
</body>
</html>

ommaconv.phphandles the data conversion.
 PHP that converts data from CSV just as easily as from XML or SQL
<html><body>
<div style="font-family:courier; font-size:small;">
$data = array(<br/>
<?
$fieldnames = array(
  $_POST['field0' ],
  $_POST['field1' ],
  $_POST['field2' ],
  $_POST['field3' ],
  $_POST['field4' ] );
$rows = split( "\n", $_POST['data'] );
$index = 0;
foreach( $rows as $row )
{
  if ( $index != 0 )
    print( ",<br/>" );
  $index++;
	  print( " array(" );
  $fields = split( ",", $row );
  for( $f = 0; $f < count( $fields ); $f++ )
  {
	  
    $data = $fields[ $f ];
	$data = preg_replace( "/\\\\\"/", "\"", $data );

	if ( $f > 0 )
	  print( ", " );
	print( $fieldnames[ $f ] );
	print( " => " );
	print( $data );
	}
	print( " )" );
  }
  ?><br/>
  );
  </div>
  </body></html>

Using Cookie Authentication PHP

Store authentication status in a cookie or as part of a session. When a user logs in
successfully, put their username in a cookie. Also include a hash of the username and a secret
word so a user can't just make up an authentication cookie with a username in it:

$secret_word = 'if i ate spinach';
if (pc_validate($_REQUEST['username'],$_REQUEST['password'])) {
setcookie('login',
$_REQUEST['username'].','.md5($_REQUEST['username'].$secret_word));
}
 Discussion
When using cookie authentication, you have to display your own login form:
<form method="post" action="login.php">
Username: <input type="text" name="username"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Log In">
</form>
You can use the same pc_validate( ) function from the Recipe 8.10 to verify the username
and password. The only difference is that you pass it $_REQUEST['username'] and
$_REQUEST['password'] as the credentials instead of $_SERVER['PHP_AUTH_USER'] and
$_SERVER['PHP_AUTH_PW']. If the password checks out, send back a cookie that contains a
username and a hash of the username, and a secret word. The hash prevents a user from
faking a login just by sending a cookie with a username in it.
Once the user has logged in, a page just needs to verify that a valid login cookie was sent in
order to do special things for that logged-in user:
unset($username);
if ($_COOKIE['login']) {
list($c_username,$cookie_hash) = split(',',$_COOKIE['login']);
if (md5($c_username.$secret_word) == $cookie_hash) {
$username = $c_username;
} else {
print "You have sent a bad cookie.";
}
}
if ($username) {
print "Welcome, $username.";
} else {
print "Welcome, anonymous user.";
}
If you use the built-in session support, you can add the username and hash to the session and
avoid sending a separate cookie. When someone logs in, set an additional variable in the
session instead of sending a cookie:
if (pc_validate($_REQUEST['username'],$_REQUEST['password'])) {
$_SESSION['login'] =
$_REQUEST['username'].','.md5($_REQUEST['username'].$secret_word));
}
The verification code is almost the same; it just uses $_SESSION instead of $_COOKIE:

unset($username);
if ($_SESSION['login']) {
list($c_username,$cookie_hash) = explode(',',$_SESSION['login']);
if (md5($c_username.$secret_word) == $cookie_hash) {
$username = $c_username;
} else {
print "You have tampered with your session.";
}
}
Using cookie or session authentication instead of HTTP Basic authentication makes it much
easier for users to log out: you just delete their login cookie or remove the login variable from
their session. Another advantage of storing authentication information in a session is that you
can link users' browsing activities while logged in to their browsing activities before they log in
or after they log out. With HTTP Basic authentication, you have no way of tying the requests
with a username to the requests that the same user made before they supplied a username.
Looking for requests from the same IP address is error-prone, especially if the user is behind a
firewall or proxy server. If you are using sessions, you can modify the login procedure to log
the connection between session ID and username:
if (pc_validate($_REQUEST['username'],$_REQUEST['password'])) {
$_SESSION['login'] =
$_REQUEST['username'].','.md5($_REQUEST['username'].$secret_word));

PHP Functions

A function is a named sequence of code statements that can optionally accept parameters and return a value. A function call is an expression that has a value; its value is the returned value from the function. PHP provides a large number of internal functions. The "Function Reference" section lists all of the commonly available functions. PHP also supports user-definable functions. To define a function, use the function keyword. For example:
function soundcheck($a, $b, $c) {
  return "Testing, $a, $b, $c";
}
When you define a function, be careful what name you give it. In particular, you need to make sure that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts with an internal function, you get the following error:
Fatal error: Can't redeclare already declared function in 
filename on line N
After you define a function, you call it by passing in the appropriate arguments. For example:
echo soundcheck(4, 5, 6);
You can also create functions with optional parameters. To do so, you set a default value for each optional parameter in the definition, using C++ style. For example, here's how to make all the parameters to the soundcheck() function optional:
function soundcheck($a=1, $b=2, $c=3) {
  return "Testing, $a, $b, $c";
}

 Passing Arguments to Functions

There are two ways you can pass arguments to a function: by value and by reference. To pass an argument by value, you pass in any valid expression. That expression is evaluated and the value is assigned to the corresponding parameter defined within the function. Any changes you make to the parameter within the function have no effect on the argument passed to the function. For example:
function triple($x) {
  $x=$x*3;
  return $x;
}
$var=10;
$triplevar=triple($var);
In this case, $var evaluates to 10 when triple() is called, so $x is set to 10 inside the function. When $x is tripled, that change does not affect the value of $var outside the function.
In contrast, when you pass an argument by reference, changes to the parameter within the function do affect the value of the argument outside the scope of the function. That's because when you pass an argument by reference, you must pass a variable to the function. Now the parameter in the function refers directly to the value of the variable, meaning that any changes within the function are also visible outside the function. For example:
function triple(&$x) {
  $x=$x*3;
  return $x;
}
$var=10;
triple($var);
The & that precedes $x in the triple() function definition causes the argument to be passed by reference, so the end result is that $var ends up with a value of 30.

1.10.2 Variable Scope

The scope of a variable is the context within which a variable is available. There are two scopes for variables in PHP. Global variables are available directly from the mainline PHP execution. That is, if you are not inside a function, you can access global variables directly. Unlike most other languages, functions in PHP have their own, completely separate variable scope. Take this example:
<?php
  function test( ) {
    echo $a;
  }

  $a = "Hello World";
  test( );       
?>
If you run this script you will find that there is no output. This is because the $a you are trying to access inside the test( ) function is a completely different variable from the global $a you created in the global scope just before calling the function. In order to access a globally-scoped variable from inside a function, you need to tell the function to use the global scope for that particular variable. It can be done with the global keyword like this:
<?php
  function test( ) {
    global $a;
    echo $a;
  }

  $a = "Hello World";
  test( );       
?>
Alternatively, you can use the $GLOBALS array like this:
<?php
  function test( ) {
    echo $GLOBALS['a'];
  }

  $a = "Hello World";
  test( );       
?>
In this last example, the $GLOBALS array is known as a superglobal, which is a variable that is automatically available in all scopes without needing to be declared global in order to be accessed from within a function.

 Static Variables

PHP supports declaring local function variables as static. A static variable retains its value between function calls, but is still accessible only from within the function it is declared in. Static variables can be initialized; this initialization only takes place the first time the static declaration is executed. Static variables are often used as counters, as in this example:
function hitcount( )
  static $count = 0;

  if ($count == 0) {
    echo "This is the first access to this page";
  } else {
    echo "This page has been accessed $count times";
  }
  $count++;
}

PHP Web-Related Variables

PHP automatically creates variables for all the data it receives in an HTTP request. This can include GET data, POST data, cookie data, and environment variables. The variables are either in PHP's global symbol table or in one of a number of superglobal arrays, depending on the value of the register_globals setting in your php.ini file.
In PHP 4.2.0 and after, the default setting for register_globals is off. With register_globals off, all the various variables that are usually available directly in the global symbol table are now available via individual superglobal arrays. There is a limited set of superglobals and they cannot be created from a user-level script. The superglobal array to use depends on the source of the variable. Here is the list:
$_GET
GET-method variables. These are the variables supplied directly in the URL. For example, with http://www.example.com/script.php?a=1&b=2, $_GET['a'] and $_GET['b'] are set to 1 and 2, respectively.
$_POST
POST-method variables. Form field data from regular POST-method forms.
$_COOKIE
Any cookies the browser sends end up in this array. The name of the cookie is the key and the cookie value becomes the array value.
$_REQUEST
This array contains all of these variables (i.e., GET, POST, and cookie). If a variable appears in multiple sources, the order in which they are imported into $_REQUEST is given by the setting of the variables_order php.ini directive. The default is 'GPC', which means GET-method variables are imported first, then POST-method variables (overriding any GET-method variables of the same name), and finally cookie variables (overriding the other two).
$_SERVER
These are variables set by your web server. Traditionally things like DOCUMENT_ROOT, REMOTE_ADDR, REMOTE_PORT, SERVER_NAME, SERVER_PORT, and many others. To get a full list, have a look at your phpinfo( ) output, or run a script like the following to have a look:
<?php
  foreach($_SERVER as $key=>$val) {
    echo '$_SERVER['.$key."] = $val<br>\n";
  }
?>
$_ENV
Any environment variables that were set when you started your web server are available in this array.
$_FILES
For RFC 1867-style file uploads the information for each uploaded file is available in this array. For example, for a file upload form containing:
<input name="userfile" type="file">
The $_FILES array will look something like this:
$_FILES['userfile']['name'] => photo.png
$_FILES['userfile']['type'] => image/png
$_FILES['userfile']['tmp_name'] => /tmp/phpo3kdGt
$_FILES['userfile']['error'] => 0
$_FILES['userfile']['size'] => 158918
Note that the 'error' field is new for PHP 4.2.0 and the values are: 0 (no error, file was uploaded); 1 (the uploaded file exceeds the upload_max_filesize directive in php.ini); 2 (the uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form); 3 (the actual number of bytes uploaded was less than the specified upload file size); and 4 (no file was uploaded).

PHP Data Types

PHP provides four primitive data types: integers, floating point numbers, strings, and booleans. In addition, there are two compound data types: arrays and objects.

 Integers

Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On 32-bit platforms, integer values range from -2,147,483,648 to +2,147,483,647. PHP automatically converts larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal (base-10), hexadecimal (base-16), or octal (base-8). For example:
$decimal=16;
$hex=0x10;
$octal=020;

 Floating Point Numbers

Floating point numbers represent decimal values. The range of floating point numbers in PHP is equivalent to the range of the double type in C. On most platforms, a double can be between 1.7E-308 to 1.7E+308. A double may be expressed either as a regular number with a decimal point or in scientific notation. For example:
$var=0.017;
$var=17.0E-3
PHP also has two sets of functions that let you manipulate numbers with arbitrary precision. These two sets are known as the BC and the GMP functions. See http://www.php.net/bc and http://www.php.net/gmp for more information.

 Strings

A string is a sequence of characters. A string can be delimited by single quotes or double quotes:
'PHP is cool'
"Hello, World!"
Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. For example:
$a="World";
echo "Hello\t$a\n";
This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable substitution is performed on the variable $a and the escape sequences are converted to their corresponding characters. Contrast that with:
echo 'Hello\t$a\n';
In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape sequences.
Another way to assign a string is to use what is known as the heredoc syntax. The advantage with this approach is that you do not need to escape quotes. It looks like this:
$foo = <<<EOD
  This is a "multiline" string
  assigned using the 'heredoc' syntax.
EOD;
The following table shows the escape sequences understood by PHP inside double-quoted strings.
Escape sequence
Meaning
\n
Linefeed (LF or 0x0A (10) in ASCII)
\r
Carriage return (CR or 0x0D (13) in ASCII)
\t
Horizontal tab (HT or 0x09 (9) in ASCII)
\\
Backslash
\$
Dollar sign
\"
Double quote
\123
Octal notation representation of a character
\x12
Hexadecimal notation representation of a character

 Booleans

The boolean type only has two states: true and false. For example:
$flag = true;
Boolean values are most commonly used when the == or === operators perform a comparison and return the result.

 Arrays

An array is a compound data type that can contain multiple data values, indexed either numerically or with strings. For example, an array of strings can be written like this:
$var[0]="Hello";
$var[1]="World";
Note that when you assign array elements like this, you do not have to use consecutive numbers to index the elements.

Showing the Browser and IP Address

Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your browser:
<html><head><title>PHP Example</title></head>
<body>
   You are using 
    <?php echo $_SERVER['HTTP_USER_AGENT'] ?>
   <br />
   and coming from 
    <?php echo $_SERVER['REMOTE_ADDR'] ?>
</body></html>
You should see something like the following in your browser window:
You are using Mozilla/5.0 (X11; U; Linux i686; en-US; 
rv:1.1b) Gecko/20020722
and coming from 127.0.0.1

1.13.2 Intelligent Form Handling

Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:
<html><head><title>Form Example</title></head>
<body>
<h1>Form Example</h1>
<?
function show_form($first="", $last="", 
                   $interest="") {
 $options = array("Sports", "Business", "Travel", 
                  "Shopping", "Computers");
 if(!is_array($interest)) $interest = array( );
 ?>
 <form action="form.php" method="POST">
 First Name:
 <input type="text" name="first" 
        value="<?echo $first?>">
 <br />
 Last Name:
 <input type="text" name="last" 
        value="<?echo $last?>">
 <br />
 Interests:
 <select multiple name="interest[ ]">
 <?php
  foreach($options as $option) {
   echo "<option";
   if(in_array($option, $interest)) {
    echo " selected ";
   }
   echo "> $option</option>\n";
  }
 ?>
 </select><br />
 <input type=submit>
 </form>
<?php } // end of show_form( ) function

if($_SERVER['REQUEST_METHOD']!='POST') {
 show_form( );
} else {
 if(empty($_POST['first']) || 
    empty($_POST['last'])  ||
    empty($_POST['interest'])) {
  echo "<p>You did not fill in all the fields,";
  echo "please try again</p>\n";
  show_form($_POST['first'],$_POST['last'], 
            $_POST['interest']);
 }
 else {
  echo "<p>Thank you, $_POST[first] $_POST[last], you ";
  echo 'selected '. 
       join(' and ', $_POST['interest']);
  echo " as your interests.</p>\n";
 }
}
?>
</body></html>
There are a few things to study carefully in this example. First, we have isolated the display of the actual form to a PHP function called show_form(). This function is intelligent, in that it can take the default value for each of the form elements as an optional argument. If the user does not fill in all the form elements, we use this feature to redisplay the form with whatever values the user has already entered. This means the user only has to fill the fields he missed, which is much better than asking the user to hit the Back button or forcing him to reenter all the fields.

The Small Business Beginners Guide

Promotion Methods
Search engines are not the only way to get visitors to your site and a common
sense approach will go a long way to helping you get people to your site.
Use your domain name and Web address in ALL your company’s promotional
materials. This includes business cards, brochures, newspaper ads, classified
ads, flyers, etc. If you have a real store, make sure your Web address is
printed on everything that leaves with your customers including register
receipts, shopping bags, and product packaging.
Have a placard printed with your Web address close to every register where
every customer can see it. You can even have small business cards printed
with your store name and Web address. Place these on the sales counter so
customers can take them.
Make sure your Web address appears in EVERY display ad in local
publications. Even include it in your radio commercials. Some communities
have a local cable channel that advertises local businesses. If you use this
media, get your Web address there too.
Look to the Web for more promotional ideas. Again, many sites give out free
information and guides that will give you ideas on promoting your e-business
both online and offline.
One fact is certain; promoting your Web site is going to be an ongoing
commitment. And, the more you dedicate yourself to continually promoting
your site, the more rewards you will reap.

Internet Search Engines

You’ve probably used a search engine to look for information in your own
journeys into the online world. If you have, you understand how valuable they
are to users looking for sites on the Web. Without them, we’d all be forever
lost in a sea of information.
Search engines try to organize the Web into orderly subjects so us humans can
find what we’re looking for. They fall into two main categories – true search
engines and indexes.

The true search engine uses the Web page contents to categorize and index the
page. They do this by periodically releasing a software program called a
spider or bot out to the Internet to gather data about Web pages. The spider
returns this data to a computer that organizes the data and indexes the page.
True search engines are machine driven. There is little or no human
intervention involved in the whole process. And, it’s all automatic.
Indexes are another story. They are built and controlled by people. A good
example of a human-driven Web index is Yahoo!. Web sites must be
submitted to Yahoo! for review. Only after someone looks at the site and
determines what category it belongs in is the site added to the index.
Yahoo is the most used Web index, so it’s critical that you get listed – and get
listed in the right place.
Getting your site listed in an index, especially Yahoo!, can take months to
accomplish. And, the site owner has little to say about how his/her site is
listed. The person doing the reviewing and indexing has the final say.
Getting your site changed after it is included in the index is next to
impossible. So, make sure you do this right the first time. Have a list of
keywords, your site title, and other information well thought-out and saying
exactly what you want it to say.

Internet Marketing for Smart People

There are some basic business rules you should follow:

• Your pages must load FAST. Most Web surfers will give you about 30
seconds before they click off. Keep your graphic files small.
• Be consistent. This means use the same colors, same backgrounds,
same typefaces, etc. throughout your entire site. If your menu is on the
left on your home page, then keep it on the left for all your pages.
• Don’t mix too many typefaces - stick to a maximum of 2 and, use
standard typefaces.
• Keep the animations to a minimum – to many can be very distracting.
• Don’t use music on a business site.
• Don’t try to be cute or kewl. This is serious business.
• Go easy on the high-tech. Just because you can do something doesn’t
mean you should.
• If you’re selling something, don’t mask it. Let your visitors know your
intentions right from the start.
• Make sure your customers can easily find your company name,
address, and telephone numbers easily. Don’t hide this information.
Begin by deciding what you want your site to accomplish and round-up all the
tools and materials you’ll need to build your site. In particular:
• Have all your content materials – stuff like images, text, and other
media you plan to use.
• Have at least the two popular Web browsers installed on your
computer - Netscape Navigator and Internet Explorer. You’ll want to
test your completed pages on both. (Your pages will appear differently
on each one.)
• Know your target audience and what you expect to offer them.
• Get an idea of the structure and scope of your site.
There are many sites on the Web that give you all the basic instruction you’ll
ever need to create Web pages. Try searching Yahoo! or your favorite search
engine for information about Web site building for beginners.

Facebook tests paid messages to strangers

Most important messages go straight to your inbox on Facebook. But there's a second class of messages, including potential spam and notes from people not in your network, that the site's algorithms deem "less relevant."
These unlucky missives are dropped in the little-known "Other" folder, where they will often spend the remainder of their digital existence unseen, unread and unloved.

"Several commentators and researchers have noted that imposing a financial cost on the sender may be the most effective way to discourage unwanted messages and facilitate delivery of messages that are relevant and useful," says the post.
The "inbox delivery test" will be available only to select people using Facebook in the U.S. for now. Companies won't have access to the feature at this time, and people are limited to one paid outgoing message a week to minimize abuse.

Php Mysql Image upload

<?php  

// 1. Gem modtagne formulardata i variabler:  
$navn = $_POST['navn'];  
$alder = $_POST['alder'];  
$postnr = $_POST['postnr'];  
$mail = $_POST['mail'];  
$billede = $_FILES['profilbillede'];  
$password = $_POST['password'];  



// 2. Forbind til databasen:  
$databaselink = mysqli_connect("localhost","mmddk3e12m8b18", "****", "mmddk3e12m8b18") or die     ("Fejl: Kan ikke etablere forbindelse til database");



$billednavn = billedupload($billede);  
// besked til brugeren om at der er sket en fejl    
if($billednavn == false){  
die("Der skete en fejl under upload af billedet");
}



// 3. Udform insert SQL streng med de modtagne data, og udfør SQL strengen på databasen vha     mysqli_query:  
$query = "INSERT INTO brugere (navn, alder, postnr, mail, password, profilbillede) VALUES ('$navn', '$alder', '$postnr', '$mail', '$password', '$billednavn')";  
$result = mysqli_query($databaselink, $query) or die( "Forespørgslen kunne ikke udføres: " .         mysqli_error($databaselink));  

// 4. luk databasen:  
mysqli_close($databaselink);  

function billedupload($fil){  
if($fil['type']=='image/jpeg' or $fil['type']=='image/png'){  
$tmp_navn = $fil['tmp_name'];  
$filnavn = $fil['name'];  
$target = 'images/' . time() . $filnavn;  
move_uploaded_file($tmp_navn,$target);  
return $target;  
}  
else{  
return false;  
}  
}  

?>
 
Make sure $_FILES is set? Debug it with var_dump($_FILES)and  enctype="multipart/form-data" in your <form> 

Samsung sells 500 handsets per minute

Samsung Electronics, the world leader in mobiles and memory chips, likely earned a quarterly profit of $8.1 billion, as it sold close to 500 handsets every minute and as demand picked up for the flat screens it makes for mobile devices

Yahoo! Axis

A Search Browser

By Yahoo!

Get a smarter, faster and more visual way to search and browse the web!

Yahoo! Axis is a new browser that redefines what it means to search and browse the web on your iPhone, iPad.

Requirements: Compatible with iPhone, iPod touch, and iPad. Requires iOS 5.1 or later. This app is optimized for iPhone 5.

Yahoo! Axis is a desktop web browser extension and mobile browser for iOS devices created and developed by Yahoo!

Since on iOS Axis is essentially running a skin over top of Safari -- similar to what the Atomic browser does. In Yahoo's case, though, it's a powerful skin, filled with features you won't find on Apple's browser, such as easy toggling between regular and image searches, and instant syncing of bookmarks and tabs between desktop, iPhone and iPad.

 

What is Shell Script

Normally shells are interactive. It means shell accept command from you (via keyboard) and execute them. But if you use command one by one (sequence of 'n' number of commands) , the you can store this sequence of command to text file and tell the shell to execute this text file instead of entering the commands. This is know as shell script.

The Role of the Device Driver

As a programmer, you are able to make your own choices about your driver, and
choose an acceptable trade-off between the programming time required and the flexibility
of the result. Though it may appear strange to say that a driver is “flexible,” we
like this word because it emphasizes that the role of a device driver is providing
mechanism, not policy.

The distinction between mechanism and policy is one of the best ideas behind the
Unix design. Most programming problems can indeed be split into two parts: “what
capabilities are to be provided” (the mechanism) and “how those capabilities can be
used” (the policy). If the two issues are addressed by different parts of the program,
or even by different programs altogether, the software package is much easier to
develop and to adapt to particular needs.

For example, Unix management of the graphic display is split between the X server,
which knows the hardware and offers a unified interface to user programs, and the
window and session managers, which implement a particular policy without knowing
anything about the hardware. People can use the same window manager on different
hardware, and different users can run different configurations on the same
workstation. Even completely different desktop environments, such as KDE and
GNOME, can coexist on the same system. Another example is the layered structure
of TCP/IP networking: the operating system offers the socket abstraction, which
implements no policy regarding the data to be transferred, while different servers are
in charge of the services (and their associated policies). Moreover, a server like ftpd
provides the file transfer mechanism, while users can use whatever client they prefer;
both command-line and graphic clients exist, and anyone can write a new user interface
to transfer files.

The kernel


The kernel is a piece of software that, roughly speaking, provides a layer between the hardware and the application programs running on a computer. In a strict, computer-science sense, the term 'Linux' refers only to the kernel - the bit that Linus Torvalds wrote in the early 90s.

The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.

Php Directory Functions


  • chdir — Change directory
  • chroot — Change the root directory
  • closedir — Close directory handle
  • dir — Return an instance of the Directory class
  • getcwd — Gets the current working directory
  • opendir — Open directory handle
  • readdir — Read entry from directory handle
  • rewinddir — Rewind directory handle
  • scandir — List files and directories inside the specified path

File Manipulation

11.3. File Manipulation

There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't connect to the database. It'd be impossible to keep this information in the database, since it's not available at exactly the time you'd need to write to it. PHP provides functions for file manipulation that can perform the following:
  • Check the existence of a file
  • Create a file
  • Append to a file
  • Rename a file
  • Delete a file

The file_exists.php script checks to see if the file is there
<?php
  $file_name="file_exists.php";

  if(file_exists($file_name)) {
    echo ("$file_name does exist.");
  }
  else {
    echo ("$file_name does not exist.");
  }
?>

As you would expect, the file does exist:
The file exists.php does exist. 
 
PHP provides several functions to tell you about various file attributes. PHP has the ability to read data from, and write data to, files on your system. However, it doesn't just stop there. It comes with a full-featured file-and-directory-manipulation API that allows you to:
  • View and modify file attributes
  • Read and list directory contents
  • Alter file permissions
  • Retrieve file contents into a variety of native data structures
  • Search for files based on specific patterns
All of this file manipulation through the API is robust and flexible. These characteristics are why we're writing this book. PHP has a lot of great commands, including all the file manipulation ones.
11.3.1.1. Permissions
Now that you know a file exists, you may think you're done, but you're not. Just because it's there doesn't mean you can read, write, or execute the file. To check for these attributes, use is_readable to check for read access, is_writable to check for write access, and is_executable to check for the ability to execute the file. Each function takes a filename as its parameter. Unless you know the file is in the same directory as your script, you must specify a full path to the file in the filename. You can use concatenation to put the path and filename together, as in:
$file_name = $path_to_file . $file_name_only; 
                                  
 
 
 
 

Including and Requiring PHP Files

To make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program. However, PHP provides four functions that enable you to insert code from other files.
  • include
  • require
  • include_once
  • require_once
All the include and require functions can take a local file or URL as input, but they cannot import a remote file. require and include functions are pretty similar in their functionality except for the way in which they handle an irretrievable resource. For example, include and include_once provide a warning if the resource cannot be retrieved and try to continue execution of the program. The require and require_once functions provide stop processing of the particular page if they can't retrieve the resource. Now we're going to get more specific about these four functions.

Defining Functions

There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement:
function some_function([arguments]) { code to execute }

The brackets ([ ]) mean optional. The code could also be written with optional_arguments in place of [arguments]. The function keyword is followed by the name of the function. Function names abide by the same rules as other named objects such as variables in PHP. A pair of parentheses must come next. If your function has parameters, they're specified within the parentheses. Finally, the code to execute is listed between curly brackets, as seen in the code above.
You can define functions anywhere in your code and call them from virtually anywhere. Scope rules apply. The scope of a variable is the context within which it's defined. For the most part, all PHP variables have only a single scope. A single scope spans included and required files as well. The function is defined on the same page or included in an include file. Functions can have parameters and return values that allow you to reuse code.
To create your own function that simply displays a different hello message, you would write:
 
<?php
function hi()
{
  echo ("Hello from function-land!");
}
//Call the function
hi();
?>

which displays:
Hello from function-land!

PHP - Echo

<?php
$myiString = "Hi!";
echo $myiString;
echo "<h5>I love  PHP!</h5>";
?>
 

Display:

Hi!
I love  PHP!
 A simple form example
 
 
1 <html>
 2 <head>
 3  <title>Building a Form</title>
 4 </head>
 5 <body>
 6  <form action="<?php echo($_SERVER['PHP_SELF']); ?>"
 7        method="get">
 8   <label>
 9         Search: <input type="text" name="search" />
 10    </label>
 11      <input type="submit" value="Go!" />
 12  </form>
 13 </body>
 14 </html>
 

PHP Configuration Directives

Although the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the code you write as well as the techniques that you employ, and your responsibilities might extend slightly beyond the application on occasion.

The configuration of PHP is primarily dictated by a file called php.ini. This file contains many configuration directives, and each of these affects a very specific aspect of PHP. If this file is absent, or if a particular configuration directive is absent from the file, a default value is used.
If you do not know the location of your php.ini file, you can use phpinfo( ) to determine where PHP expects to find it:
 
<?php

    phpinfo();

    ?>

PHP Sessions

The session_start( ) function is used to create a new session. A session is unique to the interaction between a browser and a web database application. If you use your browser to access several sites at once, you'll have several unrelated sessions. Similarly, if several users access your application each has their own session. However, if you access an application using two browsers (or two browser windows) at the same time, in most cases the browsers will share the same session; this can lead to unpredictable behavior—that's the reason why many web sites warn against it.

The first time a user requests a script that calls session_start( ), PHP generates a new session ID and creates an empty file to store session variables. PHP also sends a cookie back to the browser that contains the session ID. However, because the cookie is sent as part of the HTTP headers in the response to the browser, you need to call session_start( ) before any other output is generated

The session identifier generated by PHP is a random string of 32 hexadecimal digits, such as fcc17f071bca9bf7f85ca281094390b4. When a new session is started, PHP creates a session file, using the session identifier, prefixed with sess_, for the filename. For example, the filename associated with our example session ID on a Unix system is /tmp/sess_fcc17f071bca9bf7f85ca281094390b4.

Using Session Variables

The session_start( ) function is also used to find an existing session. If a call is made to session_start( ), and a session has previously been started, PHP attempts to find the session file and initialize the session variables. PHP does this automatically by looking for the session cookie in the browser request whenever you call session_start( ). You don't need to do anything different when starting a new session or restoring an existing one. Even if the identified session file can't be found, session_start( ) simply creates a new session file.


A simple PHP script that uses a session
<?php

  require_once "HTML/Template/ITX.php";



  // This call either creates a new session or finds an existing one.

  session_start( );



  // Check if the value for "count" exists in the session store

  // If not, set a value for "count" and "start"

  if (!isset($_SESSION["count"]))

  {

    $_SESSION["count"] = 0;

    $_SESSION["start"] = time( );

  }



  // Increment the count

  $_SESSION["count"]++;



  $template = new HTML_Template_ITX("./templates");

  $template->loadTemplatefile("example.10-2.tpl", true, true);



  $template->setVariable("SESSION", session_id( ));

  $template->setVariable("COUNT", $_SESSION["count"]);

  $template->setVariable("START", $_SESSION["start"]);

  $duration = time( ) - $_SESSION["start"];

  $template->setVariable("DURATION", $duration);



  $template->parseCurrentBlock( );



  $template->show( );

?>


Length of a String

The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string:
integer strlen(string subject)
We used strlen( ) earlier in the chapter to compare string lengths. Consider another simple example that prints the length of a 16-character string:
print strlen("This is a String");  // prints 16

Creating Arrays

PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:
$numbers = array(5, 4, 3, 2, 1);

$words = array("Web", "Database", "Applications");



// Print the third element from the array of integers: 3

print $numbers[2];



// Print the first element from the array of strings: "Web"

print $words[0];

By creating arrays this way, PHP assigns integer keys, or indexes to each element. By default, the index for the first element in an array is 0—this may seem odd but think of the index as an offset from the starting position in an array. The values contained in an array can be retrieved and modified using the bracket [ ] syntax. You can also create an array by assigning elements to a new, unset variable. The following code fragment illustrates the bracket syntax with an array of strings:
$newArray[0] = "Potatoes";

$newArray[1] = "Carrots";

$newArray[2] = "Spinach";



// Replace the third element

$newArray[2] = "Tomatoes";

In this example, PHP automatically treats $newArray as an array without a call to array( ).
An empty array can be created by assigning to a variable the return value of array( ). Values can then be added using the bracket syntax. PHP automatically assigns the next numeric index as the key (the largest integer key value plus one) when a key isn't supplied. The result of the following fragment is an array containing three items.
$shopping = array( );



$shopping[] = "Milk";

$shopping[] = "Coffee";

$shopping[] = "Sugar";

It's also easy to print individual element values themselves:
print $shopping[0];   // prints "Milk"

print $shopping[1];   // prints "Coffee"

print $shopping[2];   // prints "Sugar"

PHP Zip File Functions


PHP MySQL Functions


PHP Date / Time Functions


PHP HTTP Functions


PHP Array Functions

  • array_change_key_case — Changes all keys in an array
  • array_chunk — Split an array into chunks
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Counts all the values of an array
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Computes the difference of arrays
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Fill an array with values
  • array_filter — Filters elements of an array using a callback function
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_keys — Return all the keys or a subset of the keys of an array
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — Merge two or more arrays recursively
  • array_merge — Merge one or more arrays
  • array_multisort — Sort multiple or multi-dimensional arrays
  • array_pad — Pad array to the specified length with a value
  • array_pop — Pop the element off the end of array
  • array_product — Calculate the product of values in an array
  • array_push — Push one or more elements onto the end of array
  • array_rand — Pick one or more random entries out of an array
  • array_reduce — Iteratively reduce the array to a single value using a callback function
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Return an array with elements in reverse order
  • array_search — Searches the array for a given value and returns the corresponding key if successful
  • array_shift — Shift an element off the beginning of array
  • array_slice — Extract a slice of the array
  • array_splice — Remove a portion of the array and replace it with something else
  • array_sum — Calculate the sum of values in an array
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Removes duplicate values from an array
  • array_unshift — Prepend one or more elements to the beginning of an array
  • array_values — Return all the values of an array
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Apply a user function to every member of an array
  • array — Create an array
  • arsort — Sort an array in reverse order and maintain index association
  • asort — Sort an array and maintain index association
  • compact — Create array containing variables and their values
  • count — Count all elements in an array, or something in an object
  • current — Return the current element in an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • end — Set the internal pointer of an array to its last element
  • extract — Import variables into the current symbol table from an array
  • in_array — Checks if a value exists in an array
  • key — Fetch a key from an array
  • krsort — Sort an array by key in reverse order
  • ksort — Sort an array by key
  • list — Assign variables as if they were an array
  • natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • natsort — Sort an array using a "natural order" algorithm
  • next — Advance the internal array pointer of an array
  • pos — Alias of current
  • prev — Rewind the internal array pointer
  • range — Create an array containing a range of elements
  • reset — Set the internal pointer of an array to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sizeof — Alias of count
  • sort — Sort an array
  • uasort — Sort an array with a user-defined comparison function and maintain index association
  • uksort — Sort an array by keys using a user-defined comparison function
  • usort — Sort an array by values using a user-defined comparison function

Substrings PHP

If you know where in a larger string the interesting data lies, you can copy it out with

the substr( ) function:

$piece = substr(string, start [, length ]);

The start argument is the position in string at which to begin copying, with 0
meaning the start of the string. The length argument is the number of characters to
copy (the default is to copy until the end of the string).
For example:

$name = "Fred Flintstone";
$fluff = substr($name, 6, 4); // $fluff is "lint"
$sound = substr($name, 11); // $sound is "tone"
To learn how many times a smaller string occurs in a larger one, use substr_count( ):
$number = substr_count(big_string, small_string);

Cleaning Strings

Often, the strings we get from files or users need to be cleaned up before we can use
them. Two common problems with raw data are the presence of extraneous
whitespace, and incorrect capitalization (uppercase versus lowercase).

Removing Whitespace

You can remove leading or trailing whitespace with the trim( ), ltrim( ), and rtrim( )
functions:
$trimmed = trim(string [, charlist ]);
$trimmed = ltrim(string [, charlist ]);
$trimmed = rtrim(string [, charlist ]);

trim( ) returns a copy of string with whitespace removed from the beginning and
the end. ltrim( ) (the l is for left) does the same, but removes whitespace only from
the start of the string. rtrim( ) (the r is for right) removes whitespace only from the
end of the string. The optional charlist argument is a string that specifies all the
characters to strip.

For example:
$title = " Programming PHP \n";
$str_1 = ltrim($title); // $str_1 is "Programming PHP \n"
$str_2 = rtrim($title); // $str_2 is " Programming PHP"
$str_3 = trim($title); // $str_3 is "Programming PHP"

PHP Variable names

Variable names always begin with a dollar sign ($) and are case-sensitive. Here are
some valid variable names:
$pill
$ad_count
$dForce
$I_kk_PHP
$_underscore
$_int
Here are some illegal variable names:
$not valid
$|
$3ka 
These variables are all different:
$hot_stuff $Hot_stuff $hot_Stuff $HOT_STUFF

CREATING THE DATABASE

To create a database, connect to MySQL and run the CREATE DATABASE command. This is the
MySQL command to create a database called mydatabase:

CREATE DATABASE ’mydatabase’;


<?php
define(“MYSQLUSER”, “root”);
define(“MYSQLPASS”, “p##V89Te5t”);
define(“HOSTNAME”, “localhost”);
if ($connection = new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS)) {
echo ‘Successful connection to MySQL <br />’;
if ($result = $connection->query(“CREATE DATABASE ’mydatabase’”)) {
$connection->select_db(‘mydatabase’); // use the database
echo “Database created”;
} else {
echo “Problem creating the database. Is the user not allowed
to create database or does the database already exist?”; }
}

?>

Note that the preceding code uses an equal sign in the if statement:
if ($result = $connection->query(“CREATE DATABASE ’mydatabase’”)) {
The way that this statement is processed is that the statement on the right is evaluated fi rst, which
attempts to create the database. That function returns a value, which in this case is TRUE or FALSE.
That value is then assigned to $result, which is then evaluated to determine if the code enclosed by
the if statement should be run.

Comparison Operators for If/Else Statements

So far you have just been using the equal comparison operator, but conditional statements are really
checking to see if a statement evaluates to true, not if something is equal. You can also check to see
if something is not equal to something, less than something else, more than something, and so on.
Strings that consist of numbers are converted to numeric before the test except for the identical ===.

Comparison Operators
OPERATOR DESCRIPTION EXAMPLE
== Is equal to 6==’6’ returns true
=== Is identical to (including the type cast) 6===’6’ returns false
!= Is not equal to 6!=5 returns true
<> Is not equal to 6<>5 returns true
< Is less than 6<5 returns false
> Is greater than 6>5 returns true
<= Is less than or equal to 6<=5 returns false
>= Is greater than or equal to 6>=5 returns true
Some