Facebook

Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Saturday, January 2, 2016

Function to render text as image - escape spam bots


Escaping contact information from spam bots is one of the major challenges developers facing. Converting the text to image and rendering as image is one basic solution. Here is a function I use.
Function to render text as image
<img src="<?php echo render_text_image('test image', 183, 50);?>" />


function render_text_image($string, $width, $height, $text_align_pos = 0)
{


    $img = imagecreatetruecolor($width, $height);

    $imageX = imagesx($img);
    $imageY = imagesy($img);

    imagealphablending($img, false);
    imagesavealpha($img, true);

    $transparent = imagecolorallocatealpha($img, 255,255,255, 127);
    $white = imagecolorallocate($img, 129, 78, 16);
    $black = imagecolorallocate($img, 0, 0, 0);
    $grey = imagecolorallocate($img, 127,127,127);
    //imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
    imagefilledrectangle($img, 0, 0, $imageX, $imageY, $transparent);

    $font = ROOT_DIRECTORY . "assets/font/arialbd.ttf";
    //$font = ROOT_DIRECTORY . "assets/font/arialbd.ttf";
    $fontSize = 12;
    $text = $string;

    $textDim = imagettfbbox($fontSize, 0, $font, $text);
    $textX = $textDim[2] - $textDim[0];
    $textY = $textDim[7] - $textDim[1];

    $text_posX = ($text_align_pos== "center") ? ($imageX / 2) - ($textX / 2) : $text_align_pos;
    $text_posY = ($imageY / 2) - ($textY / 2);

    imagealphablending($img, true);
    imagettftext($img, $fontSize, 0, $text_posX, $text_posY, $white, $font, $text);
    //ImageString($img,2,0,0, $text,$black);
    //Get image to a variable
    ob_start();
    imagepng($img);
    // Capture the output
    $imagedata = ob_get_contents();
    // Clear the output buffer
    ob_end_clean();

    return "data:image/png;base64," . base64_encode($imagedata);
}

Sunday, December 6, 2015

php file upload: clean name of uploaded file, check for duplicate


File upload: clean name of uploaded file, check for duplicate
$config['upload_path'] = DIR_UPLOAD_BANNER;

$file_parts = pathinfo($_FILES['cms_banner_image']['name']);

//Clean file name, replace all specialcharacters with dahs "-" $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $file_parts['filename']);

//Replace multiple dash with single $file_name = preg_replace('/-+/', '-', $file_name); $config['file_name'] = $file_name.'.'.$file_parts['extension'];

//Check for duplicate file names $counter = 0;
while (file_exists($config['upload_path'].$config['file_name'])) {
    $counter++;
    $config['file_name'] = $file_name.'_'.
                           $counter.'.'.
                           $file_parts['extension'];
}

Thursday, November 5, 2015

PHP Tips and Tricks - Handy


1. ini_set('memory_limit', '-1');
Usage: To temporarily set memory limit to unlimited

2. ini_set('memory_limit', '512M');
Usage: How to temporarily set memory limit to 512MB

3. set_time_limit(0);

4. ini_set('max_execution_time', 0);
Usage: How to temporarily set max execution time to infinite

5. error_reporting(E_ALL);
Usage: Report all PHP errors

6. error_reporting(0);
Usage: Turn off all error reporting

7. ini_set("display_errors", 1);
Usage: Run-time configuration

8.
function getClientIp()
{
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
}
Usage: Get user ip

/*
 *9.Generate accented seo friendly url
 */

function accented_seo_url($str) {
    mb_internal_encoding('UTF-8');
    $str = utf8_encode($str);

    $new_string = preg_replace('~[^\\pL\d]+~u', "-", ltrim(rtrim(($str))));

    return mb_strtolower($new_string);
}
Usage: Generate accented seo friendly url

10. header('Content-Type: text/html; charset=utf-8');
Usage: Set utf8 in header

11.
/*
* Get 2nd monday of the month
*/

//First monday of the month
$dt = new DateTime('first Monday of jan 2017');

//Second monday of the month
$interval = new DateInterval('P1W');
$next_week = $dt->add($interval);
echo $next_week->format('Y-m-d');
Usage: Get 2nd monday of the month. Example https://eval.in/716901
12.
/*
* Get 3rd tuesday of the month
*/

//First tuesday of the month
$dt = new DateTime('first Tuesday of jan 2017');

//Third Tuesday of the month
$interval = new DateInterval('P2W');
$next_week = $dt->add($interval);
echo $next_week->format('Y-m-d');
Usage: Get 3rd Tuesday of the month. Example https://eval.in/716901

Monday, October 26, 2015

PHPAutomatedDbBackup

Credits: David Walsh for his db backup script. http://davidwalsh.name/backup-mysql-database-php

I implemented a script that can be run via cron, and can schedule different time for backing up diffrent databases.
It reads details of databases scheduled to back up at the toime of execution and create backup
You can schedule the backup of different databases at different time.
The time precision check for minutes only

How to setu-up

Move the code to your server under a directory say "DB_Backup"
Create a database, and a table with this structure

CREATE TABLE IF NOT EXISTS `table_credentials` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `host` varchar(255) NOT NULL DEFAULT 'localhost',
  `db_name` varchar(255) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `scheduled_execution_time` time NOT NULL,
  `created_date_time` datetime NOT NULL,
  `updated_date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `execution_status` enum('0','1','2','3') NOT NULL DEFAULT '0',
  `last_execution_date` datetime NOT NULL,
  `created_ip` varchar(50) NOT NULL,
  `updated_ip` varchar(50) NOT NULL,
  `is_active` enum('0','1') NOT NULL DEFAULT '1',
  `is_mannual` enum('0','1') NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Now update config.php with your db username, password etc.

Add the credentials of databases you want to backup
If you want to backup 5 databases at 12:00 am and 5 other at 1:00 am the make the value of scheduled_execution_time '12:00:00' for the first 5 databases and '1:00:00' for the next 5 databases.

Now schedule the cron to to execute

ROOT_DIRECTORY/DB_Backup/backup_db.php at 12:00 and 1:00

Thats it.

Any suggestion, updates and modification is welcome

Friday, June 29, 2012

MySql Backup Class



MySql Backup Class  written by Vagharshak Tozalakyan <vagh@armdex.com>

This class is written in a file mysql_backup.class.php
This file is to be included in the file where we actually call this class to be executed.




HOW TO USE


HOW TO USE

1. Create the instance of MySQL_Backup class.
2. Define necessary properties.
3. Call Execute() method to create backup.

require_once 'mysql_backup.class.php';
$backup_obj = new MySQL_Backup();
$backup_obj->server = 'localhost';
$backup_obj->username = 'username';
$backup_obj->password = 'password';
$backup_obj->database = 'dbname';
$backup_obj->tables = array();
$backup_obj->drop_tables = true;
$backup_obj->struct_only = false;
$backup_obj->comments = true;
$backup_obj->fname_format = 'd_m_y__H_i_s';
if (!$backup_obj->Execute(MSB_DOWNLOAD, '', true))
{
  die($backup_obj->error);
}



PUBLIC PROPERTIES

var $server = 'localhost';
The name of MySQL server.

var $port = 3306;
The port of MySQl server.

var $username = 'root';
Database username.

var $password = '';
Database password.

var $database = '';
Name of the database.

var $link_id = -1;
MySQL link identifier of the current connection. You can set this if you
want to connect the MySQL server by your own.

var $connected = false;
Set true if the connection is already established before calling Execute().

var $tables = array();
Tables you want to backup. All tables in the database will be backed up if
this array is empty.

var $drop_tables = true;
Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.

var $struct_only = false;
Only structure of the tables will be backed up if true.

var $comments = true;
Include comments in backup file if true.

var $backup_dir = '';
Directory on the server where the backup file will be placed. Used only if task
parameter equals to MSB_SAVE in Execute() method.

var $fname_format = 'd_m_y__H_i_s';
Default file name format.

var $error = '';
Error message.


PUBLIC METHODS

function Execute($task = MSB_STRING, $fname = '', $compress = false)
$task - operation to perform: MSB_STRING - return SQL commands as a string;
  MSB_SAVE - create the backup file on the server; MSB_DOWNLOAD - save backup
  file in the user's computer.
$fname - optional name of backup file.
$compress - use GZip compression?




mysql_backup.class.php
<?php

/*
  MySQL database backup class, version 1.0.0
  Written by Vagharshak Tozalakyan <vagh@armdex.com>
  Released under GNU Public license
*/


define('MSB_VERSION', '1.0.0');

define('MSB_NL', "\r\n");

define('MSB_STRING', 0);
define('MSB_DOWNLOAD', 1);
define('MSB_SAVE', 2);

class MySQL_Backup
{

  var $server = 'localhost';
  var $port = 3306;
  var $username = 'root';
  var $password = '';
  var $database = '';
  var $link_id = -1;
  var $connected = false;
  var $tables = array();
  var $drop_tables = true;
  var $struct_only = false;
  var $comments = true;
  var $backup_dir = '';
  var $fname_format = 'd_m_y__H_i_s';
  var $error = '';


  function Execute($task = MSB_STRING, $fname = '', $compress = false)
  {
    if (!($sql = $this->_Retrieve()))
    {
      return false;
    }
    if ($task == MSB_SAVE)
    {
      if (empty($fname))
      {
        $fname = $this->backup_dir;
        $fname .= date($this->fname_format);
        $fname .= ($compress ? '.sql.gz' : '.sql');
      }
      return $this->_SaveToFile($fname, $sql, $compress);
    }
    elseif ($task == MSB_DOWNLOAD)
    {
      if (empty($fname))
      {
        $fname = date($this->fname_format);
        $fname .= ($compress ? '.sql.gz' : '.sql');
      }
      return $this->_DownloadFile($fname, $sql, $compress);
    }
    else
    {
      return $sql;
    }
  }


  function _Connect()
  {
    $value = false;
    if (!$this->connected)
    {
      $host = $this->server . ':' . $this->port;
      $this->link_id = mysql_connect($host, $this->username, $this->password);
    }
    if ($this->link_id)
    {
      if (empty($this->database))
      {
        $value = true;
      }
      elseif ($this->link_id !== -1)
      {
        $value = mysql_select_db($this->database, $this->link_id);
      }
      else
      {
        $value = mysql_select_db($this->database);
      }
    }
    if (!$value)
    {
      $this->error = mysql_error();
    }
    return $value;
  }


  function _Query($sql)
  {
    if ($this->link_id !== -1)
    {
      $result = mysql_query($sql, $this->link_id);
    }
    else
    {
      $result = mysql_query($sql);
    }
    if (!$result)
    {
      $this->error = mysql_error();
    }
    return $result;
  }


  function _GetTables()
  {
    $value = array();
    if (!($result = $this->_Query('SHOW TABLES')))
    {
      return false;
    }
    while ($row = mysql_fetch_row($result))
    {
      if (empty($this->tables) || in_array($row[0], $this->tables))
      {
        $value[] = $row[0];
      }
    }
    if (!sizeof($value))
    {
      $this->error = 'No tables found in database.';
      return false;
    }
    return $value;
  }


  function _DumpTable($table)
  {
    $value = '';
    $this->_Query('LOCK TABLES ' . $table . ' WRITE');
    if ($this->comments)
    {
      $value .= '#' . MSB_NL;
      $value .= '# Table structure for table `' . $table . '`' . MSB_NL;
      $value .= '#' . MSB_NL . MSB_NL;
    }
    if ($this->drop_tables)
    {
      $value .= 'DROP TABLE IF EXISTS `' . $table . '`;' . MSB_NL;
    }
    if (!($result = $this->_Query('SHOW CREATE TABLE ' . $table)))
    {
      return false;
    }
    $row = mysql_fetch_assoc($result);
    $value .= str_replace("\n", MSB_NL, $row['Create Table']) . ';';
    $value .= MSB_NL . MSB_NL;
    if (!$this->struct_only)
    {
      if ($this->comments)
      {
        $value .= '#' . MSB_NL;
        $value .= '# Dumping data for table `' . $table . '`' . MSB_NL;
        $value .= '#' . MSB_NL . MSB_NL;
      }
      $value .= $this->_GetInserts($table);
    }
    $value .= MSB_NL . MSB_NL;
    $this->_Query('UNLOCK TABLES');
    return $value;
  }


  function _GetInserts($table)
  {
    $value = '';
    if (!($result = $this->_Query('SELECT * FROM ' . $table)))
    {
      return false;
    }
    while ($row = mysql_fetch_row($result))
    {
      $values = '';
      foreach ($row as $data)
      {
        $values .= '\'' . addslashes($data) . '\', ';
      }
      $values = substr($values, 0, -2);
      $value .= 'INSERT INTO ' . $table . ' VALUES (' . $values . ');' . MSB_NL;
    }
    return $value;
  }


  function _Retrieve()
  {
    $value = '';
    if (!$this->_Connect())
    {
      return false;
    }
    if ($this->comments)
    {
      $value .= '#' . MSB_NL;
      $value .= '# MySQL database dump' . MSB_NL;
      $value .= '# Created by MySQL_Backup class, ver. ' . MSB_VERSION . MSB_NL;
      $value .= '#' . MSB_NL;
      $value .= '# Host: ' . $this->server . MSB_NL;
      $value .= '# Generated: ' . date('M j, Y') . ' at ' . date('H:i') . MSB_NL;
      $value .= '# MySQL version: ' . mysql_get_server_info() . MSB_NL;
      $value .= '# PHP version: ' . phpversion() . MSB_NL;
      if (!empty($this->database))
      {
        $value .= '#' . MSB_NL;
        $value .= '# Database: `' . $this->database . '`' . MSB_NL;
      }
      $value .= '#' . MSB_NL . MSB_NL . MSB_NL;
    }
    if (!($tables = $this->_GetTables()))
    {
      return false;
    }
    foreach ($tables as $table)
    {
      if (!($table_dump = $this->_DumpTable($table)))
      {
        $this->error = mysql_error();
        return false;
      }
      $value .= $table_dump;
    }
    return $value;
  }


  function _SaveToFile($fname, $sql, $compress)
  {
    if ($compress)
    {
      if (!($zf = gzopen($fname, 'w9')))
      {
        $this->error = 'Can\'t create the output file.';
        return false;
      }
      gzwrite($zf, $sql);
      gzclose($zf);
    }
    else
    {
      if (!($f = fopen($fname, 'w')))
      {
        $this->error = 'Can\'t create the output file.';
        return false;
      }
      fwrite($f, $sql);
      fclose($f);
    }
    return true;
  }


  function _DownloadFile($fname, $sql, $compress)
  {
    header('Content-disposition: filename=' . $fname);
    header('Content-type: application/octetstream');
    header('Pragma: no-cache');
    header('Expires: 0');
    echo ($compress ? gzencode($sql) : $sql);
    return true;
  }

}

?>




execute_db_backup.php

<?
/*
|-----------------------
|Example MySQL Backup File  
|  
|Written by: Justin Keller <kobenews@cox.net>
|Released under GNU Public license.
|
|Only use with MySQL database backup class,
|version 1.0.0 written by Vagharshak Tozalakyan
|<vagh@armdex.com>.
|-----------------------
*/

require_once 'mysql_backup.class.php';
$backup_obj = new MySQL_Backup();

//--- EDIT - REQUIRED SETUP VARIABLES ------->>

$backup_obj->server = 'localhost';
$backup_obj->port = 3306;
$backup_obj->username = '';
$backup_obj->password = '';
$backup_obj->database = '';

//Tables you wish to backup. All tables in the database will be backed up if this array is null.
$backup_obj->tables = array();

//--- END - REQUIRED SETUP VARIABLES  ------->>

//---OPTIONAL PREFERENCE VARIABLES ------->>

//Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.
$backup_obj->drop_tables = true;

//Only structure of the tables will be backed up if true.
$backup_obj->struct_only = false;

//Include comments in backup file if true.
$backup_obj->comments = true;

//Directory on the server where the backup file will be placed. Used only if task parameter equals MSB_SAVE.
$backup_obj->backup_dir = '/';

//Default file name format.
$backup_obj->fname_format = 'm_d_Y';

//---END - OPTIONAL PREFERENCE VARIABLES ------->>

//---EDIT - REQUIRED EXECUTE VARIABLES ------->>

/*
Task:
MSB_STRING - Return SQL commands as a single output string.
MSB_SAVE - Create the backup file on the server.
MSB_DOWNLOAD - Download backup file to the user's computer.

*/
$task = MSB_DOWNLOAD;

//Optional name of backup file if using 'MSB_SAVE' or 'MSB_DOWNLOAD'. If nothing is passed, the default file name format will be used.
$filename = '';

//Use GZip compression if using 'MSB_SAVE' or 'MSB_DOWNLOAD'?
$use_gzip = true;

//---END - REQUIRED EXECUTE VARIABLES ------->>

//---NO NEED TO ANYTHING BELOW THIS LINE ------->>

if (!$backup_obj->Execute($task, $filename, $use_gzip))
{
$output = $backup_obj->error;
}
else
{
$output = 'Operation Completed Successfully At: <b>' . date('g:i:s A') . '</b><i> ( Local Server Time )</i>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>MySQL Backup</title>
</head>
<body>
<?
echo $output;
?>
</body>
</html>

Saturday, December 3, 2011

How to change PHP's eregi to preg_match



This function eregi has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Now what we need is to replace the eregi functions used in our old applications with some new functions that are still not depreciated...
First i will describe functionality of eregi() and then i will go for appropriate function to replace it.

eregi():
eregi — Case insensitive regular expression match
Syntax:

int eregi ( string $pattern , string $string [, array &$regs ] )

This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters.


Parameters






pattern
Case insensitive regular expression.
string
The input string.
regs
If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.
$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.


return Values

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.
If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

A good alternative is to use preg_match() function

Now lets talk about preg_match

preg_match — Perform a regular expression match

Description

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int$offset = 0 ]]] )
Searches subject for a match to the regular expression given in pattern.

More details can be found at php.net http://in2.php.net/manual/en/function.preg-match.php

Now How to replace eregi with preg_match


You will need to change three things
  1. need to add pattern delimiters (can be any character, but most commonly a forward slash)
  2. [[:alnum:]] will need to be replaced with the PCRE equivalent
  3. The "i" in "eregi" means case-insensitive, which PCRE does with a flag, specifically the i flag.
Otherwise, the rest looks PCRE compatible (yes, that's kind of redundant =P)
"/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i"


Thursday, December 1, 2011

How to change version of php in Xampp


Take this example that makes PHP version from 5.3 to 5.2 in Xampp


  1. Download and install latest xampp to G:\xampp. As of 2010/03/12, this is 1.7.3.
  2. Download the zip of xampp-win32-1.7.0.zip, which is the latest xampp distro without php 5.3. Extract somewhere, e.g. G:\xampp-win32-1.7.0\
  3. Remove directory G:\xampp\php
  4. Remove G:\xampp\apache\modules\php5apache2_2.dll and php5apache2_2_filter.dll
  5. Copy G:\xampp-win32-1.7.0\xampp\php to G:\xampp\php.
  6. Copy G:\xampp-win32-1.7.0\xampp\apache\bin\php* to G:\xampp\apache\bin
  7. Edit G:\xampp\apache\conf\extra\httpd-xampp.conf.
    • Immediately after the line, <IfModule alias_module> add the lines
(snip)
<IfModule mime_module>
  LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"
  AddType application/x-httpd-php-source .phps
  AddType application/x-httpd-php .php .php5 .php4 .php3 .phtml .phpt
    <Directory "/xampp/htdocs/xampp">
      <IfModule php5_module>
        <Files "status.php">
            php_admin_flag safe_mode off
        </Files>
      </IfModule>
    </Directory>
</IfModule>
(Note that this is taken from the same file in the 1.7.0 xampp distribution. If you run into trouble, check that conf file and make the new one match it.)
You should then be able to start the apache server with PHP 5.2.8. You can tail the G:\xampp\apache\logs\error.log file to see whether there are any errors on startup. If not, you should be able to see the XAMPP splash screen when you navigate to localhost.