Archive for the 'PHP' Category

PHP - PHP, Learn Something New

Tuesday, February 7th, 2006

>

If your anything like the majority of society, myself included, you could probably use a little more info on certain aspects of computers. Here, I decided to take a look at “PHP”. Yeah I know, that’s what I said, “Yeah right!”, but it’s not so confusing when you look at it a little closer…

PHP is an acronym (One of those things smart people use to confuse us) which stands for “PHP: Hypertext Preprocessor”. It used to stand for “Personal Home Page”, but that must have been too easy. So after a little reasearch I found out just what the acronym meant. It is an open source, reflective programming language.

Apparently, all that programming language stuff is to develop “dynamic web content and server side applications”. They have also found a new use for it in other types of software.

Once again, this stuff is pretty tricky, but take a look elseware! Maybe there is a “PHP for Dummies” out there. I would encourage any of you who have the slightest incling to find out more, to do so. It’s actually pretty interesting! The best thing to do for more information is to check out forums, blogs, or websites about PHP. There is also books and an actual formal development manual that you can purchase from a store or borrow from a library, that will be able to answer any of your questions about this particlular programming language.

About the Author

Feel free to reprint this article as long as you keep the article, this caption and author biography in tact with all hyperlinks.

Tyler Brooker is the owner and operator of Hosting Php Tutorials - http://www.hosting-php-tutorials.com, which is the best site on the internet for all Php related information.

PHP - Mastering Regular Expressions in PHP

Tuesday, February 7th, 2006

>

<span style=”font-weight:bold; font-size: 1.2em”>What are Regular Expressions?</span> A regular expression is a pattern that can match various text strings. Using regular expressions you can find (and replace) certain text patterns, for example “all the words that begin with the letter A” or “find only telephone numbers”. Regular expressions are often used in validation classes, because they are a really powerful tool to verify e-mail addresses, telephone numbers, street addresses, zip codes, and more.

In this tutorial I will show you how regular expressions work in PHP, and give you a short introduction on writing your own regular expressions. I will also give you several example regular expressions that are often used. Regular Expressions in PHP Using regex (regular expressions) is really easy in PHP, and there are several functions that exist to do regex finding and replacing. Let’s start with a simple regex find.

Have a look at the documentation of the preg_match function. As you can see from the documentation, preg_match is used to perform a regular expression. In this case no replacing is done, only a simple find. Copy the code below to give it a try. <pre><?php

// Example string $str = "Let’s find the stuff <bla>in between</bla> these two previous brackets";

// Let’s perform the regex $do = preg_match("/<bla>(.*)</bla>/", $str, $matches);

// Check if regex was successful if ($do = true) { // Matched something, show the matched string echo htmlentities($matches[’0′]);

// Also how the text in between the tags echo ‘<br />’ . $matches[’1′]; } else { // No Match echo "Couldn’t find a match"; }

?></pre>After having run the code, it’s probably a good idea if I do a quick run through the code. Basically, the whole core of the above code is the line that contains the preg_match. The first argument is your regex pattern. This is probably the most important. Later on in this tutorial, I will explain some basic regular expressions, but if you really want to learn regular expression then it’s best if you look on Google for specific regular expression examples.

The second argument is the subject string. I assume that needs no explaining. Finally, the third argument can be optional, but if you want to get the matched text, or the text in between something, it’s a good idea to use it (just like I used it in the example). The preg_match function stops after it has found the first match. If you want to find ALL matches in a string, you need to use the preg_match_all function. That works pretty much the same, so there is no need to separately explain it.

Now that we’ve had finding, let’s do a find-and-replace, with the preg_replace function. The preg_replace function works pretty similar to the preg_match function, but instead there is another argument for the replacement string. Copy the code below, and run it. <pre><?php

// Example string $str = "Let’s replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace $result = preg_replace ("/<bla>(.*)</bla>/", "<bla>new stuff</bla>", $str);

echo htmlentities($result); ?></pre>The result would then be the same string, except it would now say ‘new stuff’ between the bla tags. This is of course just a simple example, and more advanced replacements can be done.

You can also use keys in the replacement string. Say you still want the text between the brackets, and just add something? You use the $1, $2, etc keys for those. For example: <pre><?php

// Example string $str = "Let’s replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace $result = preg_replace ("/<bla>(.*)</bla>/", "<bla>new stuff (the old: $1)</bla>", $str);

echo htmlentities($result); ?></pre>This would then print “Let’s replace the <bla>new stuff (the old: stuff between)</bla> the bla brackets”. $2 is for the second “catch-all”, $3 for the third, etc.

That’s about it for regular expressions. It seems very difficult, but once you grasp it is extremely easy yet one of the most powerful tools when programming in PHP. I can’t count the number of times regex has saved me from hours of coding difficult text functions.

<span style=”font-weight:bold; font-size: 1.2em”>An Example</span> What would a good tutorial be without some real examples? Let’s first have a look at a simple e-mail validation function. An e-mail address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$

Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this: <pre><?php

// Good e-mail $good = "john@example.com";

// Bad e-mail $bad = "blabla@blabla";

// Let’s check the good e-mail if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $good)) { echo "Valid e-mail"; } else { echo "Invalid e-mail"; }

echo ‘<br />’;

// And check the bad e-mail if (preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $bad)) { echo "Valid e-mail"; } else { echo "Invalid e-mail"; }

?></pre>The result of this would be “Valid E-mail. Invalid E-mail”, of course. We have just checked if an e-mail address is valid. If you wrap the above code in a function, you’ve got yourself a e-mail validation function. Keep in mind though that the regex isn’t perfect: after all, it doesn’t check whether the extension is too long, does it? Because I want to keep this tutorial short, I won’t give the full fledged regex, but you can find it easily via Google.

<span style=”font-weight:bold; font-size: 1.2em”>Another Example</span> Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let’s assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this: <pre><?php

// Good number $good = "123-4567890";

// Bad number $bad = "45-3423423";

// Let’s check the good number if (preg_match("/d{3}-d{7}/", $good)) { echo "Valid number"; } else { echo "Invalid number"; }

echo ‘<br />’;

// And check the bad number if (preg_match("/d{3}-d{7}/", $bad)) { echo "Valid number"; } else { echo "Invalid number"; }

?></pre>The regex is fairly simple, because we use d. This basically means “match any digit” with the length behind it. In this example it first looks for 3 digits, then a ‘-’ (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.

<span style=”font-weight:bold; font-size: 1.2em”>What exactly is possible with Regular Expressions?</span> Regular expressions are actually one of the most powerful tools in PHP, or any other language for that matter (you can use it in your mod_rewrite rules as well!). There is so much you can do with regex, and we’ve only scratched the surface in this tutorial with some very basic examples.

If you really want to dig into regex I suggest you search on Google for more tutorials, and try to learn the regex syntax. It isn’t easy, and there’s quite a steep learning curve (in my opinion), but the best way to learn is to go through a lot of examples, and try to translate them in plain English. It really helps you learn the syntax.

In the future I will dedicate a complete article to strictly examples, including more advanced ones, without any explanation. But for now, I can only give you links to other tutorials: The 30 Minute Regex Tutorial Regular-Expressions.info

About the Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.webdev-articles.com

PHP - PHP and MySQL Tutorial: Introduction

Tuesday, February 7th, 2006

PHP is the programming language of the web it?s a fact the php is used on more webservers servers than any other web language. At the time of writing php is installed on just under than 24,000,000 Domains..

MYSQL is a commercial grade database application that is made available free under the Open Source to anyone. It?s had over 6 million installs ranging from large muli-national corporations to specialized embedded applications the website also claims mysql is installed on every continent in the world? Including antartica. At least they can blame the weather when the computer freezes? hehe! Currently MYSQL runs on more than 20 platforms including Linux, Windows, OS/X, HP-UX, AIX and Netware. Which is a perfect solution for portability requirements.

PHP - MYSQL it does have uses

The benefits to creating a site that implements a php and mysql setup are really down the site and how it wants to run and taking into account how specific data is stored and displayed, php and mysql can be used in many senarios including:

# Storing and Displaying Lots of Categorised data - For example the article you are reading now, has come from our mysql database. Sites with lots of information that needs to be categorised, stored and easily displayed would benefit from a mysql backend. Lets again take this site for example, if we created the site the old fashioned way then we would have to create a single HTML page for every article. Now lets say we we wanted to change a link in the menu right of this page then we would need to go through each and every single HTML page and manually change every element to it. Not fun I?m sure you?d agree. but with php and mysql all we now need to do is change one single php page and the whole site updates our link.. Saving you time and your sanity.

# Saving customer data into php- Many websites as an example use the duo to save customer data, Including Name, telephone, address etc.. well you get the picture. MYSQL can also track customers locations on the site and save that information into the database. PHP can also store customer purchasing and previous orders into the database which allows you to build up a perfect system for tracking customer trends and customers shopping habits based on country. All you would need to do is create a php that told mysql to grab the particular information only.

Installation

Please take note that your web host will have php and mysql pre installed on the server but and easy way to check is copy the code just below into notepad then save it as ?info.php?. Upload it to your webspace via FTP and then goto your browser and type in www.yourdomain.com/info.php or where ever you dropped the file.

< ?php
phpinfo();
?>

it should show you a lot of information such as the version of php your running and additonal, but useful information about the configuration of your php. A list of installed manuals is also included.

To install PHP & MYSQL on windows you can do it manually or you can use a program called WAMPserver which will automatically install the setup for you, just to let you know the W.A.M.P stands for windows, Apache, Mysql and PHP.

WAMPserver installation on windows

WAMP5 installs the following software on your machine Apache 1.3.31 ,PHP5, MySQL database ,PHPmyadmin and SQLitemanager on your computer. Essentially your going to turn your windows machine into a webserver beacause we are installing apache. PHP does need apache webserver to run in this setup usually.

You can download WAMPserver here: http://www.wampserver.com/en/download.php

Here are the installation instructions from wampservers site: http://www.wampserver.com/

When you install WAMP5, all the files are copied in the directory you choose. Conf files are then modified to point to that directory. It also installs a ?www? directory which will be your Document Root.

At the end of the installation, WAMP5 will automatically install Apache and MySQL as services :

- service? wampapache? : apache service

- service ?wampmysql? : mysql service

WAMP5?s installation is compact. This means that all files are copied to WAMP5?s directory. Only the MySQL conf file (usually my.ini) is copied to the Windows directory but as ?mywamp.ini? to avoid conflicts with other installs. You just have to click on the icon tray to access WAMP5?s menu, The icon tray reflects the status of your server, When you?ll uninstall WAMP5, all the services and files will be automatically deleted.

In part two will be getting down to the nitty gritty by setting up the mysql database and connecting to it through php.

For part 2 of this tutorial visit: http://www.chauy.com/2005/11/php-mysql-part-2/

Thanks!

About the Author: Tutorial provided by http://www.chauy.com - webmaster tutorials, Webmaster News and tools. This notice must remain intact. copyright (c) http://chauy.com - Used with permission

PHP - PHP: Easy Dynamic Websites

Tuesday, February 7th, 2006

>

PHP is the most popular scripting language on the web, and the reason for that is how easy it makes it to create dynamic websites quickly. If you’re already a programmer, you’ll be able to learn the basics of PHP in about five minutes, and if you’re not then it probably won’t take much longer.

Getting Started in PHP

There’s a tradition in programming that the first thing you do in any language is say ‘Hello World’. Well, here’s how you do that in PHP. First of all, create a file in your server’s root directory called index.php. Put this text in it:

<?php echo “Hello World”; ?>

Let’s look at this bit by bit. The first line means ‘what follows is PHP code’. ‘echo’ is the PHP command to send text to the web browser, and each line of PHP has to end with a semicolon. Finally, the last line means ‘end of the PHP code’.

Now, the power of PHP is that those start and end tags can do anywhere in a normal HTML document, as many times as you like. For example:

<html> <head> <title>my page - <?php echo date(); ?></title> </head> <body> <?php $total = 1 + 1; echo $total; ?> </body> </html>

This is a complete HTML document with pieces of embedded PHP. The first PHP section inserts the date into the title, and the second writes the answer to 1 + 1 (that’s 2, you know) as the content of the document - the word with a dollar before it is a variable, storing the result of the sum. Where this all becomes extremely useful is that your PHP code can open a connection to a database, read data from it, and then the text into a template, along with other things from the database like the headline, the author’s name and the date it was written.

Useful PHP Functions

Here’s a quick reference of the most useful PHP functions to help you get started.

date. This function returns the date in a format you specify using letters. For example, date(”D j M Y”) outputs dates in this format: Mon 1 Jan 2010.

echo. Writes text to the document. You can use < ?= as a useful shortcut for explode. Divides up some text into an array by looking for ’seperator’ letters or characters. Can be good if you’re using odd characters like | to separate data somewhere in your program.

fopen. Opens a file on your web server, but can also be used to open a URL and so connect to another server.

fread. Reads the contents of the file, either all at once or line by line.

header. Allows you to set your own HTTP headers - most often used to control which MIME types things are sent with (the content-type header), or to tell the browser whether to cache or not (the cache-control header).

md5. Takes some text and produces a ‘hash’ using the MD5 algorithm. This is often used to allow checking of users’ passwords without needing to save their passwords in a database in plain text. The sha1 function does the same thing, and is more secure but slower.

mysql_connect. Connects to a MySQL server. You have to tell it where the server is (usually localhost), as well as your username and password.

mysql_select_db. Chooses which MySQL database to open on the MySQL server you’re connected to.

mysql_query. Sends any SQL commands you want to your MySQL server.

mysql_fetch_assoc. Turns the results of a query sent to a MySQL server into an array, to make it easier to use in your program.

str_replace. Replaces one word with another in some text. This is useful when it comes to inserting the HTML tags between paragraphs, for example.

strtotime. Turns an English-language description of a date and time into a number representing that date and time (technically known as a Unix timestamp). This makes them easier to use with a database, as you can sort from the ‘highest’ (most recent) to the ‘lowest’ (longest ago) more easily. You can convert back from timestamps again by using the date function.

If you have trouble remembering the names of the PHP functions (they’re quite inconsistent), take a look at http://www.ilovejackdaniels.com/php/php-cheat-sheet/ - this page has a ‘cheat sheet’ with names of common functions that you can print out and keep.

About the Author

Information supplied and written by Lee Asher of Eclipse Domain Services
Domain Names, Hosting, Traffic and Email Solutions.

PHP - Quick Intro to PHP Development

Tuesday, February 7th, 2006

Chances are that if youve been around the Internet long enough, youve heard of server-side scripting languages such as PERL, ASP and ColdFusion. These are all popular languages that are used to add interactivity to Web sites, but one stands out from the crowd in terms of usability, power, and, yes, price: the PHP scripting language. Initially developed in 1995 by North Carolina programmer Rasmus Lerdorf, PHP has since blossomed into one of the leading open-source, cross-platform scripting languages available. This is due, in large part, to the worldwide community of coders that contributes to its development. Unlike proprietary scripting languages like ASP and ColdFusion, PHPs source code is freely available for peer review and contributions. This is, of course, the essence of open-source software development, but why is it that PHP in particular has gained such popularity among Web developers when there are other open-source alternatives, such as good old-fashioned PERL CGI scripts?

One very strong reason is that PHP, unlike PERL CGI scripts, is scalable and fast. Instead of requiring the server to start a new process in the operating systems kernel for each new request, which uses both CPU time and memory, PHP can run as a part of the Web server itself, which saves a considerable amount of processing time when dealing with multiple requests. This decreased processing time means that PHP can be used for high-traffic sites that cannot afford to have their performance hampered by relatively slow CGI scripts.

In addition to its scalability and speed, another usability factor that sets PHP apart is its ease of use. The PHP language is considered to be a mix between C and PERL, and it draws from the best features of each parent language, while adding unique features of its own. For example, PHP code can be embedded within standard HTML documents without using additional print statements or calling separate scripts to perform the processing tasks. In practice, this allows for very flexible programming practices. Although a working knowledge of HTML is a prerequisite for PHP development, PHPs basic functions can be learned quickly and applied to a wide range of common Webmaster-related projects, such as order forms, e-mail responses, and interactive Web pages.

Contributing to the power of the PHP language, is its native support for leading relational database platforms, including MySQL, Oracle and PostgreSQL. Platform-specific functions are built into the language for 12 databases in all. This native support for database platforms is a boon to any site that needs to track user information, store product data, or collect sales information.

Last but not least, because PHP is open-source, it is essentially free to use. Almost all professional Unix-based Web hosts offer PHP as an included option with hosting accounts. Be sure to check with your host to see if it is available to you.

This article is meant to be an introduction to the PHP language and not a tutorial, but have no fearhere are several first-rate sites that have articles that will guide you along in beginning your PHP development projects:

www.php.net
www.onlamp.com/php/
www.phpbuilder.com

Alan is the lead developer for InfoServe Media, LLC (http://www.infoservemedia.com), a Web development company that specializes in Web site design, hosting, domain name registration, and promotion for small businesses.

How to Stop Digital Thieves with CGISteve Humphrey

I’m going to assume you’re serious about your business. If you’re not, I can’t help you anyway. You’ve gone as far as getting a real merchant account to accept credit card payments online.

You know that this was neither easy or cheap. So does everyone else! So, a merchant account shows that you’ve made a serious commitment to your business. That’s good for customer confidence, which is good for business. So far so good…

Now there’s the issue of selling stuff to people online. Your order form leads them to feed their credit card info to a secure gateway, using software you bought or leased from (or through) your merchant account provider. Finally, the transaction is approved or denied.

If approved, the software generates a receipt and emails you and the customer each a copy. At this point, the customer is returned to a page you specified. In the case of downloadable products, this is often the page where they download your product. So, you’ve got the entire process fully automated.

For a product or service with a fairly low price point and a potential for many thousands of sales, this seems ideal. You can quite literally make sales and earn income 24 hours a day. So, what’s the problem?

The form code on your order page is the problem. If someone uses the ViewSource function of their browser, they can see all your code. If they have even a tiny bit of initiative and skill, they can locate the URL of your download page. After all, it’s right there in your form code!

CGI provides two ways of fixing this problem. One involves using a script that makes it impossible to view the source code. You can find a source for such a script by searching the web. Expect to pay a lot for this technology.

Another way is to make the return path a script instead of the actual download location. The script would be used to create and display the download page. It would not be visible to the surfer, since it’s not an HTML document. The script can also record details of the transaction for book-keeping purposes.

I admit that I discovered this by trial and error - and a lucky guess or two. Your merchant account gateway software may have radically different behavior than mine, but here’s what I’ve learned:

The gateway uses the POST method to send the customer to your specified return URL (which can be a script as well as a web page). It also POSTs most of its input data items at the same time. They are usually ignored, but your script can read them if you want to!

Use the names given to the form inputs. Have your script extract the values of these “named parameters” at the time it creates the download page. Record what you want to save about the transaction in your orders file or database.

Now here’s the real secret to foiling the thieves. Inside the script, check to see that the variables you extract contain non-empty values. Did you get that? Here’s an example:

if ($email eq “”) {exit;}

In this example, the script expects to get an email address. If it contains no characters, the script quits instantly. By testing for the presence of some data in such fields as customer name, email address, item #, price, etc., you can tell whether the script was called after a successful transaction - or by a thief…

Put all your security checks prior to the code that creates the download page. If any test fails, the script exits and the thief is left empty- handed. If your form-handling script can convert a product name to a product ID that’s never visible to a browser, this provides even more security. This will be POSTed back to the script and you can check for it before allowing the download.

Close these security holes and you’ll make more money. You may even sleep a little better knowing that people can’t steal that product you worked so hard to create. I know I do!

Steve Humphrey promises that you can learn to use CGI to turn your own website into a marketing machine in two hours or less with his excellent CGI learning system: “Learn to Use CGI in 2 Hours.” We highly recommend this book as required reading for anyone who wants to automate their website or their marketing efforts. Click here for immediate access: http://www.roibot.com/tk_cgi2h.cgi?cgiAV2b