Showing posts with label PHP Optimization. Show all posts
Showing posts with label PHP Optimization. Show all posts

Thursday, March 7, 2013

Fix External Broken links PHP


Adding External links may not guarantee to available all time, following code will check header response before redirect the user to that particular url using the following Code.


<?php

$url = "http://www.w3lessons.com";

$user_agent = 
'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0'

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);


// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_close($ch);


echo "<pre>";
print_r($header);

// Re
HTTP/1.1 200 OK
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 03 Jul 2012 15:28:22 GMT
ETag: "bc241f05-1aace1-4c3ee90929180"
Accept-Ranges: bytes
Content-Length: 1748193
Content-Type: application/pdf
Date: Thu, 07 Mar 2013 11:36:42 GMT
Connection: keep-alive




?>

Checking corresponding Content-Type before redirecting user help to improve user experience.




Thursday, October 11, 2012

Protect email address in web content.


While building web content we may need to include email address. In this case spam bots are may access our web page and collect email address inside our web content. based on this email address extracting script.

The only way to protect Email address inside the content is convert all email address into image.

Here is the solution to convert email address into dynamic text images


email-to-image.php

<?php

define("F_SIZE", 10);
define("F_ANGLE", 0);
define("F_FONT", "verdana.ttf");

$text = base64_decode(base64_decode($_GET['id']));

$Leading=0;
$W=0;
$H=0;
$X=0;
$Y=0;
$_bx = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$s = preg_split("/\n]+/", $text);  // Array of lines
$nL = count($s);  // Number of lines

$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;
$H = ($H==0)?abs($_bx[5]-$_bx[3])+2+($nL>1?($nL*$Leading):0):$H;

$img = @imagecreate($W+8, $H) or die("Cannot Initialize new GD image stream");

$white = imagecolorallocate($img, 255,255,255);
$txtColor = imagecolorallocate($img, 255,50,0);

// Adjust padding right:
$W+=8;
$bgwhite = imagecolorallocatealpha($img,238,238,238,0);
imagefilledrectangle($img, 0, 0,$W,$H, $bgwhite);

$alpha = "".range("a", "z");
$alpha = $alpha.strtoupper($alpha).range(0, 9);

// Use the string to determine the height of a line
$_b = imageTTFBbox(F_SIZE, F_ANGLE, F_FONT, $alpha);
$_H = abs($_b[5]-$_b[3]);
$__H = 0;

// Use the string to determine the width of a line
$_b = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$_W = abs($_b[2]-$_b[0]);

// Final width and height
$_X = abs($W/2)-abs($_W/2);
$__H += $_H;

imagettftext($img, F_SIZE, F_ANGLE, $_X, $__H, $txtColor, F_FONT, $text);

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
// END EMAIL IMAGE  
exit();
?>

index.php

<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
// Keep line breaks inside textarea
$content=preg_replace("/[\n]/", '<br />', $content);
// Find All email ids inside content
preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$content,$emails);

// Replace as image every email address
foreach($emails[0] as $email)
$content=str_replace($email,'<img src="email-to-image.php?id='.base64_encode(base64_encode($email)).'">',$content);
}
?>
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 12px;
 color: #000;
}
body {
 margin-left: 5px;
 margin-top: 5px;
 margin-right: 5px;
 margin-bottom: 5px;
 margin:0 auto;
 width:750px;
}

textarea { width:750px; font-size:15px; font-family:Verdana, Geneva, sans-serif;}

#content
{
 font-size:13px;
 padding:10px;
 background:#EEE;
 border:1px solid #CCC; 
}

#content img
{

 position:relative;
 margin-bottom:-3px;
}

</style>
</head>
<body>

<br>
<br>
<h1>Protect Email Address inside web content</h1>
<form action="" method="post">
<textarea cols="70" rows="10" name="content">
content mixed with any email address. that email address text will be converted into as image. for example we have info@example.com mail in this text area it will be return as image after the compilation. any no of occurrence will automatically replaced as image 

For Example:
Contact
admin@example.com

Technical
tech@example.com
</textarea>
<br /><br />

<input type="submit" value="Compile" name="submit" /><br />
<br />

</form>

<div id="content">
<?php echo @$content; ?>
</div>
</body>
</html>


Download This Script     Live Demo     Download Script

Wednesday, March 28, 2012

Encode PHP files, How to encode php?


PHP Code is our asset of development and concepts. We need to protect / secure our PHP Source code on distribution server. In order to protect PHP source code we need to  encode php files before going to distribute. To encode PHP files to protect PHP source. Here is my solution to protect our PHP Source code with PHP encryption and get Encrypted PHP Source to deploy. In this task we have to use htmlspecialcharsgzdeflatebase64_encodehtml_entity_decodeeval functions



How to encode PHP files and PHP Encoder Online


SourceCode.php   
Put your PHP Source you need to Encode/Protect also include domain based verification code inside this.

<?php
// SAMPLE SOURCE CODE allowed to run only on w3lessons.com
// Start
// PHP Tag in begining and Ending is Must to process encoding...
if(!strstr($_SERVER['HTTP_HOST'],"w3lessons.com"))
die("Unlicenced Domain");
?>
<!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=utf-8" />
<title>How to Encode php files</title>
</head>

<body>
<?php
echo "<h1>Welcome</h1>";
?>
</body>
</html>
<?php
//End
?>

Encoder.php
Run Encoder.php (Output will create a New File EncodeOutput.php

<?php ob_start();

// Put your Source in this file SourceCode.php
$EncodeFileName = "SourceCode.php";
$EncodeCount = intval(rand(5,72)); // Adjust to improve your code security.

// It will cleated automatically after encoding....
copy($EncodeFileName,"EncodeOutput.php");

for($i=0;$i<=$EncodeCount;$i++)
{
 $phpcode = file_get_contents("EncodeOutput.php");
 //remove space
 $phpcode=trim($phpcode);
 //count string
 $count=strlen($phpcode);
 $last=$count-4;
 $rest = substr($phpcode, 2, $last);
 $display= substr($rest, 4);
 $string= htmlspecialchars($display,ENT_NOQUOTES,'UTF-8');
 $phpcode=stripslashes($phpcode);
 $compressed = gzdeflate($string, 5);
 $encode = base64_encode($compressed);

 $phpcode = "&lt;"."&#63;"."php \n";
 $phpcode .= 'eval(html_entity_decode(gzinflate(base64_decode("'.$encode.'")),ENT_NOQUOTES));';
 $phpcode .= "\n".'?'.'>';

 file_put_contents("EncodeOutput.php",html_entity_decode($phpcode,ENT_NOQUOTES));
 usleep(1000);
}

echo "Encoding Completed ! <br /><br />View <a href=\"EncodeOutput.php\">Encoded Output</a>";

?>



EncodeOutput.php
Backup your Original file and replace the encodeoutput.php content instead of Actual PHP Code



<?php 
eval(html_entity_decode(gzinflate(base64_decode("NVa3ruWGEuv9Ga52IQPKCYaLo5xzbhbKOesoff27zWunGJIAOZy/yjMdfjXHOPwpp6M9nj9Fmc9F+at+26ka0qP8laV7SWD/n/9tJC7Kbc4s9N5bxo+CN/mGOaftTN0Z+fpzbbsFoR1BZKXnpcA3ECIXqsbN7KzLI78WZtArsp00kJV7u407OI4AGrhcpoLAk5lH2UjgCdLH4oxANSqBOMvnwL3p7gerUjkv/l0gF28xEiensPA3wLUnqT+c4Svojbx3E8efTEI2JkJfLBdPNSxHn6fsQPGUipQAPCjOaPWsYq1lAYLp/GLW90X+gEuho+lIIRtikPqlpJ7LuvgOa7MbGKHro9mSi3C4OR4xOjX7fDCrvJ7dXcnrDUc5vC3p6j4HPH1YRTAe56IKX00Nj6Aui0f8qFdEO0T5U6gWDDo8+ciDyzYDZeXg0/Iqf4zeg9tJK0VH+t5vJUSCOGf6OvNkHhCgKa4GmbRqZw8WiYc2NGpm+PNgejggMeeX6sussGa7EyeE3PyN584xf1CT+KLwZkBzRvqK6rhF7EQQVL7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NDnkKfmZFt9LCyR2xl8mi6pL/LBYyPrTVTd/GlQ0sHfktCbGdqSPg1msVuH6ZJdUeLWsyGQa7q2wjc9c7qONOtC9h5iph1FsxVXSm16IMKeqvykVcdjjD42GgiC1milnwgMtzhDZmkGwelFSRBgrv/++/v37394w/tjmPbPUt79/fvfv/4H")),ENT_NOQUOTES));
?>


Monday, March 5, 2012

Page Loading Time 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.


Find Page Loading Time PHP
<?php
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 "<br />";
$end = page_loading_time();
// Print results.
echo 'Page Loading Time: <b>' . round($end - $start, 2) . '</b> seconds';   
?>

Sunday, March 4, 2012

Remove HTML comments PHP


Cleaning or Removing HTML comments is one of the main part of Optimizing web pages. Here is the solution to Remove HTML Comments with PHP.

To Remove HTML Comments in PHP, We need to use the following Technique.

Remove HTML Comments with PHP
<?php
// Start OutputBuffer
ob_start();
?>
<!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=utf-8" />
<title>Remove HTML Comments</title>
</head>
<body>

<!-- // HTML Comments for code identification -->

<!-- Mutiple Closing Tags-->
<h1>Remove HTML Comments Example</h1>
<!-- Unclose End Tag-->
<p>This is an example to remove HTML Comments <p>

</body>
</html>
<?php
// Store HTML Output Buffer as variable with ob_get_clean();
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         => false,
     'hide-comments' => true,
           'output-xhtml'   => true,
           'wrap'           => false
     );

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>

Friday, March 2, 2012

PHP Tidy - Clean HTML Tags, HTML code, HTML Source, Comments


Website Webpage Optimization part, HTML pages contain many unnecessary development usage section such as Comments, Indents, Empty Lines, Accidental Enclosed tags without End Tag, Unknown Closing Tag, These are very sensitive for Browser Compatibly Issues, Page Loading Time and Web Page Optimization



We can able to keep our Web pages keep away from Unnecessary things such Comments, Un closed Tags, Un closed End Tags using HTML Tidy Object from PHP.

Here is the Example Code for PHP tidy Object. with Examples.
With this Example We have to use tidy Object (Tidy Object need to Enabled in PHP Configuration).
Check with phpinfo() under Tidy. ob_get_clean() , parse HTML String with parseString() function from Tidy object, and Clean our HTML with cleanRepair()

Sunday, August 14, 2011

Function to Calculate PHP Script Execution Time

PHP Script execution time response is important for quick responsive script, we can able to measure our script execution time with the following script. based on this we can optimize our Script Efficiency








<?php
function process_microtime ()
{
    list ($msec, $sec) = explode(' ', microtime());
    $microtime = (float)$msec + (float)$sec;
    return $microtime;
}

$start=process_microtime ();

// Your PHP Code Block and Process
sleep(1);

echo "<br/>";
$end = process_microtime();
// Print results.
echo 'Script Execution Time: <b>' . round($end - $start, 3) . '</b> seconds';   

?>