:::: MENU ::::
Posts tagged with: php

PHP 5.4.15 Released!

New PHP Version Available

The PHP development team announces the immediate availability of PHP 5.4.15 and PHP 5.3.25. These releases fix about 10 bugs. All users of PHP are encouraged to upgrade to PHP 5.4. PHP 5.3.25 is recommended for those wishing to remain on the 5.3 series.

Changelog

Core:

Fixed bug #64578 (debug_backtrace in set_error_handler corrupts zend heap: segfault).
Fixed bug #64458 (dns_get_record result with string of length -1).
Fixed bug #64433 (follow_location parameter of context is ignored for most response codes).
Fixed bug #47675 (fd leak on Solaris).
Fixed bug #64577 (fd leak on Solaris).

Fileinfo:

Upgraded libmagic to 5.14.

Streams:

Fixed Windows x64 version of stream_socket_pair() and improved error handling.

Zip:

Fixed bug #64342 (ZipArchive::addFile() has to check for file existence).

Download

You can get the new version from the PHP Downloads page.


Running PHP Within Sublime Text 2

What is Sublime Text?

The Sublime Text family of software had provided some real innovation when it comes to text editing. Their extremely lightweight and minimalistic editor can be extended far beyond imagination and really give thousand dollar software competition.

One of the things we do is code small PHP snippets. When it comes to projects, we prefer Zend Studio. For small pieces of code, Sublime Text 2 was exactly what we wanted. It was lacking one thing though; the ability to run PHP in-app.

Sublime provide functionality known as Build. This allows you to execute the open file through a builder, such as make, and you can even define your own. That is exactly what we did and turned this $70 software package into an irreplaceable tool.

Creating a PHP Builder

To create a PHP build system, go to Tools -> Build System -> New Build System.

Add the following contents to this new file, and save it as PHP.sublime-build:

{
"cmd": ["/usr/bin/php", "-f", "$file"]
}

Note: Each argument needs to be passed as a separate item in the array.

Using Your New Builder

Go back to your PHP file, and press Cmd+B. This will build your code. The output of the command will appear in the console if you have it open.

Summary

Adding simple functionality like the above, really adds weight to such a lightweight editor. All of the customizations can really give other mainstream editors like Eclipse a run for their money!


How-To: Insert Binary Data into MySQL

Binary Data is AWESOME!

Working with binary data can be extremely beneficial, especially when it’s very detailed data. Example, it is easier to & and | two integers than to create a crazy function to do math. In one of our previous posts, we created a class and a few functions to handle IP addresses. Inserting a converted IP into the database allows you to & and | a user supplied IP to return matches. This is a great way to work with IP’s within databases.

One issue you may run into is, when you echo a binary string, it could result in a ©'. This doesn’t look like anything readable in this format, but if you convert this with inet_ntop, it would return 97.32.169.39.

If you tried to insert that specific string into a database, it would fail under the most simplest of INSERT‘s. Note the ' (single quote). We will provide some examples on how to insert this string using queries and PHP.

Our Sample Database

For this example, we will use the following database and table:

CREATE DATABASE BinaryTest;

CREATE TABLE `BinaryTest`.`Testing` (
  `binary_field` varbinary(39) NOT NULL
);

Inserting the Data

We have included some examples on how you could insert binary data. There are 2 simple ways to do this, and one that is just plain cool.

1st Method: Prepared Statements

Our first method will use a prepared statement. This will sanitize your input and gracefully insert the row.

try{
    echo "Trying Prepared...\n";
    $stmt = $pdo->prepare("INSERT INTO Test.Testing SET binary_field=?");
    $stmt->execute(array(inet_pton("97.32.169.39")));
}
catch(\Exception $e){
    echo $e->getMessage()."\n";
}

2nd Method: Escaping Statements

Those who are old-timers with MySQL know about the need to quote your insert strings. This would turn ' and " into \' and \", preventing the breakage of quoted values. This will work, but not the most secure and desirable method.

try{
    echo "Trying Prepared...\n";        
    mysql_query("INSERT INTO Test.Testing SET binary_field=". mysql_real_escape_strings(inet_pton("97.32.169.39"));
}
catch(\Exception $e){
    echo $e->getMessage()."\n";
}

3rd Method: Converting to Hex

This is the cool method. If you want to insert Binary data into a MySQL table, convert it to hex. You can then pass this to your query and it will convert it to binary upon insertion.

try{
    echo "Trying Hex...\n";
    $pdo->query("INSERT INTO Test.Testing SET binary_field=0x". bin2hex( inet_pton("97.32.169.39") ) );
}
catch(\Exception $e){
    echo $e->getMessage()."\n";
}

Summary

We would always recommend someone to prepare their query first. If you can’t, go with the 3rd option. You can probably clean it up and optimize the code some more, but try to stay away from manually escaping your values.


Infinite Redirect Loop during WordPress Login

The Other Loop

WordPress has a very intuitive and straight forward admin interface. This is one of the reasons I choose to deploy client projects on WordPress. It’s abilities have made it one of the leading software packages for content aggregation. Although it’s almost perfect, there are still some things that users and administrators may over look which could lead you to experience a bug. A infinite redirect loop when logging in could be one of them. Luckily for them, I get to work out all the bugs before the keys are handed over.

The Fix

This fix is pretty easy. What happens depending on your configured settings and what URL (including subdomain) you access the login page from, you confuse WordPress. WordPress knows it needs to authenticate the user, but if this is happening after the login form already posted, you get stuck in an infinit loop.

Add the following just below the RewriteBase directive in your sites .htaccess:

RewriteRule ^wp-admin - [L]

Reflections: Unsung Hero’s of PHP

What are Reflections?

First off, if you don’t know what Reflections are, you should take a quick walk through the PHP: Reflection manual. You have been missing out. Reflections are some of the most powerful shadow features in current generation ( >= PHP5.3).

PHP 5.3 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. Many PHP developers are familiar with call_user_func_array(), but not Reflections. This function allows you to pass arguments to an object of the Callable type, most commonly a function or class method. It was introduced in 4.0.4 and gave developers a new approach to dynamically constructing code. Here is an example to freshen your memories:

// Example function function 
example($arg1, $arg2){ 
    echo $arg1; // Prints: argument_a 
    echo $arg2; // Prints: argument_b 
} 

// array with contents to be passed to function 
$arguments = array("argument_a", "argument_b"); 

// pass argument array to function example 
call_user_func_array('example', arguments);

This may not seem like a big deal, but in some scenarios, you can’t always estimate where you get your arguments from (although some will argue this is bad coding practice). If you have a string, like "this|is|a|string", you can explode it and pass the parts to call_user_func_array(). The string can then be any number of parts long, and if you want, you could catch them in the example() function using func_get_args().

What can Reflections do?

Reflections are very powerful, in many ways. They give a developer the ability to read document comments, dynamically call methods, invoke arguments and more. It takes the ability that call_user_func_array(), and allows you to extend it even further.

Here is a simple example using a sample class:

// Example Class
class ExampleClassToReflect { 
    private $classData; 

    public function __construct($arg1, $arg2){ 
        // Construct Called 
        $this->classData = "$arg1 reflected $arg2\n"; 
    } 

    public function callMethod(){ return $this->classData; } 
} 

$rc = new ReflectionClass('ExampleClassToReflect'); 
$class = $rc->newInstanceArgs(array('foo', 'bar')); 
echo $class->callMethod(); // returns 'foo reflected bar'

The above will create an instance of ExampleClassToReflect and pass the arguments foo and bar to it’s constructor. You can then use the variable $class just as if you called the class using the new keyword.

How are they the future?

Conclusion

Staying up on new functions and classes is very important. There are a lot of snippets of [ >= PHP5.3 ] code I have seen where someone uses an eval() but had they known about Reflections, they could have saved themselves both headache and vulnerability exposure.



Regular Expression Pattern Parsing ifconfig

**Note: ** This regex is designed to skip loopback by default.

preg_match("/^([A-z]\*\d)\s+Link\s+encap:([A-z]\*)\s+HWaddr\s+([A-z0-9:]\*).\*". 
           "inet addr:([0-9.]+).\*Bcast:([0-9.]+).\*Mask:([0-9.]+).*". 
           "MTU:([0-9.]+).\*Metric:([0-9.]+).\*". 
           "RX packets:([0-9.]+).\*errors:([0-9.]+).\*dropped:([0-9.]+).\*overruns:([0-9.]+).\*frame:([0-9.]+).*". 
           "TX packets:([0-9.]+).\*errors:([0-9.]+).\*dropped:([0-9.]+).\*overruns:([0-9.]+).\*carrier:([0-9.]+).*". 
           "RX bytes:([0-9.]+).\*\((.\*)\).*TX bytes:([0-9.]+).\*\((.\*)\)". 
           "/ims", $int, $regex); 

if( !empty($regex) ){ 

    $interface = array(); 
    $interface['name'] = $regex[1]; 
    $interface['type'] = $regex[2]; 
    $interface['mac'] = $regex[3]; 
    $interface['ip'] = $regex[4]; 
    $interface['broadcast'] = $regex[5]; 
    $interface['netmask'] = $regex[6]; 
    $interface['mtu'] = $regex[7]; 
    $interface['metric'] = $regex[8]; 

    $interface['rx']['packets'] = $regex\[9]; 
    $interface['rx']['errors'] = $regex\[10]; 
    $interface['rx']['dropped'] = $regex\[11]; 
    $interface['rx']['overruns'] = $regex\[12]; 
    $interface['rx']['frame'] = $regex\[13]; 
    $interface['rx']['bytes'] = $regex\[19]; 
    $interface['rx']['hbytes'] = $regex\[20]; 

    $interface['tx']['packets'] = $regex\[14]; 
    $interface['tx']['errors'] = $regex\[15]; 
    $interface['tx']['dropped'] = $regex\[16]; 
    $interface['tx']['overruns'] = $regex[17]; 
    $interface['tx']['carrier'] = $regex[18]; 
    $interface['tx']['bytes'] = $regex[21]; 
    $interface['tx']['hbytes'] = $regex[22]; 

    $interfaces[] = $interface; 

}



PHP Fatal error: Call-time pass-by-reference has been removed in

http://php.net/manual/language.references.pass.php

There is no reference sign on a function call – only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that “call-time pass-by-reference” is deprecated when you use & in foo(&$a);.

Good

function myFunc(&$arg) { }
myFunc($var);

Bad

function myFunc($arg) { }
myFunc(&$var);

Pages:123