Wednesday, June 10, 2015

Get webpage loading time using PHP



Execution of server side scripting need to optimize in order to get the Optimized page loading time. In this case most of the Server Side Response typically not more than 2 to 30 seconds. In this case we need to find the Exact page loading time in PHP using the following Script.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

function page_loading_time()
{
    list ($msec, $sec) = explode(' ', microtime());
    $microtime = (float)$msec + (float)$sec;
    return $microtime;
}

$start=page_loading_time();

usleep(100000);  // Delaying page output 0.1 second for testing purpose.

echo "
";
$end = page_loading_time();
// Print results.
echo 'Page Loading Time: ' . round($end - $start, 2) . ' seconds';   


?>

Friday, May 29, 2015

Generate and save file in directory using PHP

4everTutorials

In this lesson we will see how to generate file and save into new directory using PHP. So we will generate a HTML, PHP or any other type of file and save it into a newly created or existed directory.

Step 1: At first we have to select an existing directory or create a new directory by using mkdir() function.


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$dir_path = "depth1/depth2/depth3";
 
mkdir($dir_path, 0777, true);

?>

Here, $dir_path is the path to the expected directory/folder of your hard drive.
And ’0777′ is the default permission of the folder/file (widest possible access).

So, the file will be located in this directory: current_directory/depth1/depth2/depth3

But if you want to create the folder outside the current directory, then use “../” for each level you want to go back for the new directory.

For example, if your current directory is “C:\xampp\htdocs\cd” and you want to create the new folder inside “xampp” folder then you have to write like the following-


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$dir_path = "../../test";
 
mkdir($dir_path, 0777, true);

?>


So, path for the new directory will be “C:\xampp\test”.

Step 2: After creating the directory simply put the generated file to the directory by using file_put_contents() function.

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

file_put_contents($dir_path."/name-of-file.html", $content);
file_put_contents($dir_path."/name-of-file.php", $content);
file_put_contents($dir_path."/name-of-file.txt", $content);

?>

Here, name-of-file is the expected name of your file and $content is the the data that you want to save in the file.

Thursday, May 7, 2015

Text rasterization service script using php


This is an example of using Gd / FreeType to generate image text labels with TTF font. Provided script could be used as "text rasterization service" to generate arbitrarily text-images for a web site. MD5-based authorization is used to avoid image generation by unauthorized users.

Compatible with:

PHP 5 or higher
PHP 4.1 or higher
Gd 2.x, FreeType support in PHP


Our "text rasterization service" does the following:

Receives text generation parameters(text and font-size) and md5 sign of secret key + parameters.

Checks(by md5 sign) if rasterized text image exists in cache directory. If so, sends it to web browser and quits.

Checks md5 authorization: computes md5 of secret key + parameters. If computed md5-sign equals to provided md5-sign, then request is valid. Otherwise — somebody else is trying to use our "text rasterization service".

Generates text image with imagettftext. Image size exactly matches text size (using imagettfbbox)

Sends generated image to browser

So, it is possible to automatically generate a lot of image text labels for a whole web site. Caching technique will decrease server load: images would be generated only once.



<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

// Checking for gd and Freetype support 
if (!function_exists('gd_info'))
  die('No gd support in PHP.');

$gd = gd_info();
if ($gd["FreeType Support"] == false)
  die('No FreeType support in gd');

// If you're sure about gd & freetype support
// -- comment out this block 



// directory for caching generated images 
// should be writable 
$cache_dir = '/home/path/to/cache'; // DO NOT FORGET TO CHANGE


// testing cache dir 
// remove these lines if you're sure 
// that your cache dir is really writable to PHP scripts
$tf = $cache_dir.'/'.md5(rand()).".test";
$f = @fopen($tf, "w");
if ($f == false)
    die("Fatal error! {$cache_dir} is not writable. Set 'chmod 777 {$cache_dir}' 
           or something like this");
fclose($f);
unlink($tf);
// testing cache dir END 




// full path to preferred TTF font 
// you could change this to be HTTP parameter 
$font = '/home/path/to/font/FuturaBook.ttf'; // DO NOT FORGET TO CHANGE


// md5 secret 
$md5_secret_key = 'changeme'; // DO NOT FORGET TO CHANGE


// md5 sign of parameters
$auth_sign = isset($_GET['a'])?$_GET['a']:'';

// checking for cached file:
$cache_file = $cache_dir.'/'.$auth_sign.'.png';

if (file_exists($cache_file))
{
  // if cached file exists
  // output it and quit
  header("Content-type: image/png");
  readfile($cache_file);
  exit();
}

// no cached file exists 


// input parameters: text and size 
$text = isset($_GET['text'])?$_GET['text']:'default';

$font_size = isset($_GET['size'])?intval($_GET['size']):30;
if ($font_size == 0) $font_size = 30;
// 


// basic sign checking: 
$computed_sign = md5($md5_secret_key.$text.$font_size);
// computing md5 sum of concatenation 
// of secret key and parameters

// hmac-based alrorithm would fit this case more 
// but for real-world purpose md5 of concatenation
// is enought 

if ($computed_sign != $auth_sign)
  die('Auth failed'); // auth error, provided sign is invalid 


// getting bounding box 
$bbox = imagettfbbox($font_size, 0, $font, $text);
// imagettfbbox returns very strange results 
// so transforming them to plain width and height 

$size_w = abs($bbox[2] - $bbox[0]);
// width: right corner X - left corner X

$size_h = abs($bbox[7] - $bbox[1]);
// height: top Y - bottom Y

// This is a lower-left corner 
// but imagettfbbox() sets (0,0) point
// inside bounding box
// so we shifting lower-left corner
$x = -abs($bbox[0]); 
$y = $size_h - abs($bbox[1]);

$im = imagecreatetruecolor($size_w, $size_h);
// creating image

$back = imagecolorallocate($im, 255, 255, 255); // background color
$fore = imagecolorallocate($im, 0, 0, 0); // foreground color

imagefilledrectangle($im, 0, 0, $size_w - 1, $size_h - 1, $back);
// filling with background color

imagettftext($im, $font_size, 0, $x, $y, $fore, $font, $text);
// rendering text

imagepng($im, $cache_file); // outputing PNG image to file cache 

imagedestroy($im); // destroy image 


// sending data from cache file 
header("Content-type: image/png");
readfile($cache_file);


?>


To generate image 'Hello World', 90 pixels size you should call this script as (assuming you've saved it as font.php):


<img src="./font.php?text=Hello+World&size=90&a=4c9a240e98490275d845c96fdb8e5a19">


Note parameter 'a=4c9a240e98490275d845c96fdb8e5a19'. '4c9a240e98490275d845c96fdb8e5a19' is a result of md5('changemeHello World90'): concatenation of secret key, text and font size.

You could use some helper function to set script arguments, like 'image_params':
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$md5_secret_key = 'changeme';

// returns parameters and md5 sign for 
// text generating service
function img_params($text, $size) 
{
  global $md5_secret_key;
  $p = '?text='.urlencode($text).'&size='.$size.'&a=';
  return $p.md5($md5_secret_key.$text.$size);
}

?>

<html><head><title>Test</title></head>
<body>

<center>
<img src="./font.php<?php echo img_params('Hello World', 90);?>">
</center>

</body>
</html>
 

Thursday, April 2, 2015

Htaccess code syntax to prevent your wordpress website from attackers

Htaccess code syntax to prevent your wordpress website from attackers 
Hypertext access (.htaccess) file is the common name of a directory-level configuration file which allows decentralised management of web server configuration. A .htaccess file is always added to the root directory, it can override many other configuration settings which includes server’s global configuration, content type and character set.



 A .htaccess file can be used for lots of hacks that will secure and improve functionality for WordPress blogs and websites. Following are lists of main htaccess code snippets which will improve and prevent WordPress sites from hackers. Some will allow to block specific IP addresses to visit the site, redirect visitors to maintenance page when particular site is redesigned or modified, prevent IP addresses to login into the wordpress admin section etc.


Blacklist undesired users and bots ip address
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/


order allow,deny
allow from all
deny from 132.151.389
deny from 91.131.784
deny from 773.966.769
deny from 178.406.880



?>


Redirect visitors to a maintenance page
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$
RewriteCond %{REMOTE_ADDR} !^123.123.123.123
RewriteRule $ /maintenance.php [R=302,L]


?>


Redirect www to non www or vice versa
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourblogpath.com [NC]
RewriteRule ^(.*)$ http://yourblogpath.com/$1 [L,R=301]
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yourblogpath.com [NC]
RewriteRule ^(.*)$ http://www.yourblogpath.com/$1 [L,R=301]


?>


Force Caching with htaccess
The following htaccess code won’t help the initial pageload, but it will significantly help subsequent pageloads by sending 304 statuses when requested elements haven’t been modified.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

FileETag MTime Size
ExpiresActive on
ExpiresDefault "access plus x seconds"


?>


Allow only your IP adress on the wp-admin directory
Replace your IP with allow from xx.xx.xx.xx which will only allow your IP to access wp-admin directory.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Wordpress Admin Access Control"
AuthType Basic

order deny,allow
deny from all
allow from xx.xx.xx.xx



?>


The easiest way to ban a WordPress spammer
To block certain IP address from accessing your blog enter the following code into .htaccess file and replace example IP address with the one you want to ban.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/


## USER IP BANNING

order allow,deny
deny from 670.45.145.125
allow from all


?>


Deny access to your wp-config.php file
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

# protect wpconfig.php

order allow,deny
deny from all



?>



Limit the File upload size to 10MB
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

# limit file uploads to 10mb
LimitRequestBody 10240000


?>


Password protected directories
A simple way to password protect blog directories
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

AuthType Basic
AuthName "restricted area"
AuthUserFile /usr/local/var/www/html/.htpasses
require valid-user


?>


Quickly secure plugin files
WordPress plugin files might have a loop hole and may allow hackers to get into your website. To prevent others to have direct access to plugin files use following code.
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/


  order allow,deny
  allow from all



?>

Saturday, March 21, 2015

Popular Security Libraries for PHP Developers

Today, PHP is one of the most popular web programming language for creating dynamic websites. There is bunches of data on the web that PHP developers make utilization of. On the other hand, few of them are obsolete and can manage anybody to compose "awful code.

In this post, we have introduced to popular PHP security libraries that will help them to create security interfaces for web applications. If you have any suggestion regarding PHP Security Libraries please write in comment box. Thanks

Popular Security Libraries for PHP Developers


HTML Purifier

HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C’s specifications.

URLcrypt

URLcrypt makes it easy to securely transmit short pieces of binary data in a URL. Use it to securely store things like user IDs, download expiration dates, and more. URLcrypt uses 256-bit AES symmetric encryption to securely encrypt data, and encodes and decodes Base 32 strings that can be used directly in URLs.

PHP Intrusion Detection System

PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application. The IDS neither strips, sanitizes nor filters any malicious input, it simply recognizes when an attacker tries to break your site and reacts in exactly the way you want it to. Based on a set of approved and heavily tested filter rules any attack is given a numerical impact rating which makes it easy to decide what kind of action should follow the hacking attempt. This could range from simple logging to sending out an emergency mail to the development team, displaying a warning message for the attacker or even ending the user’s session.

TCrypto

TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library. By default, a cookie will be used as a storage backend. TCrypto has been designed from the ground up with security in mind. Safe algorithms and modes. Automatic and safe initialization vector creation. Encryption and authentication key creation (Keytool) using strong randomness. Key rotation (versioned keys). TCrypto can be used as a scalable “session handler”. Especially scalable, if cookies are used as a storage backend. This is a bit like Ruby on Rails sessions.

PHP Password Lib

PHP-PasswordLib aims to be an all-inclusive cryptographic library for all cryptographic needs. It is meant to be easy to install and use, yet extensible and powerful enough for even the most experienced developer.

PHPSecLib

phpseclib is designed to be ultra-compatible. It works on PHP4+ (PHP4, assuming the use ofPHP_Compat) and doesn’t require any extensions. For purposes of speed, mcrypt is used if it’s available as is gmp or bcmath (in that order), but they are not required.

Hybrid Auth

HybridAuth is an open source PHP library for authenticating through multiple social services and ID providers. The services supported include OpenID,Facebook, LinkedIn, Google,Twitter, Windows Live, Foursquare, Vimeo, Yahoo, PayPal and more. It can be integrated easily into existing websites by inserting a file and few lines to the sign-in/up pages.

Security Check – Sensiolabs

This tool is almost essential to both beginners and experienced PHP coders. The way it works is quite simple, you upload your .lockfile and it does the rest for you. If you look at the stats, the numbers of vulnerabilities found is quite staggering, don’t be surprised if your own projects might output some nasty stuff that you have missed.

SecurityMultiTool

A multitool library offering access to recommended security related libraries, standardised implementations of security defences, and secure implementations of commonly performed tasks. The purpose of the library is to serve as both a useful set of utilities and to act as a set of reference implementations which can be learned from. It may be used by applications regardless of whether they are web application framework based or not. The use of a web application framework does not guarantee your security.

What is contrast in the middle of MYISAM and InnoDB?


What is contrast in the middle of MYISAM and InnoDB?

In this post, I am explaining to each one of PHP developer to understand the difference between MYISAM and INNODB

MYISAM
1. MYISAM supports Table-level Locking
2. MyISAM designed for need of speed
3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.

INNODB
1. InnoDB supports Row-level Locking
2. InnoDB designed for maximum performance when processing high volume of data
3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
4. InnoDB stores its tables and indexes in a tablespace
5. InnoDB supports transaction. You can commit and rollback with InnoDB
 

© 2014 4everTutorials. All rights resevered.

Back To Top