Aziz Saleh – Software development

  • Home
  • Downloads
    • AzizMVC Downloads
      • Database Plugin
        • Template Plugin
    • Flash Builder 4
      • Bypass, Hijack, Beat, and Defeat Same Origin Policy
      • Flash Click Tracker
      • Flash Link Hider
      • Pacman source V 1.0
    • Java Downloads
      • Currency Converter
    • Javascript Downloads
    • PHP/MySQL Downloads
      • Aziz MVC
      • AzizMVC Documentation
      • Contact Form Maker
      • NetFlix API 1.0 Wrapper
      • Simple Blog
    • Visual Basic Downloads
      • Currency Converter
        • Key Logger w/Store, email, registry options
  • Resume & Portfolio
  • Ask me a question
  • Contact Me

Category Archives: PHP

PHP Development

Your PHP installation appears to be missing the MySQL extension which is required by WordPress

Posted on March 24, 2014 by Aziz Posted in MySQL, PHP Leave a comment

Solution 1:

Check your php.ini and make sure that you have the following line un commented:

extension=php_mysql.dll

 

Solution 2:

You can use the following library if you do not have mysql_connect enabled but have PDO enabled:

https://github.com/AzizSaleh/mysql

Create a new file: wp-content/db.php and place this code in it (update your path to mysql with path to your extracted folder):

<?php
$pathToMySQL = 'C:\\xampp\\htdocs\\mysql\\';
require_once($pathToMySQL . 'MySQL_Definitions.php');
require_once($pathToMySQL . 'MySQL.php');
require_once($pathToMySQL . 'MySQL_Functions.php');

 

Solution 3:

apt-get install php5-mysql
deprecated mysql php wordpress

Undefined mysql functions (mysql_connect, mysql_select_db, mysql_query) – PDO alternative

Posted on September 8, 2013 by Aziz Posted in MySQL, PHP Leave a comment

If you have a site that is using mysql_* functions, upgrading your PHP will soon be hassle since Zend is planning on removing those functions. If you are in that group, I have written an object which will mimic the exact functionality of mysql_* functions but using PDO as the backend.

Some of the reasons why mysql_* methods were removed were the lack of:

  • Stored Procedures (can’t handle multiple result sets)
  • Prepared Statements
  • Encryption (SSL)
  • Compression
  • Full Charset support
  • Security

My object uses PDO, so it can be modified if needed to include such features. For now the only reason why someone would use this object is to avoid rewriting their entire codebase and switch to MySQLi/Pdo/etc.

The object duplicates all exact functionality of mysql_* functions except for mysql_info method which I tried to duplicate as best as I can, but due to PDO limitations/my knowledge I can’t do it exact.

Feel free to use the object and post any issues you may find so that we can improve on it. Also let me know if you find any issues, bugs or see room for improvement.

Package is hosted on PHPClasses.org @

http://www.phpclasses.org/package/8221-PHP-Access-MySQL-databases-using-PDO-wrapper-functions.html

All files are public so you won’t need to register/login to view them (let me know if it is not the case and I’ll post it here).

Sample usage:

<?php
// Include the definitions
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'MySQL_Definitions.php');

// Include the object
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'MySQL.php');

// Include the mysql_* functions
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'MySQL_Functions.php');

// Now all of the mysql_* methods will work on a PHP version that has them removed.
mysql_connect mysql_query mysql_select_db undefined

Checking if you have Javascript installed by PHP

Posted on November 11, 2012 by Aziz Posted in Javascript, PHP 2 Comments

This question gets asked tons of times on forums I am a member of. How can I tell if a user has Javascript enabled in their browser using PHP (or ASP, Python, Perl, ROR, Java for that matter of fact).

Unfortunately, there is no way you can do that. The closest you can come to Javascript with a scripting language is to know if the browser is capable of handling Javascript, which can be done using the get_browser function in PHP:

<?php 
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n"; 
$browser = get_browser(null, true); 
print_r($browser);

 

Which will output:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

My answer to that person was to use an intermediate index.html page, which will redirect them to the main page telling them if they have Javascript enabled or not:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Loading site ...</title>
<meta HTTP-EQUIV="refresh" CONTENT="1;URL=index.php?js=no">
<script language="JavaScript">
<!-- 
window.location = "index.php?js=yes"
// -->
</script>
</head>
<body>
</body>
</html>

The way this works is that if the user has Javascript enabled, the window.location (or any other JS method you use) will be executed. If Javascript is disabled, then the Meta Refresh tag will kick in after 1 second. You probably can do the refresh at 0 second, but 1 second should give enough time for a browser that is using lots of memory (Sorry FireFox).

check get_browser javascript php

Process Maxmind countries, regions and cities – Parser to MySQL or SqLite

Posted on October 15, 2012 by Aziz Posted in MySQL, PHP Leave a comment

The object will process Maxmind Countries, regions and cities into MySQL Db or an Sqlite Db file. There are some known issues with Maxmind’s city Db like:

  1. There is an outdated country code AN.
  2. Many cities (I would say around 3%) are mapped to an incorrect region.

The object:

 

<?php
/**
 * processCities.php
 *
 * PHP version >= 4.30
 *
 * @author    Aziz Hussain <azizsaleh@gmail.com>
 * @copyright GPL license
 * @license   http://www.gnu.org/copyleft/gpl.html
 * @link      http://www.azizsaleh.com
 */

/**
 * ProcessCities
 *
 * Download and process MaxMind geo, region and city list and relationships.
 *
 * Usage Options:
 * f -> Directory to download/extract files to (DEFAULT: Current working directory)
 * r -> if set, it will force to download the files again as opposed to using existing files by default
 * o -> what type of db to use, available options 'lite' (sqlite) or 'mysql'
 *
 * d -> Database file name for sqlite or db name for MySQL
 *
 * If using mysql, the following options can also be used:
 * h -> MySQL hostname (DEFAULT: localhost)
 * u -> MySQL username (DEFAULT: root)
 * p -> MySQL password (DEFAULT: empty)
 *
 * Example usage:
 *
 * SqLite:
 * php processCities.php -f /tmp -d /tmp/geodbLite.sqlite
 * or the following (DEFAULT: will use maxmindDb.sqlite on current working directory)
 * php processCities.php -f /tmp
 *
 * MySQL:
 * php processCities.php -f /tmp -o mysql -h 192.168.1.1 -u root -p rootpass -d geo_db
 *
 *
 * @author    Aziz Hussain <azizsaleh@gmail.com>
 * @copyright GPL license
 * @license   http://www.gnu.org/copyleft/gpl.html
 * @link      http://www.azizsaleh.com
 */
class processCities
{
    /**
     * Maxmind resource links
     *
     * @var array
     */
    public $links = array (
        'countries'    => 'http://www.maxmind.com/app/iso3166',
        'regions'    => 'http://dev.maxmind.com/static/maxmind-region-codes.csv',
        'cities'    => 'http://www.maxmind.com/download/worldcities/worldcitiespop.txt.gz',
    );

    /**
     * User options
     *
     * @var array
     */
    public $options;

    /**
     * Base directory, where files are downloaded to
     *
     * @var string
     */
     public $base;

    /**
     * Constructor - check user options, download any files needed
     *
     * @return void
     */
    public function __construct()
    {
        // Custom temp directory
        $this->options = getopt('f:r:h:u:p:d:o:');

        if (!empty($this->options['f'])) {
            $this->base = $this->options['f'];
        } else {
            $this->base = __DIR__;
        }

        if (!is_writable($this->base)) {
            die('Unable to access temp directory: ' . $this->base);
        }

        $this->base = rtrim($this->base, '/') . '/';

        // Fresh copies
        if (!empty($this->options['r'])) {
            foreach (array('countries.txt', 'regions.txt', 'cities.txt') as $file) {
                if (file_exists($this->base . $file)) {
                    if (!is_writable($this->base . $file)) {
                        die('Unable to remove file: ' . $this->base . $file);
                    }

                    unlink ($this->base . $file);
                }
            }
        }

        // Download countries?
        if (!file_exists($this->base . 'countries.txt')) {
            $countries = file_get_contents($this->links['countries']);
            $res = preg_split('/<\/?pre>/', $countries);
            if (empty($res[1])) {
                die('It seems like Maxmind has changed countries list location');
            }
            $countries = trim($res[1]);
            file_put_contents($this->base . 'countries.txt', $countries);
            unset($res, $countries);
        }

        // Download regions?
        if (!file_exists($this->base . 'regions.txt')) {
            $regions = file_get_contents($this->links['regions']);
            file_put_contents($this->base . 'regions.txt', $regions);
            unset($regions);
        }

        // Download/Extract cities?
        if (!file_exists($this->base . 'cities.txt')) {
            // Download file
            exec("wget -O '{$this->base}cities.txt.gz' '{$this->links['cities']}'");

            // Extract file
            exec("gunzip -f {$this->base}cities.txt.gz");
        }
    }

    /**
     * Process
     *
     * @return void
     */
    public function process()
    {
        try {
            // Do via MySQL
            if (isset($this->options['o']) && strtolower($this->options['o']) == 'mysql') {
                $this->processToMySQL();
                return;
            }

            // Do sqllite by default
            $this->processToLite();

        } catch (Exception $error) {
            die($error->getMessage());
        }
    }

    /**
     * Start processing downloaded files to SQL Db
     *
     * @return void
     */
    public function processToLite()
    {
        // Connect to sqlite DB
        $name = 'maxmindDb.sqlite';
        if (!empty($this->options['d'])) {
            $name = $this->options['d'];
        }

        $db = new PDO('sqlite:' . $name);

        // Drop/Create Tables
        $queries = array (
            'DROP TABLE IF EXISTS countries',
            'DROP TABLE IF EXISTS regions',
            'DROP TABLE IF EXISTS cities',
            'CREATE TABLE countries (
                country_id int,
                country_code varchar(4),
                country_name varchar(255),
                PRIMARY KEY(country_id ASC)
            )',
            'CREATE TABLE regions (
                region_id varchar(2),
                country_id int,
                region_name varchar(255)
            )',
            'CREATE TABLE cities (
                city_id int,
                region_id varchar(2),
                country_id int,
                city_name varchar(255),
                ascii_name varchar(255)
            )',
            'CREATE INDEX region_id ON cities (region_id) ASC',
        );

        // Execute drop/create queries
        foreach ($queries as $query) {
            $db->exec($query);
        }

        $this->addRecords($db);
    }

    /**
     * Start processing downloaded files to MySQL Db
     *
     * @return void
     */
    public function processToMySQL()
    {
        // Default Db Settings
        $settings = array (
            'host'  => 'localhost',
            'user'  => 'root',
            'pass'  => '',
            'db'    => 'maxmind',
        );

        // Check user settings
        foreach (array(
            'h' => 'host',
            'p' => 'pass',
            'd' => 'db',
            'u' => 'user',
        ) as $input => $toVar) {
            if (!empty($this->options[$input])) {
                $settings[$toVar] = $this->options[$input];
            }
        }

        // Connect to Db
        $db = new PDO("mysql:dbname={$settings['db']};host={$settings['host']}", $settings['user'], $settings['pass']);

        // Drop/Create Tables
        $queries = array (
            'DROP TABLE IF EXISTS countries',
            'DROP TABLE IF EXISTS regions',
            'DROP TABLE IF EXISTS cities',
            'CREATE TABLE `countries` (
                `country_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                `country_code` VARCHAR( 4 ) NOT NULL ,
                `country_name` VARCHAR( 255 ) NOT NULL
            )',
            'CREATE TABLE `regions` (
                `region_id` VARCHAR (2) NOT NULL ,
                `country_id` INT UNSIGNED NOT NULL ,
                `region_name` VARCHAR( 255 ) NOT NULL ,
                PRIMARY KEY ( `region_id`, `country_id` )
            )',
            'CREATE TABLE `cities` (
                `city_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                `region_id` VARCHAR(2) NOT NULL ,
                `country_id` INT UNSIGNED NOT NULL ,
                `city_name` VARCHAR( 255 ) NOT NULL ,
                `ascii_name` VARCHAR( 255 ) NOT NULL,
                 INDEX ( `region_id` )
            )',
        );

        // Execute drop/create queries
        foreach ($queries as $query) {
            $db->exec($query);
        }

        $this->addRecords($db, 'mysql');
    }

    /**
     * Add records to Db
     *
     * @param   resource                $db     Db Handler
     * @param   enum ('lite', 'mysql')  $type   Db Type
     *
     * @return  void
     */
    public function addRecords($db, $type = 'lite')
    {
        // Country code to Id mapping
        $countryMapping = array();

        // Insert countries
        echo 'Starting countries' . PHP_EOL;
        $countries = file_get_contents($this->base . 'countries.txt');
        $countries = explode(PHP_EOL, $countries);

        // Foreach country
        foreach ($countries as $country) {
            // Check for empty lines
            $country = trim($country);
            if (empty($country)) {
                continue;
            }

            // Construct SQL
            list($countryCode, $countryName) = explode(',', $country);
            $countryName = $this->escape(trim($countryName, '"'));
            $sql = "INSERT INTO countries (country_code, country_name) VALUES ('$countryCode', '$countryName')";

            // Add to Db
            $db->exec($sql);
            $lastId = $db->lastInsertId();
            $countryMapping[$countryCode] = $lastId;
        }
        echo 'Finished countries' . PHP_EOL;

        // Insert regions
        echo 'Starting regions' . PHP_EOL;
        $regions = file_get_contents($this->base . 'regions.txt');
        $regions = explode(PHP_EOL, $regions);

        // Foreach region
        foreach ($regions as $region) {

            // Check for empty lines
            $region = trim($region);
            if (empty($region)) {
                continue;
            }

            // Construct SQL
            list($countryCode, $regionId, $regionName) = explode(',', $region);
            $regionName = $this->escape(trim($regionName, '"'));

            // Get country Id based on mapping
            $countryCode = $countryMapping[$countryCode];

            $sql = "INSERT INTO regions (region_id, country_id, region_name) VALUES
            ('$regionId', '$countryCode', '$regionName')";

            // Add to Db
            $db->exec($sql);
        }
        echo 'Finished regions' . PHP_EOL;

        // Insert cities (takes longest)
        echo 'Starting cities' . PHP_EOL;
        $file = fopen($this->base . 'cities.txt', 'r');

        // Skip first line
        fgets($file, 4096);

        // Keep track of completed Ids
        $doneCities     = array();
        $lastCountry    = false;
        $skipped        = array();

        // Foreach city
        while (($line = fgets($file, 4096)) !== false) {

            // Construct SQL
            list($countryCode, $asciiName, $cityName, $regionCode, $pop, $lat, $long) = explode(',', $line);

            $asciiName      = $this->escape($asciiName);
            $cityName       = $this->escape($cityName);
            $regionCode     = $this->escape($regionCode);
            $countryCode    = strtoupper($countryCode);

            // Get country Id based on mapping
            if (!isset($countryMapping[strtoupper($countryCode)])) {
                if (!isset($skipped[$countryCode])) {
                    echo 'Skipping cities in country: ' . $countryCode . '. Not a valid country code' . PHP_EOL;
                    $skipped[$countryCode] = true;
                }
                continue;
            }
            $countryCode = $countryMapping[strtoupper($countryCode)];

            // Let's reset done cities so it does not grow out of proportion
            if ($lastCountry == false || $lastCountry != $countryCode){
                $doneCities = array();
                $lastCountry = $countryCode;
            }

            $sql = "INSERT INTO cities (country_id, ascii_name, city_name, region_id) VALUES
            ('$countryCode', '$asciiName', '$cityName', '$regionCode')";

            /*
             * If latitude/longitude already processed, do not add it again
             * The issue with maxmind that it stores multiple variation of the same location
             */
            $key = md5($lat . $long);
            if (isset($doneCities[$key])) {
                continue;
            }
            $doneCities[$key] = true;

            // Add to Db
            $db->exec($sql);
        }
        fclose($file);
        echo 'Finished cities' . PHP_EOL;

        // Close connections
        if (stripos(get_resource_type($db), 'mysql') !== false) {
            mysql_close($db);
            return;
        }

        // Close Db connection
        $db = null;
        return;
    }

    /**
     * Escape Db Argument
     *
     * @param   string  $argument
     *
     * @return  string
     */
    public function escape($argument)
    {
        $searches = array('\\', "\0", "\n", "\r", "'", '"', "\x1a");
        $replaces = array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z');
        return str_replace($searches, $replaces, $argument);
    }
}

$process = new processCities();
$process->process();
cities city countries country geo maxmind parser region regions targeting

Parallel Threaded PHP MySQL Table Level Backup

Posted on October 15, 2012 by Aziz Posted in MySQL, PHP 2 Comments

This class can backup and restore multiple MySQL tables in parallel.

It can take a backup of a MySQL database by running the mysqldump command multiple times in parallel, one time for each database table to backup.

The class can also do the opposite, i.e. restore a MySQL database by running the MySQL command multiple times in parallel to restore all the database tables.

The next step with this class is to make it multiple parallel on table level.
<?php 
/** 
 * ASHDumper.php 
 * 
 * PHP version >= 4.30 
 * 
 * @author    Aziz Hussain <azizsaleh@gmail.com> 
 * @copyright GPL license 
 * @license   http://www.gnu.org/copyleft/gpl.html 
 * @link      http://www.azizsaleh.com 
 */ 

/** 
 * ASHDumper 
 * 
 * Threaded MySQL backup and restore. To use you must have mysql and mysqldump 
 * commands in your environment variables. You also need access to the proc_open function. 
 *  
 * Usage (run php ASHDumper.php [--help]?(>=5.3) for more info) 
 *  
 * To backup a database: 
 * php ASHDumper.php -b yes -h localhost -u root -pPassword -o c:\abspath\to\output\dir 
 * PHP >= 5.3 
 * php ASHDumper.php --backup -h localhost -u root -pPassword -o c:\abspath\to\output\dir 
 * 
 * To restore a database: 
 * php ASHDumper.php -r yes -h localhost -u root -pPassword -o c:\abspath\to\sql\dir 
 * PHP >= 5.3 
 * php ASHDumper.php --restore -h localhost -u root -pPassword -o c:\abspath\to\sql\dir 
 * 
 * To restore a database creating the database: 
 * php ASHDumper.php -r yes -c yes -h localhost -u root -pPassword -o c:\abspath\to\sql\dir 
 * PHP >= 5.3 
 * php ASHDumper.php --restore --create -h localhost -u root -pPassword -o c:\abspath\to\sql\ 
 *  
 * @author    Aziz Hussain <azizsaleh@gmail.com> 
 * @copyright GPL license 
 * @license   http://www.gnu.org/copyleft/gpl.html 
 * @link      http://www.azizsaleh.com 
 */ 
class ASHDumper 
{ 
    /** 
     * Load options, show help if needed 
     * and run restore/backup as specified 
     * 
     * @return void 
     */ 
    public static function load() 
    { 
        // Get options 
        if (phpversion() >= 5.3) { 
            $options = getopt('h:u:p:d:o:c:r:b:', array( 
            'help', 'create', 'backup', 'restore' 
            )); 
        } else { 
            $options = getopt('h:u:p:d:o:c:r:b:'); 
        } 
        // help? 
        if (isset($options['help'])) { 
            self::showHelp(); 
            exit(); 
        } 

        // Options with defaults 
        $fields = array( 
            'h'    => array('hostName', 'localhost'), 
            'u'    => array('userName', 'root'), 
            'p'    => array('password', ''), 
            'o'    => array('outputDir', dirname(__FILE__)), 
        ); 

        // Holder for Db info 
        $dbInfo = array(); 

        // Load optional values 
        foreach ($fields as $opt => $keys) { 
            if (isset($options[$opt])) { 
                $dbInfo[$keys[0]] = $options[$opt]; 
            } 
            if (empty($dbInfo[$keys[0]])) { 
                $dbInfo[$keys[0]] = $keys[1]; 
            }         
        } 

        $dbInfo['outputDir'] = rtrim($dbInfo['outputDir'], '/\\') .  
            DIRECTORY_SEPARATOR; 

        // No database specified 
        if (empty($options['d'])) { 
            self::showHelp(); 
            return; 
        } else { 
            $dbInfo['database'] = $options['d']; 
        } 

        if (isset($options['r']) || isset($options['restore'])) { 
            // Restore DB 
            self::restore($dbInfo, $options); 
            return; 
        } 

        if (isset($options['b'])  || isset($options['backup'])) { 
            // Backup DB 
            self::backup($dbInfo); 
            return; 
        } 

        self::showHelp(); 
        return; 
    } 

    /** 
     * Show Help Message 
     * 
     * @return void 
     */ 
    public static function showHelp() 
    { 
        echo PHP_EOL . '-------------' . PHP_EOL . 'ASHDumper.php' . PHP_EOL . 
        '--------------' . PHP_EOL .  
        'Use this script to backup/restore your database' .  
        ' at a table level.' . PHP_EOL . ' Each table will get its own process' .  
        ' to get backed up and restored' . PHP_EOL . PHP_EOL .  
        '------------' . PHP_EOL . 'REQUIREMENTS' . PHP_EOL . 
        '------------' . PHP_EOL .  
        ' - You need to have proc_open Enabled' . PHP_EOL . 
        ' - You need to have access to mysql/mysqldump' . PHP_EOL . 
        ' - Output directory must exist and must be writable by you' .  
        PHP_EOL . PHP_EOL . 
        '--------' . PHP_EOL . 'OPTIONS' . PHP_EOL .  
        '--------' . PHP_EOL .  
        '-h Host Name of MySQL' . PHP_EOL .  
        '-u User Name of MySQL' . PHP_EOL .  
        '-p Password of MySQL' . PHP_EOL .  
        '-d Database Name of MySQL' . PHP_EOL .  
        '-o Folder of where to store SQL files (backup) ' .  
        'or located (restore)' . PHP_EOL . PHP_EOL . 
        '------' . PHP_EOL . 'USAGE' . PHP_EOL .  
        '------' . PHP_EOL .  
        'To backup a database:' . PHP_EOL .  
        'php ASHDumper.php -b yes -h localhost -u root -pPassword ' .  
        '-o c:\abspath\to\output\dir' . PHP_EOL .  
        '[PHP >= 5.3] php ASHDumper.php --backup -h localhost -u root -pPassword ' .  
        '-o c:\abspath\to\output\dir' . PHP_EOL . PHP_EOL .  
        PHP_EOL . 'To restore a database (DB Must Exist):' . PHP_EOL .  
        'php ASHDumper.php -r yes -h localhost -u root -pPassword -o ' .  
        'c:\abspath\to\sql\dir'. PHP_EOL .  
        'php ASHDumper.php --restore -h localhost -u root -pPassword -o ' .  
        '[PHP >= 5.3] c:\abspath\to\sql\dir'. PHP_EOL . PHP_EOL .         

        PHP_EOL . 'To restore a database (Create DB If It Does Not Exist):' . PHP_EOL .  
        'php ASHDumper.php -r yes -c yes -h localhost -u root -pPassword -o ' .  
        'c:\abspath\to\sql\dir'. PHP_EOL . 
        '[PHP >= 5.3] php ASHDumper.php --restore --create -h localhost -u root -pPassword -o ' .  
        'c:\abspath\to\sql\dir'. PHP_EOL;; 

        return; 
    } 

    /** 
     * Restore a DB 
     *  
     * @param    array    $dbInfo 
     *                    userName    MySQL Username 
     *                    hostName    MySQL Host Name 
     *                    password    MySQL User Password 
     *                    outputDir    Directory to write SQL files to 
     * @param    array    $options    Options Param 
     * 
     * @return void 
     */ 
    public static function restore($dbInfo, $options) 
    { 
        // Create Database if it does not exist 
        if (isset($options['c']) || isset($options['create'])) { 
            self::createIfNotExist($dbInfo); 
        } 

        // Get files to restore 
        $tableList = array(); 
        $files = glob($dbInfo['outputDir'] . '*.sql', GLOB_BRACE); 
        foreach ($files as $file) { 
            $tableList[] = str_replace('.sql', '', basename($file)); 
        } 

        // Command 
        $command = "mysql -u {$dbInfo['userName']} -p{$dbInfo['password']} " .  
        "-h {$dbInfo['hostName']} {$dbInfo['database']} < {$dbInfo['outputDir']}%s.sql"; 

        self::runWorkers($command, $tableList); 

        return; 
    } 

    /** 
     * Backup a DB 
     *  
     * @param    array    $dbInfo 
     *                    userName    MySQL Username 
     *                    hostName    MySQL Host Name 
     *                    password    MySQL User Password 
     *                    outputDir    Directory to read files from 
     * 
     * @return void 
     */ 
    public static function backup($dbInfo) 
    { 
        // Get table list 
        $tableList = self::getTables($dbInfo); 

        // Command 
        $command = "mysqldump -u {$dbInfo['userName']} -p{$dbInfo['password']} " .  
        "-h {$dbInfo['hostName']} {$dbInfo['database']} %s > {$dbInfo['outputDir']}%s.sql"; 

        self::runWorkers($command, $tableList); 

        return; 
    } 

    /** 
     * Get list of tables from DB, used in the backup method 
     * 
     * @param    array    $dbInfo 
     *                    userName    MySQL Username 
     *                    hostName    MySQL Host Name 
     *                    password    MySQL User Password 
     * 
     * @return     array 
     */ 
    public static function getTables($dbInfo) 
    { 
        $tables = array(); 
        try { 
            // Connect to db 
            $dsn = "mysql:dbname={$dbInfo['database']};host={$dbInfo['hostName']}"; 
            $db = new Pdo($dsn, $dbInfo['userName'], $dbInfo['password']); 

            $result = $db->query("show tables"); 
            while ($row = $result->fetch(PDO::FETCH_NUM)) { 
                $tables[] = $row[0]; 
            } 
        } catch (PDOException $e) { 
            // Any errors, show them to user 
            echo 'Failed: ' . $e->getMessage(); 
            exit(); 
        } 

        return $tables; 
    } 

    /** 
     * Create database if it does not exist 
     * 
     * @param    array    $dbInfo 
     *                    userName    MySQL Username 
     *                    hostName    MySQL Host Name 
     *                    password    MySQL User Password 
     *                    database    Database Name 
     * 
     * @return     void 
     */ 
    public static function createIfNotExist($dbInfo) 
    { 
        try { 
            // Connect to db 
            $dsn = "mysql:host={$dbInfo['hostName']}"; 
            $db = new Pdo($dsn, $dbInfo['userName'], $dbInfo['password']); 
            // Create database 
            $db->query("CREATE DATABASE IF NOT EXISTS `{$dbInfo['database']}`"); 
        } catch (PDOException $e) { 
            // Any errors, show them to user 
            echo 'Failed: ' . $e->getMessage(); 
            exit(); 
        } 

        return; 
    } 

    /** 
     * Run a worker for each table 
     * 
     * @param    string    $jobCommand        Command to execute 
     * @param    array    $tables            List of tables to process 
     * 
     * @return void 
     */ 
    public static function runWorkers($jobCommand, $tables) 
    { 
        // presets 
        $threads        = array(); 
        $resultStream    = array(); 
        $tableRealtion    = array(); 
        $options        = array(1 => array('pipe', 'w')); 

        // Counts 
        $tableCount        = count($tables); 
        $doneCount        = 0; 

        // Start workers 
        while (true) { 
            // Any tables left to do? 
            if (count($tables) > 0) { 

                $table = array_shift($tables); 
                // Construct the process command with process ID & current db to use 
                $command = sprintf($jobCommand, $table, $table); 

                $pipes = array(); 

                // open thread 
                $threads[]            = proc_open($command, $options, $pipes); 
                $resultStream[]        = $pipes; 
                $tableRealtion[]    = $table; 

                // If this thread started 
                if (end($threads) == false) { 
                    // If it fails, close the thread & pipe 
                    $closeCount = count($threads)-1; 
                    unset($threads[$closeCount]); 
                    unset($resultStream[$closeCount]); 
                    unset($tableRealtion[$closeCount]); 

                    // Put table back in if failed 
                    array_unshift($tables, $table); 
                } 
            } else if (count($threads) <= 0) { 
                break; 
            } 

            foreach($threads as $sub => $thisThread) { 
                // Get the status 
                $status = proc_get_status($thisThread); 
                // If its not running or stopped, close it & get the results 
                if ($status['running'] != 'true' || $status['signaled'] == 'true') { 
                    $doneCount++; 
                    $results = stream_get_contents($resultStream[$sub][1]); 

                    // Any errors 
                    if (!empty($results)) { 
                        echo 'Error processing table ' . $tableRealtion[$sub] .  
                        ': ' . $results . PHP_EOL; 
                    } else { 
                        echo 'Completed Table: ' . $tableRealtion[$sub] . PHP_EOL; 
                    } 

                    echo ($tableCount - $doneCount) . ' Tables Remaining' . PHP_EOL . PHP_EOL; 

                    // Close the pipe & threads                     
                    fclose($resultStream[$sub][1]); 
                    unset($threads[$sub]); 
                    unset($resultStream[$sub]); 
                    unset($tableRealtion[$sub]); 
                } 
            } 
        } 
    } 
} 

ASHDumper::load();
db mysql php

Now listed on the PHP Yellow Pages – PHP Certification

Posted on November 21, 2011 by Aziz Posted in PHP Leave a comment

AZIZ S. HUSSAIN

Zend Certified Engineer

ClientCandidateID: ZEND013689
RegistrationID: 245239360
Certification date:
Nov 21st, 2011
City: Sarasota
State / Province / Region: FL, Florida
Country: United States


certification php

Netflix API 1.0 Wrapper is finally out

Posted on February 27, 2011 by Aziz Posted in PHP Leave a comment
I was over Netflix and saw that their API had no PHP implementation. So I created this simple application that allows users to access Netflix’s API via PHP.

Script URL

Demo

Download

Hope you enjoy It 🙂

If none of the APIs work, its probably because I have exceeded by maximum number of connections per day.

Aziz

php_ssh2.dll VC6, VC7, VC8, VC9

Posted on December 23, 2010 by Aziz Posted in PHP Leave a comment

Update: Sorry I have seemed to misplace the files on this post. I will try and regenerate them as soon as I can.

Just incase anyone needed it.They all are extracted from VC9 but used hex editor to fool PHP to think it was to which it is labeled.

I am using it as VC6 and it works great.

php_ssh2.dll VC6
php_ssh2.dll VC7
php_ssh2.dll VC8
php_ssh2.dll VC9

PHP Object Merge and In Object Functions – object_merge

Posted on December 1, 2010 by Aziz Posted in PHP Leave a comment

These are two functions to manipulate PHP objects.

The first function is similar to array_merge function in that it merges two objects based on an index.

The second function in_object also acts like in_array to which it checks if a certain index exists in an array at a specific value.

Hopefully someone finds it helpful.

 

<?php

// Object merge and in Object functions
function object_merge($objectFrom,$objectTo,$indexUse) 
{ 
    $objectReturn = array(); 
    foreach($objectFrom as $curObject) 
    {         
        $index = in_object($indexUse,$curObject->$indexUse,$objectTo,true); 
        if(is_int($index)) 
        { 
            foreach($objectTo[$index] as $indexName => $indexValue) 
            { 
                $curObject->$indexName = $indexValue; 
            } 
        } 
        $objectReturn[] = (object) $curObject;         
    } 
    return $objectReturn; 
} 

function in_object($searchFor,$searchValue,$objectSearch,$returnResult) 
{ 
    foreach($objectSearch as $index => $thisObject) 
    { 
        if($thisObject->$searchFor == $searchValue) 
        { 
            if($returnResult) 
            { 
                return $index; 
            } else { 
                return true; 
            } 
        } 
    } 
    return false; 
} 

// Usage 
$obj1[0] = (object) array('catId' => 1, 'catName' => 'Name'); 
$obj1[1] = (object) array('catId' => 2, 'catName' => 'Name2'); 

$obj2[0] = (object) array('catId' => 1, 'catDesc' => 'Desc'); 
$obj2[1] = (object) array('catId' => 2, 'catDesc' => 'Desc2'); 

$obj_merged = object_merge($obj1,$obj2,'catId'); 
print_r($obj_merged);

MegaVideo Premium Link Scraper

Posted on August 26, 2010 by Aziz Posted in PHP Leave a comment

This class will allow you to scrape MegaVideo Premium Links to share or use for your own.

Please note that you need to follow these steps:

1) Login into your account at MegaVideo (or MegaUpload).
2) View your cookies that you got from whichever site you loged into.
3) Replace USERNUMBER and SESSIONID with your user number and session id from the cookies in the attached file: megavideoCookie.txt.

If you do this excessively, MegaVideo will ban your IP, so you will have to renew your IP every now and then (depending on how heavy the load is).

Enjoy. Let me know if you have any problems.

Sample Implementation:

<?php
/*
MegaVideo Video Scraper
Premium Account Required
Written by Aziz S. Hussain
@
www.AzizSaleh.com
Produced under LGPL license
@
http://www.gnu.org/licenses/lgpl.html

Example Use of the class: megavideo.class.php
*/

# Include Main Class
require_once('megavideo.class.php');

# Setup the URL
$newVideo = new megaVideo('http://www.megavideo.com/?v=6PTHEVUY');
# Work to get the link
$newVideo->doScrape();
# You now have the link
echo $newVideo->getLink();
# The link can be used for download or stream
# To use for stream, you will need a flash player like JW Flash Player
# http://www.longtailvideo.com/players/jw-flv-player/

Main Class:

<?php

/*
MegaVideo Video Scraper
Premium Account Required
Written by Aziz S. Hussain
@
www.AzizSaleh.com
Produced under LGPL license
@
http://www.gnu.org/licenses/lgpl.html


Class Structure

class megaVideo
{
    # MegaVideo link
    private megaVideoURL
    # Final link
    private finalLink
    
    void __construct(string videoURL)                    # Store video link    
    array getMegaVideoVars(string megaVideoURL)            # Returns vars needed to create viewing key
    string decrypt(string str, string key1, string key2)# Actually decrypts the vars into the key
    void doScrape()                                        # Does the scraping
    string getLink()                                    # Return the URL for download or streaming        
}
*/

class megaVideo
{
    # MegaVideo link
    private $megaVideoURL;
    # Final link
    private $finalLink;
    
    # Construct, just store the vide link
    function __construct($videoURL)
    {
        $this->finalLink = $videoURL;
    }
    
    # This function will return the megaVideo vars
    # Note that it uses CURL and the COOKIE megavideoCookie.txt
    # Cookie text file must be in this format: 
    /*
    
    # Netscape HTTP Cookie File
    # http://www.netscape.com/newsref/std/cookie_spec.html
    # This file was generated by libcurl! Edit at your own risk.

    .megavideo.com    TRUE    /    FALSE    1263332544    user     4BDHJJNEJOKDF4KJHKJFJIUGHUYG3.JKLHDU4

    */
    # You need to change the user number 1263332544 and session  4BDHJJNEJOKDF4KJHKJFJIUGHUYG3.JKLHDU4
    # You can get that information by viewing the cookie information (using firefox)
    # URL passed must be in this format: http://www.megavideo.com/?v=6PTHEVUY
    function getMegaVideoVars()
    {
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL,$this->finalLink);
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'megavideoCookie.txt');
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'megavideoCookie.txt');
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    
        $buffer = curl_exec($ch);
        curl_close($ch);
        preg_match('/flashvars\.un = "(.*)";.*flashvars\.k1 = "(.*)";.*flashvars\.k2 = "(.*)";.*flashvars\.s = "(.*)";/Ums',
                $buffer,$results);
        # Return required vars
        $finalResults = array($results[4],$results[1],$results[2],$results[3]);
        return $finalResults;
    }


    # This function will decrypt the required keys form megavideo
    function decrypt($str, $key1, $key2)
    {
        $reg1 = array();
        for($reg3=0; $reg3<strlen($str); $reg3++)
        {
            $reg0 = $str[$reg3];
       
            switch($reg0)
            {
              case '0': $reg1[] = '0000'; break;
              case '1': $reg1[] = '0001'; break;
              case '2': $reg1[] = '0010'; break;
              case '3': $reg1[] = '0011'; break;
              case '4': $reg1[] = '0100'; break;
              case '5': $reg1[] = '0101'; break;
              case '6': $reg1[] = '0110'; break;
              case '7': $reg1[] = '0111'; break;
              case '8': $reg1[] = '1000'; break;
              case '9': $reg1[] = '1001'; break;
              case 'a': $reg1[] = '1010'; break;
              case 'b': $reg1[] = '1011'; break;
              case 'c': $reg1[] = '1100'; break;
              case 'd': $reg1[] = '1101'; break;
              case 'e': $reg1[] = '1110'; break;
              case 'f': $reg1[] = '1111'; break;
           }
        }
          
        $reg1 = join($reg1);
        $reg6 = array();
          
        for($reg3=0; $reg3<384; $reg3++)
        {
            $key1 = ($key1 * 11 + 77213) % 81371;
            $key2 = ($key2 * 17 + 92717) % 192811;
            $reg6[] = ($key1 + $key2) % 128;
        }
          
        for($reg3=256; $reg3>=0; $reg3--)
        {
            $reg5 = $reg6[$reg3];
            $reg4 = $reg3 % 128;
            $reg8 = $reg1[$reg5];
            $reg1[$reg5] = $reg1[$reg4];
            $reg1[$reg4] = $reg8;
        }
          
        for($reg3=0; $reg3<128; $reg3++)
        {
            $reg1[$reg3] = $reg1[$reg3] ^ ($reg6[$reg3+256] & 1);   
        }
          
        $reg12 = $reg1;
        $reg7 = array();
          
        for($reg3=0; $reg3<strlen($reg12); $reg3+=4)
        {
            $reg9 = substr($reg12, $reg3, 4);
            $reg7[] = $reg9;
        }
          
        $reg2 = array();
          
        for($reg3=0; $reg3<count($reg7); $reg3++)
        {
            $reg0 = $reg7[$reg3];
            switch($reg0)
            {
              case '0000': $reg2[] = '0'; break;
              case '0001': $reg2[] = '1'; break;
              case '0010': $reg2[] = '2'; break;
              case '0011': $reg2[] = '3'; break;
              case '0100': $reg2[] = '4'; break;
              case '0101': $reg2[] = '5'; break;
              case '0110': $reg2[] = '6'; break;
              case '0111': $reg2[] = '7'; break;
              case '1000': $reg2[] = '8'; break;
              case '1001': $reg2[] = '9'; break;
              case '1010': $reg2[] = 'a'; break;
              case '1011': $reg2[] = 'b'; break;
              case '1100': $reg2[] = 'c'; break;
              case '1101': $reg2[] = 'd'; break;
              case '1110': $reg2[] = 'e'; break;
              case '1111': $reg2[] = 'f'; break;
            }
        }
        return join($reg2);
    }
    
    # Actually return the URL that the video can be viewed without time restrictions
    function doScrape()
    {
        # Retrieve info
        list($serverID,$un,$k1,$k2) = $this->getMegaVideoVars();
        # Get the key
        $decKey = $this->decrypt($un,$k1,$k2);
        
        $this->finalLink = "http://www$serverID.megavideo.com/files/$decKey/randomName$un.flv";
    }
    
    # Return the link begotten after scraping
    function getLink()
    {
        return $this->finalLink;
    }    

}

Cookie File:

# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.
# MegaVideo Premium Link Scraper by Aziz S. Hussain
# @ www.AzizSaleh.com


.megavideo.com    TRUE    /    FALSE    USERNUMBER    user     USERSESSION

Next Page »

Recent Posts

  • PHP does not have MySQL support enabled.
  • Your PHP installation appears to be missing the MySQL extension which is required by WordPress
  • Undefined mysql functions (mysql_connect, mysql_select_db, mysql_query) – PDO alternative
  • Checking if you have Javascript installed by PHP
  • Process Maxmind countries, regions and cities – Parser to MySQL or SqLite

Recent Comments

  • fathima on Currency Converter Using Java Netbeans
  • Chris on Currency Converter
  • Khalid Ahmad Qweder on Resume & Portfolio
  • Michel on Currency Converter
  • Michel on Currency Converter

Archives

  • March 2014
  • September 2013
  • November 2012
  • October 2012
  • November 2011
  • February 2011
  • December 2010
  • November 2010
  • August 2010
  • May 2010
  • September 2009

Categories

  • Flash Builder 4
  • General
  • Java
  • Javascript
  • MySQL
  • PHP
  • Visual Basic

Meta

  • Register
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
CyberChimps ©2025