Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Php Date or Time

Simplest display of date or time is telling your users what time it is.
Use the date( ) or strftime( )

strftime( ) says: Wed Oct 20 12:00:00 2004

date( ) says: Wed, 20 Oct 2004 12:00:00 -0400

Both strftime( ) and date( ) take two arguments.
The first controls how the time or date string is formatted,
and the second controls what time or date to use. 

print date('m/d/y');




The date( ) and strftime( ) functions each have their strong points.
 If you are generating a formatted time or date string that has
other text in it too, strftime( ) is better because you don't have to
worry about letters without percent signs turning into time or date values.


print 'strftime( ) says: ';
print strftime('Today is %m/%d/%y and the time is %I:%M:%S');
print "\n";
print 'date( ) says: ';
print 'Today is ' . date('m/d/y') . ' and the time is ' . date('h:i:s');



The date( ) function shines for different reasons. It supports
some things that strftime( ) doesn't, such as a leap year indicator,
 a DST indicator, and trimming leading zeroes from some values.
 Furthermore, date( ) is a PHP-specific function. The strftime( ) PHP
 function relies on an underlying operating system function also
called strftime( ). That's why some format characters aren't supported
on Windows. When you use date( ), it's guaranteed to work the same
 everywhere. Unless you need to put text that isn't format characters
 into the format string, choose date( ) over strftime( ).




Php-Configuration Control Through .htaccess

The .htaccessfile is very powerful and can control more than just
URL structure. For instance, you can control PHP configuration
options using the .htaccessfile. To increase the memory
allotted to PHP use this command:

php_value memory_limit 64M

This increases the memory limit in PHP to 64 MB.
You can also increase the max file size upload
and post size:

php_value upload_max_filesize 20M
php_value post_max_size 20M

Now the maximum file size you can post from a form and upload
is set to 20 MB. Most hosting companies set these values to
around 2 MB by default so these are settings that will be used often
for larger file uploads. Not all hosting companies will allow these
values to be set in your .htaccess file, and they could create an
error on your website if that is the case.

The .htaccessfile can also be used for security purposes.
 Using .htaccessallows you to restrict access to your website
by IP address, essentially locking it down from anonymous visitors. To lock
down your website by IP addresses, add the following code to your .htaccessfile:

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Access Control"
AuthType Basic
order deny,allow
deny from all
#IP address to whitelist
allow from xxx.xxx.xxx.xxx

Replace xxx.xxx.xxx.xxx with any IP address that you want to grant
 access to your website. You can have multiple allow fromlines so add
 as many IP addresses as you need. This allows access to
your website only if you are using an IP address defined here.

Php Session Security-Internet Security

Because a session may contain sensitive information, you need to treat
 the session as a possible security hole. Session security is necessary to
 create and implement a session. If someone is listening in or snooping
 on a network, it's possible that he can intercept a session ID and use
 it to look like he is someone else. It's also possible to access session
 data from the local filesystem on multiuser systems such as ISP hosting machines.

Session hijacking is when someone accesses either a client's cookie
 or session ID, and then attempts to use this data. Session fixation
 is attempting to set your own session ID. Session fixation and
hijacking are easy to combat. We'll make use of the super global
variables for the client's IP address and browser type to keep things secure.


<?php
session_start();
$user_check = md5($_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']);
if (empty($_SESSION['user_data'])) {
session_regenerate_id();
echo ("New session, saving user_check.");
$_SESSION['user_data'] = $user_check;
}
if (strcmp($_SESSION['user_data'], $user_check) !== 0) {
session_regenerate_id();
echo ("Warning, you must reenter your session.");
$_SESSION = array();
$_SESSION['user_data'] = $user_check;
}
else {
echo ("Connection verified!");
}
?>

we stored the encoded combination of the IP address and
browser type. That way, when the user returns to this page,
we can compare the value stored in the session versus a fresh
 computation of the IP address and browser type. If the two
 don't match, we potentially have a hijacker, so we pick a new
 ID and clear out any saved data for that session. That way,
 the hijacker cannot retrieve any of the private information
stored in the session. This doesn't cause a problem for
legitimate users, because they aren't going to change browser
 or IP addresses in the middle of a session with your web site.




Building Dynamic Images-PHP

You want to create an image based on a existing image
 template and dynamic data typically text).
 For instance, you want to create a hit counter.

Load the template image, find the correct position to properly center
 your text, add the text to the canvas, and send the image to the browser:

// Configuration settings
$image    = ImageCreateFromPNG('button.png');
$text     = $_GET['text'];
$font     = ImagePSLoadFont('Times');
$size     = 24;
$color    = ImageColorAllocate($image,   0,   0,   0); // black
$bg_color = ImageColorAllocate($image, 255, 255, 255); // white

// Print centered text
list($x, $y) = pc_ImagePSCenter($image, $text, $font, $size);
ImagePSText($image, $text, $font, $size, $color, $bg_color, $x, $y);

// Send image
header('Content-type: image/png');
ImagePNG($image);

// Clean up
ImagePSFreeFont($font);
ImageDestroy($image);

Building dynamic images with GD is easy; all you need to do is combine
 a few recipes together. At the top of the code in the Solution, we
load in an image from a stock template button; it acts as the background
 on which we overlay the text. We define the text to come directly from
 the query string. Alternatively, we can pull the string from a database
 in the case of access counters or a remote server stock
 quotes or weather report icons.


<?php
if (isset($_GET['button'])) {

    // Configuration settings
    $image    = ImageCreateFromPNG('button.png');
    $text     = $_GET['button'];      // dynamically generated text
    $font     = ImagePSLoadFont('Times');
    $size     = 24;
    $color    = ImageColorAllocate($image,   0,   0,   0); // black
    $bg_color = ImageColorAllocate($image, 255, 255, 255); // white

    // Print centered text
    list($x, $y) = pc_ImagePSCenter($image, $text, $font, $size);
    ImagePSText($image, $text, $font, $size, $color, $bg_color, $x, $y);

    // Send image
    header('Content-type: image/png');
    ImagePNG($image);



    // Clean up
    ImagePSFreeFont($font);
    ImageDestroy($image);

} else {
?>
<html>
<head>
    <title>Sample Button Page</title>
</head>
<body>
    <img src="<?php echo $_SERVER['PHP_SELF']; ?>?button=Previous"
         alt="Previous" width="132" height="46">
    <img src="<?php echo $_SERVER['PHP_SELF']; ?>?button=Next"
         alt="Next"     width="132" height="46">
</body>
</html>
<?php
}
?>
If a value is passed in for $_GET['button'], we generate
 a button and send out the PNG. If $_GET['button'] isn't set, we print
 a basic HTML page with two embedded calls back to the script with
 requests for button images — one for a Previous button and one for
 a Next button. A more general solution is to create a separate
 button.php page that returns only graphics and set the image
source to point at that page.


MySQL with php

The basic steps of performing a query, whether using the mysql
command-line tool or PHP, are the same:

Connect to the database.

Select the database to use.

Build a SELECT statement.

Perform the query.

Display the results.



When connecting to a MySQL database, you will use two
 new resources. The first is the link identifier that holds all
of the information necessary to connect to the database for
an active connection. The other resource is the results resource.
It contains all information required to retrieve results from an
active database query's result set.


<?php
$db_host='hostname of database server';
$db_database='database name';
$db_username='username';
$db_password='password';

$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}

$db_select = mysql_select_db($db_database);
?>

Building a SQL query is as easy as setting a variable to the
string that is your SQL query. Of course, you'll need to use a
valid SQL query, or MySQL returns with an error when you
execute the query. The variable name $query is used, but you
can choose anything you'd like for a variable name.
The SQL query in this example is
SELECT * FROM tbl.




Sorting Arrays-PHP


PHP supports a variety of ways to sort an array when 
I say sort, I am referring to an alphabetical sort if it is a string,
 and a numerical sort if it is a number. When sorting an array, 
you must keep in mind that an array consists of several pairs 
of keys and values. Thus, an array can be sorted based upon
 the values or the keys. Also, you can sort the values and keep 
the corresponding keys matched up or sort the values and 
have them receive new keys.
To sort the values, without regard to the keys, 
you use sort(). 
 To sort these values again without regard to the keys,
 in reverse order, you use rsort(). 
The syntax for every sorting function is like this:

function($Array);
So, sort() and rsort() are simply:
sort($Array);
rsort($Array);
 
To sort the values, while maintaining the correlation
 between the value and its key, you use asort(). 
To sort them in reverse, while maintaining the key
 correlation, you use arsort().
To sort by the keys, while still maintaining the correlation
 between the key and its value, you use ksort(). 
Conversely, krsort() will sort the keys in reverse.
Last, shuffle() randomly reorganizes the order of an array.

As an example of sorting arrays, you'll create a list of students
 and the grades they received on a test, then sort this list first
 by grade then by name.

Create the array:
 
$Grades = array(
"Richard"=>"95",
"Sherwood"=>"82",
"Toni"=>"98",
"Franz"=>"87",
"Melissa"=>"75",
"Roddy"=>"85"
);


 Print a caption and then print each element of 
the array using a loop.

print ("Originally, the array looks
 like this:<BR>");
for ($n = 0; $n < count($Grades);
 $n++) {
   $Line = each ($Grades);
   print ("$Line[key]'s grade is
 $Line[value].<BR>\n");
}


Sort the array in reverse order by values to determine 
who had the highest grade.

arsort($Grades);
 
Because you are determining who has the highest 
grade, you need to use arsort() instead of asort(). 
The latter, which sorts the array by numeric order, would 
order them 75, 82, 85, etc. and not the desired 98, 95, 87, etc.

php-Dynamic Variables

Sometimes it is useful to set and use variables dynamically. 
Normally, you assign a variable like this: 

$var = "hello";
 
Now let's say you want a variable whose name is the 
value of the $var variable. You can do that like this:

$$var = "World";
 
PHP parses $$var by first dereferencing the innermost 
variable, meaning that $var becomes "hello". The 
expression that's left is $"hello", which is just $hello.
 In other words, we have just created a new variable 
named hello and assigned it the value "World"
You can nest dynamic variables to an infinite level in 
 PHP, although once you get beyond two levels, it 
can be very confusing for someone who is trying to read your code.
There is a special syntax for using dynamic variables, and 
any other complex variable, inside quoted strings in PHP: 

echo "Hello ${$var}";
 
This syntax also helps resolve an ambiguity that occurs when
 variable arrays are used. Something like $$var[1] is 
ambiguous because it is impossible for PHP to know which
 level to apply the array index to. ${$var[1]} tells 
PHP to dereference the inner level first and apply the 
 array index to the result before dereferencing the outer level.
 ${$var}[1], on the other hand, tells PHP to apply the index
 to the outer level.
Initially, dynamic variables may not seem that useful, but there
 are times when they can shorten the amount of code you need 
to write to perform certain tasks. For example, say you have 
an associative array that looks like: 

$array["abc"] = "Hello";
$array["def"] = "World";
 
Associative arrays like this are returned by various functions
 in the PHP modules. mysql_fetch_array() is one example.
 The indices in the array usually refer to fields or entity names 
within the context of the module you are working with. It's
 handy to turn these entity names into real PHP variables, 
so you can refer to them as simply $abc and $def

security to POST-PHP

$_POST
 POST-method variables. Form field data from regular 
POST-method forms.
 
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. 

mysqli_real_escape_string can be add for security reson.

A common error people make when using sessions is that they
 tend to use it as a replacement for authentication -- or sometimes 
as an add-on to authentication. Authenticating a user once as he
 first enters your site and then using a session ID to identify that 
user throughout the rest of the site without further authentication 
can lead to a lot of problems if another person is somehow able
 to get the session ID. There are a number of ways to get the 
 session ID:
  • If you are not using SSL, session IDs may be sniffed
  • If you don't have proper entropy in your session IDs,
     they may be guessed
  • If you are using URL-based session IDs, they may 
    end up in proxy logs
  • If you are using URL-based session IDs, they may 
    end up bookmarked on publicly-accessible computers
Forcing HTTP Authentication on each page over SSL is the
 most secure way to avoid this problem, but it tends to be a 
bit inconvenient. Just keep the above points in mind when 
building a web application that uses sessions to store users' 
personal details.

PHP Expressions

An expression is the basic building block of the language.
 Anything with a value can be thought of as an expression. 
Examples include:
5
5+5
$a
$a==5
sqrt(9)
By combining many of these basic expressions, you can
 build larger, more complex expressions.
Note that the echo statement we've used in numerous 
examples cannot be part of a complex expression because
 it does not have a return value. The print statement, on
 the other hand, can be used as part of complex expression
 -- it does have a return value. In all other respects, echo 
and print are identical: they output data.

Expressions are combined and manipulated using operators.

The control structures in PHP are very similar to those
 used by the C language. Control structures are used to 
control the logical flow through a PHP script. PHP's control 
structures have two syntaxes that can be used interchangeably. 
The first form uses C-style curly braces to enclose statement 
 blocks, while the second style uses a more verbose syntax 
that includes explicit ending statements. The first style is 
preferable when the control structure is completely within 
a PHP code block. The second style is useful when the 
construct spans a large section of intermixed code and 
HTML. The two styles are completely interchangeable, 
however, so it is really a matter of personal preference 
which one you use. 

The if statement is a standard conditional found in most languages.
 Here are the two syntaxes for the if statement:
if(expr) {            if(expr):
  statements            statements
} elseif(expr) {      elseif(expr):
  statements            statements
} else {              else:
  statements            statements
}                     endif;
The if statement causes particular code to be executed if
 the expression it acts on is true. With the first form, 
you can omit the braces if you only need to execute a 
single statement.


how Installing mod_rewrite localhost

If you’ve installed Apache yourself, read on. Because of its
 popularity, mod_rewrite is now included with all common
 Apache distributions. If desired, you can verify if your Apache installation has the
mod_rewrite module by looking for a file named
mod_rewrite.sounder the modulesfolder in your
Apache installation directory.

However, mod_rewrite may not be enabled by default
 in your Apache configuration. To make sure,open the
Apache configuration file, named httpd.conf. If you’ve
 installed Apache using the XAMPP
the full path of the file will be
\Program Files\xampp\apache\conf\httpd.conf.
Open httpd.confand find the following line:
#LoadModule rewrite_module modules/mod_rewrite.so
The leading #means the line is commented, so remove it
 in order to have Apache load the mod_rewrite
module upon its startup:
LoadModule rewrite_module modules/mod_rewrite.so

After any change to httpd.conf, you need to restart the
 Apache server in order for the changes to take
effect. In case you run into trouble, you can check
Apache’s error log file (/logs/error.log), which
should contain the details of the error.

Once mod_rewrite is installed and enabled, you
add the rewriting rules to the Apache configuration
file, httpd.conf. Apache also lets you save configuration
 options including rewriting rules on a
per-directory basis to a configuration file named .htaccess.
 All you have to do is create a file named .htaccessinto a
 directory of your application, and Apache will read it
automatically when accessing that directory.

PHP while Loop

PHP while Loop with code


while - loops run  a set of code as  the  condition is true.

Basic Syntax
while (condition)
{
    code for executed;
}

<?php
$k=1;

while($k<=5) {
  echo "The number is: $k <br>";
  $k++;
}
?>

$k start with 1 and run 5 times as the k++
It continues to loop through the code  until the condition becomes false.

var_dump and print_r -PHP-standard

Functions like var_dump and print_r are also invaluable when debugging

var_dump

var_dump functions displays information about variables in a simple, readable 
format. This function is very useful when debugging—providing a simple
 and easy way to display the current contents of one or more variables.

For simple scalar variables such as booleans, integers, strings, and doubles,
 the type of the variable is printed, followed by an opening bracket, the value
 contained in the variable, and a closing bracket.

Arrays are printed as a list of keys and values, and have their type array
 printed at the top of the list.

print_r

print_r displays information about a variable in a format meant to
 be easily understandable by humans. It is often used for debugging—
providing a simple and easy way to display the current contents of a variable.
 However, var_dump provides more complete information and allows
 for the use of multiple arguments.
For simple scalar variables, such as booleans, integers, strings, 
and doubles, the value contained in the variable is printed.

If print_r is used on a data structure that is a reference to itself, 
the function enters a recursive loop—generating the same information
 repeatedly until the script times out or the user cancels the script.

Visualize Traffic with DIY Vector

you will learn how to create your own traffic chart using the incredibly cool Canvas framework, which can produce vector graphics and animations with a little bit of HTML and JavaScript. All code referenced in this hack is also available in a single zip file at http://blogoscoped.com/googleappshacks/canvas.zip. Although setting up Canvas may take a little longer than using, say, the Google Charts API  it's also much more flexible, and can even include animated charts.

Draw Something Using Canvas

Canvas is a vector graphics framework which works in most popular browsers today including Firefox, Opera and Safari, and does not require a plug-in like Flash does. Internet Explorer too can render Canvas code, at least with a little tweak you'll see further below. Canvas can be used to have a web page show 2D and 3D drawings, games, charts, applications, animations, and much more.

A longer canvas tutorial is available at http://developer.mozilla.org/en/docs/Canvas_tutorial (explaining how to draw rectangles, curves, imported images, and much more), but let's just see what you need to draw a simple line. First, create a file named index.html and open it with a plain text editor. Create a basic page like the following;

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; CHARSET=UTF-8" />
  <title>Drawing a line</title>
</head>
<body>
  <h1>Soon, a line will appear!</h1>
</body>
</html>

       

So far, that's all plain XHTML. Now somewhere in the <body> of the page, put the canvas tag:

Next, create a default.js file containing the following JavaScript, and put it in the same folder as index.html:
function main() {
    // grab the canvas
    var canvas = document.getElementById('picture');
    var ctx = canvas.getContext('2d');

    // set the color and line width
    ctx.strokeStyle = 'rgba(40,200,180,1)';
    ctx.lineWidth = 8;

    // draw a line
    ctx.beginPath();
    ctx.moveTo(40, 140);
    ctx.lineTo(240, 40);
    ctx.stroke();
}

That's not a lot of code—you're grabbing the canvas element using the ID you defined

URL rewriting-various exercises-seo

 Installing mod_rewrite
 Testing mod_rewrite
 Working with regular expressions
 Rewriting numeric URLs with two parameters
 Rewriting keyword-rich URLs
 Building a link factory
 Pagination and URL rewriting
 Rewriting images and streams

If you’ve installed Apache yourself, read on. Because of its popularity, mod_rewrite is now included
with all common Apache distributions. If desired, you can verify if your Apache installation has the
mod_rewrite module by looking for a file named mod_rewrite.sounder the modulesfolder in your
Apache installation directory.
However, mod_rewrite may not be enabled by default in your Apache configuration. To make sure,
open the Apache configuration file, named httpd.conf.

Once mod_rewrite is installed and enabled, you add the rewriting rules to the Apache configuration
file, httpd.conf.

You use this to have mod_rewrite translate my-super-product.htmlto product.php?product_id=123.
The linethat precedes the RewriteRuleline is a comment.
# Translate my-super.product.html to /product.php?product_id=123
RewriteRule ^my-super-product\.html$ /product.php?product_id=123
You can find the official documentation for RewriteRuleat http://www.apacheref.com/
ref/mod_rewrite/RewriteRule.html.
In its basic form, RewriteRuletakes two parameters. The first parameter describesthe original URL that
needs to be rewritten, and the second specifies what it should be rewritten to. The pattern that describes the
original URL is delimited by ^and $, which assert that the string has nothing before or after the matching
text (explained further in the following sections), and its contents are written using regular expressions,
which you learn about next.

Using RewriteBase

The regular expressions and scripts in this book assume that your application runs in
the root folder of their domain. This is the typical scenario. If, however, you host your
application in a subfolder of your domain, such as
http://www.example.com/seophp, you’d need to make a few changes to accommodate 
the new environment.

The most important change would be to use the RewriteBasedirective of mod_rewrite
to specify the new location to act as a root of your rewriting rules. This directive is
explained at http://www.apacheref.com/ref/mod_rewrite/RewriteBase.html.
Also, the rewritten URL should lose its leading slash, because you’re not rewriting to
root any more. Basically, if you host your first example in a subfolder named seophp,
your .htaccessfile for the previous exercise should look like this:

RewriteEngine On
RewriteBase /seophp
RewriteRule ^my-super-product\.html$ product.php?product_id=123

RewriteRule command and its parameters must be written on a single line in
your .htaccessfile. If you split it in two lines as printed in the book, you’ll get a 500 error from the
web server when trying to load scripts from that folder.

How to Enable mod_rewrite at Server

mod_rewrite may not be enabled by default in your Apache configuration. To make sure,
open the Apache configuration file, named httpd.conf.
The full path of the file will be \Program Files\xampp\apache\conf\httpd.conf.

Open httpd.conf and find the following line:
#LoadModule rewrite_module modules/mod_rewrite.so
The leading #means the line is commented, so remove it in order to have Apache load the mod_rewrite
module upon its startup:

LoadModule rewrite_module modules/mod_rewrite.so

After any change to httpd.conf, you need to restart the Apache server in order for the changes to take
effect. In case you run into trouble, you can check Apache’s error log file /logs/error.log, which
should contain the details of the error.

Once mod_rewrite is installed and enabled, you add the rewriting rules to the Apache configuration
file, httpd.conf. Apache also lets you save configuration options (including rewriting rules) on a
per-directory basis to a configuration file named .htaccess. All you have to do is create a file named
.htaccessinto a directory of your application.

what is CodeIgniter Helpers?

Helpers, as their name implies, help you with specific tasks. Unlike libraries, helpers are not object -oriented but procedural in nature. Each helper contains one or more functions, each focusing on a
specific task, with zero dependence on other functions.

Helpers can either be loaded locally or autoloaded in /system/application/config/autoload.php.

CodeIgniter's  helpers:

Array —  The   Array helpercontains functions that help you work with arrays. For example, the
random_element()function takes an array as input and returns a random element from it.

Cookie —  The   Cookie helpercontains functions that help you set, read, and delete cookie data.

Date —  The   Date helpercontains functions that help you work with dates. For example, the
now function returns the current time as a UNIX time stamp.

Directory —  The   Directory helpercontains a single function that helps you work with directories.
For example, the directory_mapfunction reads a specified directory path and builds an array
of it that contains all of its files and subdirectories.


Download —  The   Download helpercontains a single function that helps you download data
easily. The force_download()function generates server headers that force data to be
downloaded instead of viewed in a browser.

File —  The   File helpercontains functions that help you read, write, and delete files.

Form —  The   Form helpercontains functions that help you build forms. It is probably one of the
most used helpers in the CodeIgniter toolbox.

HTML —  The   HTML helpercontains functions that help you create HTML blocks quickly and
easily. For example, the ul()function can turn an array of items into a bulleted list.

Inflector —  The   Inflector helpercontains functions that help you to turn words into plural or
singular form, to apply camel case, or to turn words separated by spaces into an underscored
phrase.

Security —  The   Security helpercontains security - related functions like xss_clean(),  which
filters out any code that may be used in a cross site scripting hack.

Smiley —  The   Smiley helpercontains functions that help you manage emoticons. The functions
in this helper might seem superfluous, but become invaluable if you are coding a bulletin board
or chat application.

String —  The   String helpercontains functions that help you work with strings, like the random_
string  function, which as its name implies, creates random strings based on type and length
arguments.

Text —  The   Text helpercontains functions that help you work with text. For example, the word_
limiter function can limit a string to a certain number of words, which is useful if you ’ re
trying to limit user input on a form.

Typography —  The   Typography helpercontains a single function that helps you format text in
appropriate ways. For example, the auto_typography()function wraps paragraphs with < p >
and < /p > , converts line breaks to < br/ > , and converts quotes, dashes, and ellipses properly.

PHP, you can use the substr()function instead of the word_limiter or character_limiter
made available by the Text helper. Certainly, you ’ re not forced to use helpers, but they ’ re made available
to you, and they do a fine job of saving time and effort.


codeigniter routes page

The  routes.php filelets you remap URI requests to specific controller functions. For example, you may
have a controller named sitewith a function named index. The URI for this controller/function
combination might be:
http://www.example.com/site/index
Furthermore, if your site controller had a pagesfunction that accepted a numeric ID for database
lookup, the URI might look like this:
http://www.example.com/site/pages/4
In some cases, you might want to remap one or more of these default routes. For example, the second
example might be better displayed as this:
http://www.example.com/about_us/
In that case, your routes.php file would contain a rule like this:
$route[‘about_us’] = “site/pages/4”;
For right now, though, this kind of manipulation falls under “ advanced  usage, ”  so  don ’ t  worry  too  much
about it. However, please do note that this kind of thing is possible. Also, be aware that two “ reserved
routes ” exist: default_controller and scaffolding_trigger.
$route[‘default_controller’] = “welcome”;
The default_controller route tells CodeIgniter which controller should be loaded if no controller is
identified. For simplicity ’ s sake, keep this setting.

CodeIgniter Libraries

CodeIgniter libraries help you do your job faster and more efficiently. Each libraryis really a PHP class
with various methods that you can use once the library is loaded by a controller.

CodeIgniter gives  the following libraries:
Benchmarking —  The   Benchmarking libraryis always active. Use it to determine the time
difference between any two marked points in code and to calculate memory usage.

Calendaring —  The   Calendaring librarymust be loaded by a controller. Use it to dynamically
create calendars for given months and years, with some control over formatting and appearance.

Config —  The   Config libraryis initialized automatically by the system. Use it to retrieve
configuration information.

Database —  The   Database libraryis a very powerful set of methods that must be loaded. You ’ ll
be using this library so much that the next subsection of this chapter focuses on it exclusively.

Email —  The   Email librarymust be loaded. It includes a very powerful set of tools that simplifies
the job of sending e - mails.

Encryption —  The   Encryption librarymust be loaded. It provides you with powerful two - way
encryption methods.

File Uploading —  The   File Uploading librarymust be loaded. Use this library whenever you need
to handle file uploads. It includes powerful validation features that can restrict a file by mime
type, size in kilobytes, or even image dimensions.

FTP —  The   FTP librarymust be loaded. Use this library to transfer files to a remote server only
standard FTP is supported, by the way.

HTML Table —  The   HTML Table librarymust be loaded. Use this very versatile library to
autogenerate HTML tables from arrays or database result sets.

Image Manipulation —  The   Image Manipulation librarymust be loaded. Use it to resize images,
create thumbnails, crop or rotate images, and watermark images. Some functions require further
PHP support such as GD/GD2.

Input and Security —  The   Input and Security librarymust be loaded. Use it to pre - process  input
data from forms and URLs and to handle some security functions such as guarding against
XSS attacks.

Language —  The   Language librarymust be loaded. Use this library to load different sets of
language files for internationalization.

Loader —  The   Loader libraryis automatically loaded. You will use this library primarily to load
views with your controller, but it is also used to load libraries.

Output —  The   Output libraryis automatically loaded. This library has one main function: Send
the finalized web page to the requesting browser. It is also used for caching.

Pagination — The  Pagination librarymust be loaded. Use this labor - saving library to paginate
database results for performance and usability. You can control how many records to display per
page, how many records to pull from the database, and the look and feel of different parts of the
pagination.

Session —  The   Session librarymust be loaded. Use CodeIgniter ’ s Session library to maintain
state information about a user. This library does not use PHP ’ s  built - in  sessions  —  instead,  it
generates its own session data. Because this library is so important, a separate subsection of this
chapter is devoted to it.

PHP-MySQL application Security

With these two methods, there’s no longer any need to ever use GET for requests internal to an application.
You may still need it for external requests, to other applications and web sites that aren’t coded to look for their
parameters as POST data, but you can’t do anything about them.
Of course, I also should mention that there’s not much security in POST unless you’re also using SSL
Hash the passwords with Phpass.
Store the hashed passwords in the database, protected to the extent possible.   
Use 2FA.Prevent SQL injection with parameterized queries.   
Prevent XSS by escaping all user-originated output.    
Prevent CSRF with a csrftoken. 

Prevent clickjacking with an  
X-Frame-Optionsheader.
Use POST rather than GET.

Use SSL.

 Submitting Requests with POST

Submitting requests with POST instead of GET makes it just a bit harder
 for an attacker to break in, since JavaScript has to be used and easy tricks like
 coding a request in an image srcattribute won’t work. POST also prevents data like
a csrftoken from accidentally getting e-mailed or posted on a social site.

The only requests that should use GET are those that don’t do anything
 other than to display a page. Indeed, RFC 2612, the official specification for HTTP,
 says “the convention has been established that the GET and HEAD methods
SHOULD NOT have the significance of taking an action other than retrieval.
  It’s not disallowed, just discouraged. But you should act like it’s disallowed.
   

Manage Databases on a Server by php

MySQL-related functions.

  • mysql_list_dbs() Used to list the databases on a MySQL server.
  • mysql_num_rows() Returns the number of rows in a result set.
  • mysql_tablename() Despite its name, can extract the name of a table or a database from a result.
The goal of this script is to list all the databases on the local MySQL server.
  1. Open a new file in your text editor and start a PHP block:
    <?
    
  2. Create a variable to hold the result of the mysql_connect() function. Include the @ to suppress warnings, as well as the die() function to cause the script to end and a message to display if the connection fails:
    $connection = @mysql_connect("localhost", "spike", "9sj7En4")
    or die(mysql_error());
    
    
  3. Create a variable to hold the result of the mysql_list_dbs() function. Include the @ to suppress warnings, as well as the die() function to cause the script to end and a message to display if the script can't get the list:
    $dbs = @mysql_list_dbs($connection) or die(mysql_error());
     
    The only argument necessary for the mysql_list_dbs() function is the link identifier for the current connection.

    1. You'll be looping through a result and dynamically populating a bullet list. Start that bullet list outside the loop:
      $db_list = "<ul>";
      
    2. Start a counter. You'll need it for your loop:
      $i = 0;
      
    3. Begin a while loop. This loop will continue for as long as the value of $i is less than the number of rows in the $dbs result value:
      while ($i < mysql_num_rows($dbs)) {
      
    4. Once you're within the while loop, get the name of the database reflected in the current row of the result:
      $db_names[$i] = mysql_tablename($dbs, $i); 
       
      1. The variable $i is replaced by its value, so during the first loop this line would be something like $db_names[0] = mysql_tablename($dbs, 0);
        Counting starts at 0, not 1, so this would reflect the first row in the result. As the counter increments, so does the row number.
      2. Add the current database name to the bullet list:
        $db_list .= "<li>$db_names[$i]";
        
      3. Increment your count before you close the while loop:
        $i++;
        
        
      4. Close the while loop, the bullet list, and your PHP block:
        }
        $db_list .= "</ul>";
        ?>
        
       

     


HTTP Request Methods-PHP



HTTP Request Methods The Internet’s HTTP protocol, commonly used to fetch Web pages, defines a number of “methods” that browsers can use to send requests and data to Web servers. Of the available methods, the two most important are the GET method and the POST method.
GET is the “default” method for the Internet, used whenever you request a page with your browser. All data in the request must be encoded in the URL.

POST is most often used for submitting forms. It allows additional form data to be sent with the request. HTML lets you specify the method to use for each formtag. Although GET is the default, it is most common to use POST, which avoids cluttering the URL with the submitted data.


Use the POST method when declaring your form in HTML. This prevents
form values from appearing in the URL, and allows a larger amount of data
to be submitted through the form.

Use PHP’s htmlspecialcharsfunction when populating form fields with
PHP values, to avoid malformed HTML.
PHP has its own wrappers for Curl, so we can use the same tool from within
PHP. A simple GETrequest looks like this:
<?php
$url = "http://oreilly.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

?>
The previous example is the simplest form, setting the URL, making a request to its
location (by default this is a  GET  request), and capturing the output. Notice the use of
curl_setopt(); this function is used to set many different options on Curl handles and
it has excellent and comprehensive documentation on http://php.net. In this example,
it is used to set the  CURLOPT_RETURNTRANSFERoption to  true, which causes Curl to  return
the results of the HTTP request rather than  outputthem. In most cases, this option
should be used to capture the response rather than letting PHP echo it as it happens.
We can use this extension to make all kinds of HTTP requests, including sending custom
headers, sending body data, and using different verbs to make our request.
If you use normal HTTP, form data will be sent in “clear text” over the Internet
from the browser to the server. This means it can be intercepted by someone
using a packet sniffer. When you send confidential information such as financial details,
 use an encryption technology such as SSL.

<?php
$url = "http://requestb.in/example";
$data = array("name" => "Lorna", "email" => "lorna@example.com");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

?>
Again,  curl_setopt()is used to control the various aspects of the request we send.
Here, a POSTrequest is made by setting the CURLOPT_POSToption to 1, and passing the
data we want to send as an array to the  CURLOPT_POSTFIELDSoption. We also set a
Content-Typeheader, which indicates to the server what format the body data is in; the
various headers

Assuming magic quotes is disabled on your server, and you have no other measures
in place to prevent it, this clever attack alters the meaning of the query:
SELECT * FROM users
WHERE username='' AND password='' OR username LIKE '%'

The modified query will select allrecords in the user table! When the script checks
whether any users matched the supplied user name and password combination,
it will see this big result set and grant access to the site

This can be prevented if we escape the incoming variables:

$sql = "SELECT * FROM users
WHERE username='" . safeEscapeString($_POST['username']). "'
AND password='" . safeEscapeString($_POST['password']). "'";
In some cases, depending on the circumstances, this may not be necessary.