Posted by: antervedi | December 30, 2008

MVC

MVC Architecture in PHP

MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP. View is basically the user interface. Controller is the logic that operates everything in between.

MVC and PHP development

The Model

The MVC structure is meant for reasonably-sized applications, using object-oriented coding. The Model part, in a PHP app, would usually be a class (or multiple classes). Fairly often, the class is a representation of a table you store in the database — member variables are the data columns, and member methods are operations that can be done. As an example, you might have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.

Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available — what can you do to the data in the database. I thought I should just clarify (if it wasn’t clear already) — this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value. (It’s fairly basic programming practices, but you’d be surprised how many web apps programmers didn’t graduate with a CS degree..)

Here’s an example of the Model part of your code. Of course, there will be many more classes in a real application. This is just the code is the simplest form, without a lot of the details.

class User
{
   var $username;
   var $password;
   var $email;
   function User($u, $p, $e) // constructor
   {
      $this->username = $u;
      $this->password = $p;
      $this->email = $e;
   }
   function create()
   {
      // creates user in the db
   }
   function login()
   {
      // checks against db, does login procedures
   }
   static function authenticate($u, $p)
   {
      // checks against db
   }
   function logout()
   {
      // does logout procedures
   }
}

The View

The View, in the simplest words, is the user interface. However, it doesn’t mean it would be just straight HTML. Minimal PHP logic will need to be used in your application’s interface a lot of times. For example, if you were to have the main logged-in page say, “Hello, [username]!” You would certainly need some PHP code to handle that, right? That is all part of the View. Of course, all the CSS, Javascript would be part of this too.

It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional “action” code belongs to the View — that is the Controller’s job, which we’ll see next.

This was easy to understand, but for clarification’s sake, let’s see an example anyway. Of course, the following isn’t even valid XHTML 1.0 (it lacks a DOCTYPE, for instance), but this is just an example.

<?php
require_once('User.php');
// makes sure user isn't already logged in
if (User::authenticate($_COOKIE['username'], $_COOKIE['password']))
{
   header(”Location:/main.php”);
   exit();
}
?>
<html>
<head><title>Please login</title></head>
<body>
<h1>Login</h1>
<?
if ($_GET['error'] == 1)
{
   echo ‘Login incorrect. Please try again.<br />’;
}
?>
<form action=”login_action.php” method=”post”>
User: <input type=”text” name=”username” /><br />
Pass: <input type=”password” name=”password” /><br />
<input type=”submit” value=”Login” />
</form>
</body>
</html>

The Controller

Sometimes it is confusing to understand what the Controller needs to do, if you weren’t working on an actual application and just reading a book/an article. It would seem like the Model and the View are all you need. So let’s go back to a concrete PHP example.

Now imagine you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you’re using AJAX) You don’t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won’t do anything. You certainly don’t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.

This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).

Some developers fall into the temptation to display outputs from the Controller, because it’s convenient. Imagine, if you had a login form, how easy is it to just print “Login incorrect” directly from the Controller PHP code? (assuming you aren’t using AJAX, for this particular example) It is an option, and I will tell you that many scripts do just that. However, to truly utilize a MVC structure’s advantage, the Controller (like the Model) should not display any HTML outputs, but rather use redirection. You may use cookies/sessions, database storage, flat file caching, or query string to the View file to store the states of your application; and then you should always let the View take care of displaying outputs, using these stored states.

Now let’s see an example of a Controller code.

<?php
require_once('User.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser->login())
{
   // set cookies for login info
   header(”Location:/main.php”);
   exit();
}
else
{
   header(”Location:/login.php?error=1″);
   exit();
}
?>

Conclusion

Using the MVC structure, code becomes a lot easier to understand. For other developers to join in to understand your code, as well as for yourself in the future when you come back to it after a while. Development is also a lot easier because you know exactly where to look for what piece of code. If you were going to change some message displaying in the interface, you only need to go to the View. If your database structure sees a change, such as passwords now encrypting in a different way, you only need to change your Model. The MVC architecture is very powerful and makes your object-oriented web apps development a lot more efficient.

Posted by: antervedi | December 30, 2008

What is PHP


PHP: PHP is a powerful server-side scripting language for creating dynamic and interactive websites.

Array: An array can store one or more values in a single variable name.

  • Numeric array – An array with a numeric ID key
  • Associative array – An array where each ID key is associated with a value
  • Multidimensional array – An array containing one or more arrays

Foreach: For each item in the specified array execute this code. For Each loop will continue until it has gone through every item in the array.

Function: A function is a block of code that can be executed whenever we need it.

Get: The $_GET variable is used to collect values from a form with method=”get”. Information sent from a form with the GET method is visible to everyone and it has limits on the amount of information to send (max. 100 characters).

Post: The $_POST variable is used to collect values from a form with method=”post”. Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

Include: The include() function takes all the text in a specified file and copies it into the file that uses the include function.

Cookies: A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Session: A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

PHP Error Handling: We will show different error handling methods:

1. Simple “die()” statements 2. Custom errors and error triggers 3 Error reporting

Exception: Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

Primary Key: The primary key of a relational table uniquely identifies each record in the table. PRIMARY KEY is used as a unique identifier for the rows.

Foreign Key: These keys are used to create relationships between tables.

Primary key and Unique Key: Differences:

Primary key and unique are Entity integrity constraints

Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered.

Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values. (In oracle, one null is not equal to another null).

1)unique key can be null but primariy key cant be null.

2)primariy key can be refrenced to other table as FK.

3)we can have multiple unique key in a table but PK is one and only one.

4)PK in itself is unique key.

Joins: A join operation matches records in two tables. The two tables must be joined by at least one common field. That is, the join field is a member of both tables. Typically, a join operation is part of a SELECT query.

1.How do I generate a random number from php?

Ans: srand((double)microtime()*1000000);

echo rand(0,100);

2. which is faster mysql_unbuffered_query or mysql_query ?

Ans: when we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query.

3. What is meant by Persistent Database Connections?

Ans: Difference between the regular Mysql connection and Persistent connection

$con=mysql_connect( \”hostname \”, \”user \”, \”pwd \”);

It will be closed when we call mysql_close($con) or PHP scripts stops execution.

$con=mysql_pconnect( \”hostname \”, \”user \”, \”pwd\”);

It will not be closed when we call mysql_close($con) or PHP scripts stops execution. It is useful when we are dealing with large application or accessing multiple data or information continuously. if we like to continue our database connection we will have to use mysql_pconnect() function.

1) What are the differences between Get and post methods in form submitting, give the case where we can
use get and we can use post methods?

Ans : When you want to send short or small data, not containing ASCII characters, then you can use “GET”
Method. But for long data sending say more then 100 character you can use “POST” method. Once most imp diff is when you are sending the form with “Get” method. You can see the output which you are sending in the ddressbar. Whereas if you send the form with “POST” method then user can not see that information.

3) How can we submit a form without a submit button?

Ans : I can submit a form in many ways, for e.g.
1. When user click on checkbox, or drop down
2. When user click on radio button
3. At the end of the form I will type “Click here to submit” & link text to the processing file
————————————————–
5) What is the difference between mysql_fetch_object and mysql_fetch_array?

Ans :
Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference isinsignificant). mysql_fetch_object() is similar to mysql_fetch_array(), with one difference – an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

9) What are the differences between require and include, include_once?
ANS :
include() & require() – includes the file during the execution of the script. but is there is any problem include() generate a warning message where as require() generates the fatal error. include_once() & require_once() – same as include() and require() but if file is already included then does not produce any error or not include that file again

1. WHAT IS THE DIFFERENCE BETWEEN GET & POST?

Get is an Idompotent method. (Idompotent: The side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property.)”GET” is basically for just getting (retrieving: quering db for data & retriving) data whereas “POST” may involve anything, like storing or updating data, or ordering a product, or sending E-mail. In GET form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. For GET in IE, Maximum URL Length Is 2,083 Characters in Internet Explorer (Q208427) or approximatly 1k.

9. WHAT ARE THE DIFFERENCES BETWEEN REQUIRE AND INCLUDE, INCLUDE_ONCE?

All three are used to an include file into the current page. It is faster than include().
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.

12. FUNCTIONS IN IMAP, POP3 AND LDAP?

imap_body — Read the message body
imap_check — Check current mailbox
imap_delete — Mark a message for deletion from current mailbox
imap_mail — Send an email message

21. DIFFERENCE BETWEEN HTMLENTITIES() AND HTMLSPECIALCHARS()]

htmlspecialchars : Convert some special characters to HTML entities (Only the most widley used)
htmlentities : Convert ALL special characters to HTML entities

25. HOW CAN WE GET THE PROPERTIES (SIZE, TYPE, WIDTH, HEIGHT) OF AN IMAGE USING PHP IMAGE FUNCTIONS?

getimagesize — Get the size of an image
image_type_to_extension — Get file extension for image type
imagesx — Get image width
imagesy — Get image height

29. OPTIMISING QUERIES

First, one thing that affects all queries: The more complex permission system setup you have, the more overhead you get.
If you do not have any GRANT statements done, MySQL will optimise the permission checking somewhat. So if you have a very high volume it may be worth the time to avoid grants. Otherwise, more permission check results in a larger overhead.

Q. How can we increase the execution time of a PHP script?
ans. By the use of void set_time_limit ( int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

Q. How can I know that a variable is a number or not using a JavaScript?
ans. bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.

53. List out the predefined classes in PHP?
Ans:-
1. Standard Defined Classes
These classes are defined in the standard set of functions included in the PHP build.

a. Directory
The class from which dir() is instantiated.

b.stdClass

2.Ming Defined Classes
These classes are defined in the Ming extension, and will only be available when that
extension has either been compiled into PHP or dynamically loaded at runtime.

3. Oracle 8 Defined Classes
These classes are defined in the Oracle 8 extension, and will only be available when
that extension has either been compiled into PHP or dynamically loaded at runtime.

a. OCI-Lob
b. OCI-Collection

4. qtdom Defined Classes
These classes are defined in the qtdom extension, and will only be available when that
extension has either been compiled into PHP or dynamically loaded at runtime.

a. QDomDocument

b. QDomNode

56. How can we send mail using JavaScript?
Ans:-
No You can’t send mail using Javascript but u can execute a client side email client to send the email using mailto: code.

Using clientside email client
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=”mailto:mailid@domain.com?subject=”+tdata+”/MYFORM”;
return true;
}

55. What are the difference between abstract class and interface?

Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.

Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.

58. What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.
Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

64. What is maximum size of a database in mysql?

MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.
The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system.
Operating System File-size Limit
Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB

66. Explain Normalization concept?

The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).

First Normal Form

The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).

Second Normal Form

Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.

Third Normal Form

I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table

70. What are the advantages and disadvantages of CASCADE STYLE SHEETS?

External Style Sheets

Advantages

Can control styles for multiple documents at once
Classes can be created for use on multiple HTML element types in many documents
Selector and grouping methods can be used to apply styles under complex contexts

Disadvantages

An extra download is required to import style information for each document
The rendering of the document may be delayed until the external style sheet is loaded
Becomes slightly unwieldy for small quantities of style definitions

71. What type of inheritance that php supports?

Answer: In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.

72. How can increase the performance of mysql select query?

The structure of table view buyers is as follows
+—————-+————-+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+—————-+————-+——+—–+———+—————-+
| user_pri_id | int(15) | | PRI | NULL | auto_increment |
| userid | varchar(10) | YES | | NULL | |
+—————-+————-+——+—–+———+—————-+
the value of user_pri_id the last row 2345 then What will happen in
the following conditions

Condition1: Delete all the rows and insert another row then What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 2345) and insert another row then What is the value for this auto incremented field user_pri_id

In general, when you want to make a slow SELECT … WHERE query faster, the first thing to check is whether you can add an index. All references between different tables should usually be done with indexes. You can use the EXPLAIN statement to determine which indexes are used for a SELECT. See section 7.4.5 How MySQL Uses Indexes and section 7.2.1 EXPLAIN Syntax (Get Information About a SELECT).
Some general tips for speeding up queries on MyISAM tables:

To help MySQL optimize queries better, use ANALYZE TABLE or run myisamchk –analyze on a table after it has been loaded with data. This updates a value for each index part that indicates the average number of rows that have the same value. (For unique indexes, this is always 1.) MySQL will use this to decide which index to choose when you join two tables based on a non-constant expression. You can check the result from the table analysis by using SHOW INDEX FROM tbl_name and examining the Cardinality value. myisamchk –description –verbose shows index distribution information.

To sort an index and data according to an index, use myisamchk –sort-index –sort-records=1 (if you want to sort on index 1). This is a good way to make queries faster if you have a unique index from which you want to read all records in order according to the index. Note that the first time you sort a large table this way, it may take a long time.

In both cases let the value for auto increment field be n then next row will have value n+1 i.e. 2346

82. What are the differences between drop a table and truncate a table?
Answer: Delete a Table or DatabaseTo delete a table (the table structure, attributes, and indexes will also be deleted).
What if we only want to get rid of the data inside a table, and not the table itself? Use the TRUNCATE TABLE command (deletes only the data inside the table).

96. How can I use the COM components in php?

The COM class provides a framework to integrate (D)COM components into your PHP scripts.
string COM::COM ( string module_name [, string server_name [, int codepage]])
COM class constructor. Parameters:
module_name
name or class-id of the requested component.
server_name
name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE in php.ini.
codepage
specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
Usage:
Version}\n”; //bring it to front $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff $word->Selection->TypeText(“This is a test…”); $word->Documents[1]->SaveAs(“Useless test.doc”); //closing word $word->Quit(); //free the object $word->Release(); $word = null; ?>

107. How many ways I can redirect a php page?

Here are the possible ways of php page redirection.
Using Java script:
'; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } } redirect('http://maosjb.com'); ?>
Using php function:
Header("Location:http://maosjb.com ");

108. List out different arguments in php header function?

void header ( string string [, bool replace [, int http_response_code]])

109. What type of headers have to add in the mail function in which file a attached?

$boundary = '—–=' . md5( uniqid ( rand() ) );
$headers = "From: \"Me\"\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";

110. What is the difference between and And which can be preferable?

move_uploaded_file ( string filename, string destination)

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

116. What is the difference between Reply-to and Return-path in the headers of a mail function?

Reply-to: Reply-to is where to delivery the reply of the mail.

Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

117. Explain about Type Juggling in php?

PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.


$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)

If the last two examples above seem odd, see String conversion to numbers.
If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Note: The behavior of an automatic conversion to array is currently undefined.

Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being “f”, or should “f” become the first character of the string $a?
The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes “f”, the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

119. How can I embed a java programme in php file and what changeshave to be done in php.ini file?

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

66. Explain Normalization concept?
The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).
First Normal Form
The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).
Second Normal Form
Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.
Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table

I will give you a summarized explanation. There are two main things you have to do to integrate php with paypal:

  1. Open an account with paypal
  2. add hidden form elements to your existing form (which you are using for the shopping cart feature)

add hidden form elements to your existing form

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="
you@youremail.com">
<input type="hidden" name="item_name" value="
Item Name">
<input type="hidden" name="currency_code" value="
USD">
<input type="hidden" name="amount" value="
0.00">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>

https://www.paypal.com/cgi-bin/webscr

page at PayPal that is set up to accept submission of your order

you@youremail.com

your email address you have entered in the paypal account

Item Name

The item name to be sold.

These details will probably come from database

USD

The item currency to be sold in

0.00

The item price to be sold

http://www.paypal.com/en_US/i/btn/x-click-but01.gif

<html>
<body>
<form name= “order” action=”https://www.paypal.com/cgi-bin/webscr” method=”post”>

Since we wish to send detailed customer information, the input control with the name attribute set to “cmd” must have a value of “_ext-enter”.

<input type=”hidden” name=”cmd” value=”_ext-enter”><br>

The next line is also a requirement for using extended values. Its value must be set to “_xclick”. In this way we will be able to pass our customer information to PayPal and not require that it be re-entered.

<input type=”hidden” name=”redirect_cmd” value=”_xclick”><br>

After submission to PayPal, the user is returned to your site and the success or failure of the transaction is confirmed. This will be handled in a page called “notify.php”, but feel free to name it whatever you like. A query string called “status” will be examined in order to output an appropriate message to the user.

<input type=”hidden” name=”return”
value = “http://<your site>/notify.php?status=T”><br>
<input type=”hidden” name=”cancel_return”
value = “http://<your site>/notify.php?status=F”><br>

Enter the appropriate values for the next set of items. Remember, the value of the input “business” will be the same as the e-mail address of your Paypal account. Likewise with “item_name” and “shipping”. The first shipping value represents the cost of shipping the first item and the second the cost of each additional item.

<input type=”hidden” name=”business” value =”mybusiness@myisp.com”>
<input type=”hidden” name=”item_name” value=”your product”>
<input type=”hidden” name=”shipping” value=”5.00″>
<input type=”hidden” name=”shipping2″ value=”5.00″>

If handling shipping costs in this way does not meet your requirements PayPal provides other ways of doing this.

Information Retrieved from Query String

As shown in our graphic above, detailed order information was presented to the user in the previous page and will not be re-presented at the PayPal site. Paypal still needs summary information in order to bill the correct amount. This will now be retrieved from the query string passed to this page. The number of items is also retrieved as this will affect shipping costs.

<?php
//get values from previous page
$quantity = $HTTP_GET_VARS['quantity'];
$total = $HTTP_GET_VARS['total'];
echo “<input type=\”hidden\” name=\”quantity\” value=\”$quantity\”><br>\n”;
echo “<input type=\”hidden\” name=\”amount\” value=\”$total\”><br>\n”;

The “customerid” parameter was also passed in to this page but will be retrieved when needed to create a database query.
Information From the Database

First a note about the database. Assume a customer table with the following structure:
Field                                  Type

id                                       int(11)                     Primary Key
email                                 varchar(50)
lastname                           varchar(50)
firstname                          varchar(50)
streetaddress1                 varchar(50)
streetaddress2                 varchar(50)
city                                    varchar(50)
stateprov                          varchar(50)
pcode                                varchar(50)
country                              varchar(50)
password                          varchar(50)
dateadded                        timestamp(14)

The customer information needs to be retrieved from the database. Let�s create a connection and the SQL query to retrieve the information we wish to pass to PayPal.

//include database password information etc.
$hostname = “myhost.com”;
$username = “user”;
$password = “password”;
if(!($link = mysql_connect($hostname, $username,$password)))
die(“Could not connect to database.”);
$databasename = “mydatabase”;
if(!(mysql_select_db($databasename,$link)))
die(“Could not open table.”);

Retrieve the information from the database using the primary key.

//now get customer info from database
$customerid = $HTTP_GET_VARS['id'];
$strsql=”SELECT email, firstname, lastname, streetaddress1, “.
“streetaddress2, city, stateprov, pcode FROM “.
“tblcustomer WHERE id = ‘$customerid’”;
if(!($rs= mysql_query($strsql, $link)))
die(“Could not open table.”);
//only one row should be returned
$row = @ mysql_fetch_array($rs);

The form is now completed with the information retrieved from the database.

// now complete the form
echo “<input type=\”hidden\” name=\”email\” value=\”$row[email]\”><br>\n”;
echo “<input type=\”hidden\” name=\”first_name\” value=\”$row[firstname]\”><br>\n”;
echo “<input type=\”hidden\” name=\”last_name\” value=\”$row[lastname]\”><br>\n”;
echo “<input type=\”hidden\” name=\”address1\”
value = \”$row[streetaddress1]\”><br>\n”;
echo “<input type=\”hidden\” name=\”address2\” value =
\”$row[streetaddress2]\”><br>\n”;
echo “<input type=\”hidden\” name=\”city\” value=\”$row[city]\”><br>\n”;
echo “<input type=\”hidden\” name=\”state\” value=\”$row[stateprov]\”><br>\n”;
echo “<input type=\”hidden\” name=\”zip\” value=\”$row[pcode]\”><br>\n”;
?>
<!– end of form  –>
</form>

You might have noticed that there is no “submit” button associated with our “paypal.php” page. Because our customer has already confirmed his order, code is used to submit this form to PayPal. The following JavaScript code will execute after the page has loaded and your customer will not see the “paypal.php” page at all.

<script type=”text/javascript” language=”JavaScript”>
//submit form
document.order.submit();
</script>
</body>
<html>

business

Email address on your PayPal account

item_name

Name of the item (or a name for the shopping cart)

currency_code

Defines the currency in which the monetary variables (amount, shipping, shipping2, handling, tax) are denoted. Possible values are “USD”, “EUR”, “GBP”, “CAD”, “JPY”.

amount

Price of the item (the total price of all items in the shopping cart)

image

The image for the button your buyer will press to initiate the PayPal payment process. You can substitute your own image by replacing the src with the URL of your image

.htaccess: An htaccess file is a simple ascii text file which you create or edit in a text editor. Allowing you to password protect directories, enable server side includes, generate custom error messages, and block users by IP address among other things.

Captha: In a CAPTCHA test (an acronym for “Completely Automated Public Turing test to tell Computers and Humans Apart,” also sometimes spelled in lowercase), an image of letters is dynamically generated. The letters, because they’re part of an image and not text (e.g. text that you could cut and paste), are difficult for a spambot or other computer program to read. Yet, a person has little trouble reading the letters in a captcha image.

Serialization: Serialization is the process of persisting the state of an object. Lets say for example you create a dog object and instantiate all its various members, size, age, height etc. Serialization allows you to ‘save’ this object persisting all its state. Its kind of like saving anything, this can then be restored at a later date and the object reused.

Sql Injection: User input that uses SQL Injection.

$name_bad = "' OR 1'"; 

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

echo "Injection: " . $query_bad;

Delete and Truncate:

TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server.
DELETE is a DML command and can be rolled back.

Both commands accomplish identical tasks (removing all data from a table), but TRUNCATE is much faster.

Drop: Remove table and its data.

Indexes: Indexes in MySQL can increase the speed of your MySQL queries to squeeze a bit more performance out of your database.

PHP5 has an integrated support for SOAP as it provides in-built classes for SOAP calls.

PHP5 offers Exception handling mechanism that was missing in its earlier version. You no longer have to write your own logic to return different type of values from one function to another in case of errors.

Garbage Collection refers to the automatic reclamation of dynamically allocated object or variable that are no longer in accessible when an object or variable goes out of scope.

PHP6 is in development as of July 2007 and the PHP team is considering to add namespaces support. With PHP6 a lot of default options in php.ini will either be removed or be enabled. To name a few magic_quotes, safe_mode, register_mode will all be removed.

<!– /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:”"; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} pre {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:”Courier New”; mso-fareast-font-family:”Times New Roman”;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} –>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:”Table Normal”;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-parent:”";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:”Times New Roman”;
mso-ansi-language:#0400;
mso-fareast-language:#0400;
mso-bidi-language:#0400;}

Re: What is the difference between mysql_connect() and mysql_pconnect()?

Answer

Mysql_connect()->we can colse the datedase
Mysql_pconnect()->we can't close the datadase

Mysql_conect()->opens the database every time page is load
Mysql_pconnect()->Need not to the every time page load

Re: what is the difference between MyISAM and INNO DB in MySQL with the Advantage and disadvantage

MyISAM and InnoDB are storage engines in MySql.
MyISAM does not support transactions while InnoDB support
it.
InnoDB: Row level locking, Transaction support, forgin key
constrant and crash recovery.

MyISAM: Much more conservate approach to disk space
management each MyISAM table store in a separate file. in
MyISAM memory and space usage, full text indexing support,
table based locking, bulk insert capabilities and speed are
plus factor but crushes recovery would be the horror story.

As general approach, if you have a more reads use MyISAM and

if you have a more update use InnoDB.

Posted by: antervedi | December 15, 2008

How to Understand Seo

Why do we need SEO? A. Search Engine Optimization or SEO is a marketing tool used worldwide on the Internet in order to get higher ranking. Simple enough right?

Step1
Afraid it’s not that easy, in this discipline one has to look at various attributes of their website. From content to links, link backs and last but not least their structure. Once you have had a good look at your website content you have to remove any impediments that are preventing your site from achieving it’s rightful place in the search rankings on the Internet. Therefore the question is why do we need SEO?

Step2
Since we are still in the SEO infancy stage there are a lot of changes happening. The major understanding everyone is finally catching up on is that users searching have what they coin as “local intent”. Basically the user is looking for someone close to them especially if you are a retailer or a local hardware store.

Step3
Did you know that 63% of all search made by users are made with the desire for someone locally? That is why you will notice a lot of search engines are adapting the zip code feed in the searches. I am sure you have seen this, especially if you are looking for a doctor. This new attribution is more prevalent and will hone the searches specifically to the users local area and not across the globe to china.

Step4
Search Mobile is a new addition to your of local search -Think about this ingenious idea now with GPS installed in all mobile phones it will automatically give you your criteria search locally since it already knows where your location is by your phone.

Step5
Who needs SEO is anyone who is on the Internet. More than 80% of users will start with a search. Therefore any business that wants to get more clients or more users on their sites needs to understand and ultimately use SEO properly.

Step6
SEO is also beneficial to your business regardless of whether you are brand oriented or not. It’s comes from the old school of marketing and advertising basically, keep your name and brand out there. Regardless of whether you are Pepsi, Ford, or a local TV station.

Step7
Therefore the question is should SEO be written for search engines or for the user? This is a common misconception that if you write SEO style then your users will come. NOT! The consideration is you have 2 things to deal with: 1. People using the search and 2. The robots crawling your pages. Now the question you should ask yourself is who is going to buy from you? Regardless of whether you are selling a local product or are going for an International market will be people. Therefore make sure your content is written for people with flow and information. The search robots will pick those keywords up don’t worry.

Step8
The common mistake is that when you have someone writing your SEO they will offer all the tricks and shortcuts in order to get you a higher ranking. They ain’t cheap either. Therefore stay away from those companies. They may very well get you a higher ranking but Google will catch up and tear you down like the cheap tawdry hustler you are.

Posted by: antervedi | December 12, 2008

Maximum Upload size with PHP

Depending on how you host your website (or application) there are different ways to change the PHP settings. In particular, the most asked about problem, changing the maximum upload size.

There are 3 settings PHP uses that limit your uploading ability:

  • post_max_size
    This is the combined maximum size of all files sent on the form. If you have 2 file fields on your form, the total filzesize of the 2 files must not exceed the post_max_size value.
  • upload_max_filesize
    This is the filesize limit of each individual file.
  • memory_limit
    PHP scripts have a memory limit, and generally speaking this can prevent some uploads from working. The limit should be set at a reasonable level, of course you won’t need 20mb for a simple ‘hello world’ script. Try slowly increasing this value if you find that uploads still aren’t working.

If you host your site remotely, you should check their documentation on how to change the PHP configuration settings. But if you’re not so inclined, and prefer a trial and error approach, here’s a summary of things to try:

Change php.ini directly

If you host your site on a server that you have access to, you can change your php.ini file directly. This is the easiest approach. Your php.ini file should exist in the PHP installation directory. Open it in your favourite text editor and search for these lines and change them:

memory_limit = 8M
post_max_size = 8M
upload_max_filesize = 2M

You may need to restart apache for the changes to take effect.

Changes to .htaccess

.htaccess files only apply to Apache webservers. They are files that append and change certain values that apache uses and they are placed in the root folder (and all folders beneath will use those settings). If apache uses PHP as a Module, then you can add values to the .htaccess file:

php_flag file_uploads On
php_value memory_limit 8M
php_value post_max_size 8M
php_value upload_max_filesize 2M

If you try this approach, and your webserver displays a 500 interal server error, then PHP is not runing as a module and apache didn’t like the php_value entries. You will need to remove your changes.

Upload a php.ini file

This generally works if the changes to .htaccess method doesn’t. Some web hosts that use apache, also use PHP as a CGI. Then also, most times, this allows changes to the PHP configuration using a custom php.ini file that you can upload. You don’t want to include every setting available to PHP in your file. Only include the ones you want to change, and don’t forget the heading [PHP]:

[PHP]
; Whether to allow HTTP file uploads.
file_uploads = On
; Maximum amount of memory a script may consume (8MB)
memory_limit = 8M
; Maximum size of POST data that PHP will accept.
post_max_size = 8M
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M 
Posted by: antervedi | December 9, 2008

Christmas Greetings

http://www.101christmas.net/

http://www.care2.com/send/catxmas1.html

http://www.123greetings.com/events/christmas/merry_christmas/

http://www.riversongs.com/christmas_cards.html

http://www.greetingsnecards.com/events/christmas/

http://www.christmas-wishes.com/

Posted by: antervedi | December 5, 2008

Blogging

What is a blog? And why are they so popular?

A blog (a contraction of the term “Web log“) is a Web site, usually maintained by an individual with regular entries of commentary, descriptions of events, or other material such as graphics or video. Entries are commonly displayed in reverse-chronological order. “Blog” can also be used as a verb, meaning to maintain or add content to a blog.

A blog is a special type of Web page—an online journal—with unique characteristics that set it apart from regular Web pages. Blogs are made up of multiple journal entries listed in reverse chronological order that invariably include a title, a date, and time stamp. Each blog entry also will have its own Permalink (a unique Web address) and sometimes a Trackback (an automatic entry that appears in your blog to tell you that somebody has written about your entry, and linked to it), a Category, and Comments.

Comments are one of the things that make blogs unique and special. Anybody who reads a blog may, if the blog owner allows it, publish comments under a blog entry to agree, to disagree, to sympathize, or to share their own thoughts. This interaction is different than more traditional feedback utilities such as Guestbooks. Guestbooks are generic—entries are not tied to one particular page, or commentary. Blog comments, on the other hand, are tied directly to a particular entry.

Who uses blogs?

Nowadays, anybody can use a blog. Traditionally, blogs have been used by journalists, political commentators, and the like. Blogs have been used as the instrument of choice for some amazing exposés over the years, some of which are mentioned in Wikipedia’s article about blogs. In recent times, blogs have been adopted by mainstream Internet users, thanks in part to Blogger.com and LiveJournal, and MSN when they introduced MSN Spaces—a very easy to use, free blogging service that is available to all users of MSN Messenger.

Posted by: antervedi | December 5, 2008

Books

osbkphpeasyGetting started on the Web can be frustrating if you have no website to develop from. So Julie Meloni’s PHP: Fast & Easy Web Development is appreciated right from the start because Julie makes sure that you are able to get a localhost website installed and started in Windows as well as Linux. And so you get detailed start-up instructions not just for PHP but also Apache Server and MySQL. And that sets the style for this very practical introduction to PHP and MySQL, The syntax and theory are discussed but the exercises and practice carry the load..

Nonetheless readers will solve useful exercises in array usage, strings and formatting plus the key to PHP – how to work with databases. The book emphasizes MySQL – and why not ? The interface to MySQL is very easy to use and MySQL is used by PHP developers in more applications than just about all the other databases combined. Again, the exercises come through with graded introduction to database usage, forms input and report writing. But don’t look for advanced topics like object design or advanced media output. This book is designed to get you up and running quickly and it delivers. All of the exercises are included on the enclosed CD – a bargain to get all this for $30.

osbkphpwrox11HangontoyourseatbeltsherecomesabookonPHPandMySQLthatwillrockandroll. PHP MySQL Website Programming by Chris Lea, Mike Buzzard, Jessey Cinis, Dilip Thomas
is exactly that – the project is about building a complete website, a weblog for DVD lovers including such amenities as news bulletin, discussion boards, polls, XML/RSS feeds, and even banner ads. You get to see not only the logic but also the design consideration around building a weblog application like phpBB or PostNuke.

And at the same time you get a very good introduction to PHP, PHP’s object oriented tools (often given short shrift in intro PHP texts), and a nice grounding in MySQL. In fact, that is the interesting thing about the book – all the new texts about C#, Java, VB.NET etc usually feature some section on UML and class diagrams. Whereas this book emphasizes the database design as well as module/classes. It also shows the big gap between open source tools like Perl, PHP, Python, TCL and other scripting languages and the BEA, Microsoft, Oracles of the development world -use of OO and OO design is just emerging(new versions of PHP 5 and Perl 6 will both enhance there core OO capabilities). So a book like this that takes a consistent OO approach to PHP is well appreciated.

WordPress for Business Bloggers:

wordpressforbusinessbloggersThis book will take you beyond the basics of WordPress, helping you take full advantage of its rich and powerful features to transform your basic blog into a more advanced and professional blog as quickly and painlessly as possible.

WordPress Theme Design:

wordpressthemedesignThis book walks through clear, step-by-step instructions to build a custom theme for the WordPress open-source blog engine. The author provides design tips and suggestions and covers setting up your WordPress sandbox, and reviews the best practices from setting up your theme’s template structure, through coding markup, testing, and debugging, to taking it live.

http://www.gigapedia.org
http://www.ebay.com

Categories

Follow

Get every new post delivered to your Inbox.