Find invalid filenames from a web host

12 Feb 2016 in Web

With the following code, you can find invalid filenames under a directory:

<?php
// change according to your needs
$dir = __DIR__;

// force browser to show the output as plain text
header('Content-Type: text/txt; charset=utf-8');

// scan directory
$dir = new DirectoryIterator($dir);
foreach ($dir as $fileinfo) {
    // do not process . and ..
    if ($fileinfo->isDot()) {
        continue;
    }

    $filename = $fileinfo->getFilename();

    if (strlen($filename) == strlen(utf8_decode($filename))) {
        continue;
    }

    // filename mismatch
    echo $dir . $filename . "\n";
}

Obviously, to be used on a php web host.

A fractal of BAD developers Pt.1

05 Feb 2016 in PHP, Codesod

Recently, we moved a customer's website to one of our servers. The site is written in PHP with all these things you want to avoid: Register globals, bad procedural code, code repetitions, etc.

One of the things we had to deal with was creating the database. Because in every php file the developers were using this code:

$db=mysql_connect("localhost","XXX","YYY");
mysql_select_db("ZZZ",$db);

we forced ended up creating a user XXX with password YYY on database ZZZ (yeah i know, this is where sed might be useful). Joking aside, this is where require statement come in handy. So instead of the above, you may write this:

include "database.php";

and create a database.php file with the following code:

<?php
$db = mysql_connect("localhost","XXX","YYY");
mysql_select_db("ZZZ",$db);

Also, notice the use of the deprecated (and removed from PHP 7) mysql extension.

To be continued...

PHP Programming guidelines

01 Feb 2016 in PHP

Matthias Noback has posted a series of articles on Programming Guidelines:

PHP is pretty much a freestyle programming language. It's dynamic and quite forgiving towards the programmer. As a PHP developer you therefore need a lot of discipline to get your code right. Over the years I've read many programming books and discussed code style with many fellow developers. I can't remember which rules come from which book or person, but this article (and the following ones) reflect what I see as some of the most helpful rules for delivering better code: code that is future-proof, because it can be read and understood quite well. Fellow developers can reason about it with certainty, quickly spot problems, and easily use it in other parts of a code base.

Continue reading:

Optimizing images for use on the web

26 Jan 2016 in Web

The importance of image optimization from google developer:

Images often account for most of the downloaded bytes on a web page and also often occupy a significant amount of visual space. As a result, optimizing images can often yield some of the largest byte savings and performance improvements for your website: the fewer bytes the browser has to download, the less competition there is for the client's bandwidth and the faster the browser can download and render useful content on the screen.

After this short intro, I mainly use:

jpegoptim: utility to optimize jpeg files. Provides lossless optimization (based on optimizing the Huffman tables) and "lossy" optimization based on setting maximum quality factor.

# example command line usage to optimize images under a directory
find /path/to/dir -type f -name "*.jpg" -exec jpegoptim --strip-all {} \;

optipng: PNG optimizer that recompresses image files to a smaller size, without losing any information. This program also converts external formats (BMP, GIF, PNM and TIFF) to optimized PNG, and performs PNG integrity checks and corrections.

# example command line usage to optimize images under a directory
find /path/to/dir -type f -name "*.png" | xargs optipng -nc -nb -o7 -full

If you are using grunt on your development workflow, look for the grunt-contrib-imagemin task and apply the options like:

imagemin: {
    png: {
        options: { optimizationLevel: 7 },
        files: [...]
    },
    jpg: {
        options: { progressive: true },
        files: [...]
    }
}

Debugging SOAP requests

24 Jan 2016 in PHP, SOAP

If for some reason you have to deal with debugging on SOAP requests (that is, to see the actual request and response bodies), you can use these methods:

and remember to set the trace option when initializing the SOAP object. For example, using the free webservicex.net:

<?php
// initialize soap client
$soap = new SoapClient(
    "http://www.webservicex.net/country.asmx?WSDL", [
    "trace" => true,
]);

// call a method on soap object
$soap->__call("getCountries", [
    // options for method
]);

// output raw request, something like
// <?xml version="1.0" encoding="UTF-8"?>
// <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
//                    xmlns:ns1="http://www.webserviceX.NET">
//     <SOAP-ENV:Body>
//         <ns1:GetCountries/>
//     </SOAP-ENV:Body>
// </SOAP-ENV:Envelope>
echo $soap->__getLastRequest(); 

// output raw response, something like
// <?xml version="1.0" encoding="utf-8"?>
// <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
//                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
//                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
//     <soap:Body>
//         <GetCountriesResponse xmlns="http://www.webserviceX.NET">
//             <GetCountriesResult>
//                 <!-- ... -->
//             </GetCountriesResult>
//         </GetCountriesResponse>
//     </soap:Body>
// </soap:Envelope>
echo $soap->__getLastResponse(); 

Accessing Whois info after changing IP

19 Jan 2016 in DNS

The problem: you changed IP/nameservers for a site and after DNS changes propagated, you found out you need some information from the old site.

If you are lucky (and quick) enough, you can work around this problem by visiting whois.domaintools.com and searching for the site you want. Look for the IP Address (eg A.B.C.D), make sure it's not the same as the new site and put it in your /etc/hosts file like this:

# the format is <IP> <host>
A.B.C.D  my.site

Now you can visit the old site (eg my.site) from your browser, if it's still available from the old host.

Magento's memory limit on CLI

18 Jan 2016 in PHP, Magento

Recently, I noticed a command line script built for a Magento store, terminated with out of memory errors:

PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted...

As it turns out, Magento is reading the .htaccess file even if running from command line and applies any php configuration found to the script environment.

In order to fix this, find the line

php_value memory_limit 256M

and get rid of it.

Getting a database backup via php

15 Jan 2016 in Code Snippets, PHP, MySQL

<?php
//
// Download a gzipped mysql dump from a remote host
//
// Invoke it via curl with:
//  curl http://remote.site/path/to/script.php -o /path/to/dump.sql.gz
//

// replace with your own values
$username = escapeshellarg("YOUR DATABASE USER");
$password = escapeshellarg("YOUR DATABASE PASSWORD");
$database = escapeshellarg("YOUR DATABASE NAME");

// dump it!
passthru("mysqldump -u$username -p$password $database | gzip");

The Sad State of Web Development

14 Jan 2016 in Development, Web

Taken from The Sad State of Web Development:

2015 is when web development went to shit. Web development used to be nice. You could fire up a text editor and start creating JS and CSS files. You can absolutely still do this. That has not changed. So yes, everything I’m about to say can be invalidated by saying that.

Although a little rough, this article says a lot about

The web (specifically the Javascript/Node community) has created some of the most complicated, convoluted, over engineered tools ever conceived.

My opinion? Keep It Simple. Choose the simplest thing that really works and don't go for the newer shinier thing. Avoid the hype and work on proven and tested technologies. Or else good luck "updating dependencies 3 months later".

Oh, and don't forget to read on The Magpie Developer.