WebDev Masters

Web Development & Webmaster Resources

Browsing Posts in PHP

 Aghreni offers skill enhancement courses in 

· PErL, PHP, Ruby & java/J2ee

· Unix/linux

· Mysql

· Web development

· User interface design

·  Veritas

· Usability engineering

· Project management

· Leadership

· Software development techniques

· Software testing techniques

Aghreni Technologies is an offshore provider of open source software, solutions, products and services.

Many times your site needs images to be uploaded, maybe for display with submitted content, then you have to make sure that the images displayed should be of a suitable size. If a user uploads a particularly large image, it may destroy the layout of the page when it is displayed.

Thumbnail images guarantee you that the images displayed will never exceed certain height and width values. Creating a basic thumbnail is a five-stage process:

1. Load the source image into a PHP variable.

2. Determine the height and width of the original image.

3. Create a blank thumbnail image of the correct size.

4. Copy the original image to the blank thumbnail.

5. Display the thumbnail using the correct content type.

EXAMPLE: Suppose we have to create a thumbnail from a photo in JPEG format. First of all, we specify the path to the source image as well as our desired width and height in pixels:

$sourceImage = ‘SAMPLE_IMAGES/scenery.jpg’;
$thumbWidth = 200;
$thumbHeight = 200;

Next, we use imagecreatefromjpeg to load an image from the file system into a PHP variable:$original. The getimagesize function returns the width and height of the image.

$original = imagecreatefromjpeg($sourceImage);
$dims = getimagesize($sourceImage);

Then we use the imagecreatetruecolor function to create a blank image into which the thumbnail image will be placed: $thumb = imagecreatetruecolor($thumbWidth,$thumbHeight);

There should be a code for the point at which the thumbnail image is actually created from the original:

imagecopyresampled( $thumb, $original, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $dims[0], $dims[1] );

At last, after we have sent the correct content type header, we’ll use imagejpeg to output the completed thumbnail:

header( “Content-type: image/jpeg” );
imagejpeg( $thumb );

Bhavna Bhatnagar
PhpTechHelp.com

PHP- Automated Housekeeping
Queries are run by users through the web interface and by administrators through either administrative web interfaces or from the MySQL command interpreter. However, sometimes automated querying is necessary to produce periodic reports, update data, or delete temporary data. We discuss how queries can be automated in this section.

To show how queries can be automated, consider an example from the online winestore. The shopping cart in the online winestore is implemented using the winestore database. As discussed in Chapter 12, when an anonymous user adds a wine to their shopping basket, an order row is added to the orders table. The row is for a dummy customer with a cust_id=-1, and the next available order_id for this dummy customer. A related items row is created for each item in the shopping cart. The order_id is maintained in the session variable order_no so that orders by different anonymous customers aren’t confused.

Our system requirements in Chapter 1 specify that if a customer doesn’t purchase the wines in their shopping cart within one day, then the shopping cart should be emptied. This is an example of a DELETE operation that should be automated. It is impractical to require the administrator to run this query each day to remove junk data.

The following query can be run from the Linux shell to remove all orders rows that are more than one day old and are for the dummy customer:

% /usr/local/mysql/bin/mysql -uusername -psecret
-e ‘USE winestore; DELETE FROM orders WHERE
unix_timestamp(date) <
(unix_timestamp(date_add(now( ), interval -1 day)))
AND cust_id = -1;’
The MySQL time and date function unix_timestamp( ) converts a timestamp attribute to an integer that is accurate to the nearest second. In this query, we compare the value of the entry in the orders table with the value of exactly one day earlier from the current date and time. If the row is older than one day, then it is deleted. The same query works for the items table, when orders is replaced with items in the FROM clause.

13.1.1 cron Jobs
Having designed and tested the query, it can be inserted into a Unix cron table to automate the operation. The crond daemon is a process that runs by default in a Linux installation and continually checks the time. If any of the entries in user tables match the current time, then the commands in the entries are executed. Consider an example:

30 17 * * mon-fri echo ‘Go home!’
This prints the string at 5:30 p.m. each working day. The two asterisks mean every day of the month, and every month of the year respectively. The string mon-fri means the days Monday to Friday inclusive. More details about cron can be found by running man crontab in a Linux shell.

We can add our housekeeping query to our cron table by running:

% crontab -e
This edits the user’s cron table.

We have decided that the system should check for old shopping carts every 30 minutes. To do so, we add the following two lines to the file:

0 * * * * /usr/local/mysql/bin/mysql -uusername -psecret
-e ‘USE winestore; DELETE FROM orders WHERE
unix_timestamp(date) <
(unix_timestamp(date_add(now( ), interval -1 day)))
AND cust_id = -1;’

30 * * * * /usr/local/mysql/bin/mysql -uusername -psecret
-e ‘USE winestore; DELETE FROM items WHERE
unix_timestamp(date) <
(unix_timestamp(date_add(now( ), interval -1 day)))
AND cust_id = -1;’
The first line contains the complete query command for the orders table from earlier in this section, and the second line the items query. The shopping cart orders DELETE query runs exactly on each hour, while the items DELETE query runs at 30 minutes past each hour. Different times are used to balance the DBMS load.

Reports, updates, delete operations, and other tasks can be added to the cron table in a similar way. For example, we can output a simple report of the number of bottles purchased yesterday and send this to our email address each morning:

0 8 * * * mon-fri /usr/local/mysql/bin/mysql -uusername
-psecret -e ‘USE winestore; SELECT sum(qty) FROM
items WHERE unix_timestamp(date) >
(unix_timestamp(date_add(now( ), interval -1 day))) AND
cust_id != -1;’ | mail help@webdatabasebook.com
We could also have automatically written the information to a log file or to a table in the database.

More PHP Tutorial

It’s not so easy to get great PHP web hosting. Most companies are something to be afraid of. Wouldn’t you hate to see that your service was down for two days straight and there was nothing you could do because support “just wasn’t available”?

Today in many cases this service is just another term for “I want a quick buck”. Some of the companies don’t really care for the people and are just out to make money.

The reason most people don’t find a solution right away is because they just fall prey of the seemingly good programs that they find first. One of the main reasons people fall into these traps is because the best companies are usually not so well know, so people don’t tend to go with these companies right away.

For starters it’s very much possible to be paying a cheap price and getting a premium service. Only a few companies offer such great services that they are worth finding in case you ever need anything.

So you’re not sure whether you’ve actually found the right service. Here are some of the features the “right one” will have:

MySQL, PHP, Python, Perl, CGI, Cron: All the technical stuff you may require should be included. If you don’t know what that means don’t worry, but it’s always good to have it around just in case.

Bandwidth: This is how many visitors your site will be able to host in a month. Anything more than 75GB will work fine for most people.

Monthly Price: Cheap doesn’t always mean bad, but sometimes it can hut depending on the web hosting. We recommend getting “healthy cheap” which is around 10 bucks a month. This gives a good price and gets you good service.

Proper Web Statistics: How much traffic you’re getting? What keywords are people using to find you? What sites link to you? All this stuff you’ll want to know.

Choosing the right service the first time is not easy, but it’s possible, research is the key.

We suggest doing your research and then signing up with the web hosting company that meets your needs and your price range. You’ll be glad you did and won’t have to change for years. So go and find yourself the right PHP web hosting for you. It’ll be worth every second of your time.

Even though many people are a pain and we hate to admit it, you’ll feel very comfortable once you have found the answer to your problem and you’ll know that you’ll keep this service for years to come, this is why this is so critical and important.

Want to see which hosting companies are we talking about? Visit our site (http://www.web-hosting-review-central.info) to learn which is the best PHP Web Hosting company on the internet. HINT: Their Web Hosting is Cheap.

New website owners and existing website owners alike consistently make a very common, yet extremely costly mistake. They find a web designer first and then an SEO second. Unfortunately, these entrepreneurs do not realize that literally every single thing that goes into building a new website will impact your SEO campaign. They commonly funnel thousands of dollars into a brand new website, only to find out that there are a lot of areas that must be rebuilt in order to have an optimum SEO campaign.


I will identify 6 major areas of concern, in hopes that even a small percentage of these website owners will come across this document at the right time, which is BEFORE they begin to develop their website.


1) Domain name registration & hosting. Make sure that when you register your website’s address that you register it for at least 5 years. Sites that register their site for a short amount of time send up a red flag at Google, who end up thinking that site site has been registered short-term in the hopes of helping another website, that is owned by the same person/company, to rank well by linking to it. When choosing your domain name, do not choose a URL that is riddled with hyphens between all your keywords. It is more important that you target this to your visitors than to the search engines.


2) Creating static URL’s. This is one of the most overlooked yet important things that you can do to ensure that your SEO campaign is a success. By eliminating dynamic parameters within your website’s URLs, you are ensuring that search engine bots will have no problems indexing all of your pages. Creating static URL’s can be accomplished by using the mod rewrite command in the .htaccess file in the root folder of your server. Here is an example of a dynamic URL (which you want to avoid), and a static URL (which you want):


Dynamic: http://www.yoursite.com/listings.php?ref=22

Static: http://www.yoursite.com/listings/22.html


Make sure that any potential programmer or designer that you hire understands that this will be a full requirement of the job.


3) Editing the head tag. There are three areas in the head tag that you will want to be able to either edit yourself or have your SEO edit. They are the page title, the description meta tag and the keywords meta tag. Having control over these for each of your top level pages (all the pages linked to from your home page), will be critical to your websites success in the search engines. You definitely do not want these to be the same on every page (they must be unique and reflect the nature of the content on the given page). For other pages that will be created in high volumes, you will want to make sure that there is a variable string (your web designer/programmer will understand what this is) in place for each of the three areas in question, so that they will automatically be filled with content that is the right length and reflects the content on the given page.


Again, make sure that your designer/programmer understands that this is a requirement of the job.


4) Clean, simple code. Ideally you want to define all aesthetic properties that different types of text on your site are going to have in a separate CSS file. This means that you want to avoid using as many tags as possible, especially font, size and color tags. You also want to avoid creating PHP scripts that are either two long, and contain a lot of unnecessary steps, or ones that rely heavily on javascript. It is best to avoid using javascript as much as possible.


Remember, the most important thing your site can be doing is making it easy for search engine bots to easy scroll through the code of your website and follow all the links that it finds. When there is unnecessary code and script on your site, it makes it a lot harder for them, thus hurting your SEO campaign.


Make sure that whoever is helping you build your site understands that there job is to output the cleanest, simplest code possible. If you have any questions about this or don’t understand it, it is best to talk to an SEO expert about it, to ensure that it is done properly.


5) Ensuring that visible written content is editable. The writing within the body of your site is one of the most important areas for you or your Optimizer to help your site increase it’s rankings. Ensuring that either of you can edit it at your own convenience is extremely critical to the entire SEO campaign. This because from time to time search engine algorithms will change, and that might mean that a strategy that was implemented in the past might not suffice, so you must be able to change it to keep up with the most up to date SEO techniques.


6) Site structure. Considering the nature of PHP, your site will most likely (and should) be created by a series of includes that puts all of the pieces of a given page together. You want to ensure that the layout and placement of graphics and navigational links within these includes is strategically correct. Remember, you don’t want to have to pay someone to go back and redo this, so it is critical to get it right the first time.


If you are unfamiliar with a lot of the information that I presented in this article, it is probably in your best interest to at the very least, consult with an SEO or SEO company during the entire design process. A good SEO will be very comfortable working with you and your design team to ensure that the end product will be one that will last you a long time, and will go a long way in helping your site generate revenue online.

Bobby Heard is a Managing Director of Abalone Designs, Inc., a search engine optimization company based in Vancouver, Canada.

Gone are the days of expensive web hosting. There was a time, just a few years ago, when hosting was not as cheap as it is now. Lets see why.

Hosting is all about storage on a hard disk (which resides on the web server) and bandwidth for your data. Till a few years ago, hard disk storage was not as large as it is now. Now-a-days hard disk drives come in a typical 400 GB to 500 GB capacity ranges. Even the smallest ones for home computer usage come in over 100 GB sizes. Compare that with a 40 GB hard drive just a few years ago.

A few of these 400 GB to 500 GB range hard disk drives in a typical Linux powered web server with 4 Intel Xeon Central Processing Units gives more than enough processing power and storage capacity to host hundreds of websites on one server, all of them running happily.

Throw in open source (free) Apache + PHP + MySQL combination and you have a recipe for hosting a real working dynamic website at very low costs. What was once a premium combination is now very standard and very cheap and very affordable. It is not uncommon to find hosting plans as cheap as just 99 cents per month, which come complete with all features including PHP and MySQL and enough storage + bandwidth.

There is, thus, no reason for anyone who wants to host anything from a personal homepage or a home business / small business wanting a dynamic website for their online business, to go only for simple HTML websites. No. That is long gone.

Shared web hosting has become very affordable for every kind of use and application. As storage and processing technology advances, hosting will be available with even better capacities and more powerful features. It makes complete sense to use the power of PHP and MySQL when it is well within everyone’s reach.

RackNebula provides Affordable PHP MySQL Hosting starting from 99 Cents. Click Here: http://www.RackNebula.com

Sometimes it’s useful to enable visitors to your site to upload content, for example, photos, which can then be displayed on the site.

Folders on a website, for example, an images folder will typically have permissions of 755, which means that normal visitors to the site will be unable to upload content into the folder. They will receive an error message if they try to do so.

In order to allow a file upload, one solution is to temporarily change the permissions on the folder to 777 before the upload is made, and then to change them back to 755 after the upload has been made.

The following PHP script shows how you can do this using PHP’s ftp_site command. This script only changes the permissions one way (to 777), it doesn’t change them back. You would need to extend the script or write another one to do this. The line that reads $mod = ’0777′; // permissions to be set is the one that determines what the permissions are going to be set to.

Note: Please note that for display purposes, I have used square brackets ‘[' instead of angle brackets for tag names. In order to use the script you will need to change the square brackets back to angle brackets.

[?php

// Set up variables
$host = 'www.xyz.com'; // host (website) that contains the folder you want to change
$user = 'username'; // username to log onto the host
$password = 'password'; // password to log onto the host
$folder = 'public_html/test/'; // folder name to change
$mod = '0777'; // permissions to be set

// connect to FTP site
$conn = ftp_connect("$host");
if (!$conn)
{
echo 'Error: Could not connect to ftp server';
exit;
}

// log in to FTP site
@ $result = ftp_login($conn, $user, $password);
if (!$result)
{
echo "Error: Could not log on as $user";
ftp_quit($conn);
exit;
}

// try to change the permissions on the directory
if (ftp_site($conn, 'CHMOD '.$mod.' '.$folder)) {
echo "Successfully changed permissions";
}
else {
echo "There was a problem changing the permissions";
ftp_quit($conn);
exit;
}

// close the connection
ftp_close($conn);

?]

The script is fairly straight forward. You initially set up a few variables for the host name and stuff like that, you then connect to the FTP site, log on to the site, change the permissions of the folder, and then finally log off.

The path to the folder (assigned to $folder) will be something like ‘public_html/…/’. Check with your ISP if you’re not sure what this is.

John Dixon is a web developer working through his own company John Dixon Technology. As well as providing web development services, John’s company also provides free open source accounting software written in PHP and MySQL.

If you want to build a user-management system – or work on someone else’s – you should know a few basics about how passwords are encrypted or hashed. In other words, how are they made safe for storage?

What is a Hash?

Before a password is stored, it is typically converted into a “hash.” This isn’t technically a form of encryption, because it is a one way process. Once a password has been hashed… there’s no going back.

For example, if I hash the phrase “Bananas,” I might get back this garbled mess of characters – “1ee31b77d0697c36914b99d1428f7f32.”

The reason we do this is so that someone who views the database – a hacker or maybe a dishonest systems adminstrator – can’t figure out your password. He or she will see the hash and have no idea what the password is.

The script that checks your password when you log in knows how the hash was created – so it can recreate that hash if you give it the same password. The hash it creates based on your input can then be checked against the one in the database to see if you entered the real password.

Ok, How Do We Create a Hash?

There are two major functions for creating hashes in php – md5() and crypt().

md5 is the simpler function, so we’ll start there. You simply call the function like so…

md5(“Password String”);

This returns the encrypted hash. If you called md5(“Bananas”), you would always get “1ee31b77d0697c36914b99d1428f7f32″ back as a result. You would then store that phrase in the database to check the password in the future.

Crypt is a bit more complicated. With md5, you always get the same result. With crypt, you can use different encryption keys or “salts” to get different results. You can encrypt something with crypt like this…

crypt(“Password String”);

or

crypt(“Password String”, “Salt”);

If you do not provide a salt or encryption key, them PHP creates one for you. This changes the way the word is hashed. So if you called crypt(“Bananas”) twice, you would get two different results. Here’s some extra reading on how to use crypt to hash and encrypt a password in PHP.

So Which is Better?

That’s debateable. In most cases, crypt uses the same hashing algorithm that md5 does. Neither is necessarily “stronger” than the other.

The one advantage that crypt does has is that it can a different encryption key or salt each time. The same password can have a different hash if it is created with a different salt.

Therefore it is near impossible to create a dictionary of known hashes. With md5, this can be done easily – because each password phrase has only one possible hash value.

A dictionary like this would make a hacking attempt much easier than if the computer had to physically hash and check each possible phrase. Here’s some more reading on the difference between md5 and crypt.

Good luck hashing, and remember – the best way to learn php is to try new things. So go practice.

We discussed there that HTTP Basic Authentication has a number of drawbacks, and that you can avoid those with PHP-based authentication.The PHPLib features sophisticated classes for handling user authentication and permission management. The PHPLib authenticates sessions; thus it depends on the Session class.

On those pages in which you need authentication, the following page_open() call should be made to instantiate a session and authentication object:


page_open(array(“sess” => “Session_Example”, “auth” => “Auth_Example”));


Being based on sessions introduces a number of advantages for the authentication:

The username and the authentication element are sent only once, at the login. Once authenticated, the server stores the authentication data inside the session, and doesn’t transmit username or authentication element again.This is different than in HTTP Basic Authentication, where the username and password are transmitted in the HTTP headers of each request. But it also means that, if you lose the session, you lose the authentication.


The authentication procedure on the server can be complex. It can use any database or any other mechanism you can think of.The authentication is handled by an undefined function of the Auth class (auth_validatelogin()) and you have to implement it. 214 Chapter 6 Database Access with PHP
It’s not limited to a whole directory, but can be different for individual files of the application, and can even implement authentication levels inside a script. It’s possible to hide parts of the script from users who are not allowed to access them.
Users who aren’t known to the system can register themselves before logging in. A registration form is offered and the PHPLib will automatically create a standard entry in the user database.
Authentication via PHPLib works even with the CGI version of PHP.
You can log users out cleanly.This means that you can give your users the chance to terminate the current sessions (a logout button).
Users can be logged out automatically after a certain idle time. Doing so provides additional security for your application, because you can prevent session hijacking after a longer idle time.

Looking for best cheap web hosting plans including PHP & FTP? First take a look at some important features which must be considered when choosing your web hosting company:

Reliability and uptime: Hosting uptime refers to the percentage of time the host is accessible via the internet. It is very important your service be uptime (functioning and available for use). It means you can access your account whenever you want to update your web pages, and users can enter your website whenever they refer to your site address. If your hosting service is not uptime it can be catastrophic!

Disk space: Web hosting space is the amount of room that the web host provides to store your HTML, graphic, video/audio and other files. This figure is most commonly stated in gigabytes. If you don’t know how much space you need for your website, you can choose a web host with unlimited disk space, which allows you to build as many web pages as you want.

Bandwidth: Bandwidth (or data transfer) refers to the amount of data that is accessed by your visitors. Web hosts define bandwidth as the total amount of data access from your server over a month’s time. This figure is most commonly expressed in gigabytes. If you don’t know how much bandwidth you need for your website, you can pick a web host with unlimited data transfer, which allows you to support as many visitors as you want.

Ease of Control Panel: It is important that the control panel is easy to use and all information can be accessed easily.

If you are a beginner it is generally hard to you to pick the right web hosting service. There are many websites which display a couple of web hosting companies as the best and leave people confused without being helpful. To make things even more confusing, some hosting companies are cheating and lying to their customers!

*********************************************************************

All Web Hosts Presented On ThreeHosts.com Include PHP & FTP:

Threehosts.com is a reliable website to help you have the best choice. Their experts have been evaluating web hosting service providers for years, and now they provide you with the most reliable results. They present the information in an easy to understand format that helps the consumer make the best choice within just a few minutes. This is their purpose, to help you make the right choice the first time.

There you can reach the three reputable companies that are leaders in the web hosting industry. They are all easy-to-use and affordable.

http://www.threehosts.com/php-ftp