Tag Archives: php

PHP Auto Replace Multiple Files Content

Previously my best friend told me about his problems in php. He has a bunch of php file that already outdated.These files use php 4 format. He requested me if there is a way to change the format <? used in those files into <?php that used in current php format. Therefore, I made a php script to do such thing.

This script has feature:

  • List all files in current folder except the script it self
  • Read each file one by one
  • Replace requested string
  • Save it
This is the script:
<?php
//if file is too many, there is a possibility that the script exceed the max exection time
$this_file = 'index.php';//this is the script file for exception
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";

			if($file != $this_file){

				$handle2 = fopen("$file", "rb");
				$contents = '';
				while (!feof($handle2)) {
				  $contents .= fread($handle2, 8192);
				}
				$contents = str_replace("<?", "<?php", $contents);// for replacing <? into <?php
				//for replacing deprecated function, you need regex
				echo htmlspecialchars($contents).'<hr><br>';
				fclose($handle2);

				$fp = fopen("$file", 'w');
				fwrite($fp, $contents);
				fclose($fp);
			}
        }
    }
    closedir($handle);
}
?>

Just copy the script into a folder where resides the files that you want to replace the content.

 http://septiadi.com/2011/06/22/php-auto-replace-multiple-files-content/
Advertisements

Avoid MySql Injection

Avoid MySql Injection

Before we can Avoid MySql Injection, we have to know what is MySql Injection. MySql  Injection is an action performed by system user to make harm to the Database system. User will input MySql statement into an input tag that most of the tag type is text. However there is a browser that can manipulate the html element that will make more easier to connduct MySql Injection. On the other hand, MySql Injection can be conducted by using variable get from url.

Exp you have code:

$search = $_GET['search'];
$query = "Select * from `member` where `username` = '".$search."'";
//if user input just a simply name then it will be ok $search = septiadi
$search ="Select * from `member` where `username` = 'septiadi' "; //this will be ok
//if user input nasty statement $search = ' or '1' = '1
$search ="Select * from `member` where `username` = '' or '1' = '1' "; //this will be bad

If the user input ” ‘ or ‘1’ = ‘1’ ”  the statement will always true. If you use it for authentication process, you will gain access easily. On a very extreme condition, user may give statement  to delete table or drop database. Such as ” ‘; DROP TABLE `member` where  ‘1’ = ‘1″.

To Avoid MySql Injection, we simply add a function for every input from user in our php files. Exp:

$search = mysql_real_escape_string($_GET['search']);//for php 4.3.0 and above
//if magic_quotes_gpc is enabled, first apply stripslashes() to $search
$query = "Select * from `member` where `username` = '".$search."'";

For you that use ajax or jquery, I recomend that you put all of the executing code into one php file. In this case, it will be easier to implement mysql_real_escape_string to Avoid MySql Injection. I’ll give an aditional function that automaticlally implement mysql_real_escape_string to any input.

function clean_query($query){
if(get_magic_quotes_gpc()){
$result = stripslashes($query);
}
else {
$result = $query;
}
$result = mysql_real_escape_string($result);
return $result;
}
/* the above function is to avoid mysql injection */
foreach($_POST as $key => $val){
$_POST[$key] = clean_query($_POST[$key]);// change all $_POST with clean_query function
}

Place the above code into the frist line of your php file. It will replace all $_POST with $_POST that has been implemented by mysql_real_escape_string to Avoid MySql Injection. You can change $_POST into $_GET based on your coding.

MySql Injection is quiet simple but indeed very dangerous. Therefore, Avoid MySql Injection is an absolute needs for web developer that use database.

 

http://septiadi.com/2011/03/31/avoid-mysql-injection/


PHP Calculator Using Eval

PHP Calculator Using Eval

Continuing my previous post Javascript Calculator Using Eval, in this post, I will try to share also to make a simple PHP Calculator Using Eval. Unlike Javascript Calculator Using Eval PHP Calculator Using Eval using php code that reside inside the form. We will use form tag that targeted to the file it self.

The HTML and PHP code:

<form action="" method="post">
<input type="text" name="query" />
<input type="submit" value="calculate" />
<input type="text" disabled value="<?php if(isset($_POST['query'])){eval('echo '.$_POST['query'].';');} ?>"/>
</form>

Make sure to save the file with the extension .php. Otherwise it wont work.

Our PHP Calculator Using Eval here have similar function with Javascript Calculator Using Eval that can calculate a simple calculation such as addition, reduction, multiplication and division. It also can handle parenthesis.

The different of this PHP Calculator Using Eval with Javascript Calculator Using Eval is the  PHP Calculator Using Eval has to reload the page to calculate your inputted query, while the Javascript Calculator Using Eval is not reloading the page.

I wish this PHP Calculator Using Eval is useful for you.

Good Luck

Related Post:

Javascript Calculator Using Eval

http://septiadi.com/2011/03/14/php-calculator-using-eval/


Code Compressor Ver 2

Code Compressor Ver 2

This code is the continuation of my previous Code Compressor. This Code Compressor Ver 2 can delete comments in php, html, javascript and css. However, this Code Compressor Ver 2 avoid to delete text that reside between quotes or double quotes.

Same with my previous Code Compressor Code Compressor Ver 2 also have 2 types of code. First is the html code to handle the form.

HTML code:

<h1>Code Compressor by Muhammad Hasan Septiadi</h1>
<!--This code made by Muhammad Hasan Septiadi-->
<form action="" method="post" align="center">
<textarea name="source" style="width:100%;height:300px;" id="source"></textarea>
<input type="submit" value="Minimize"/>
</form>

Then, the second one is the php code that process the inputted value from html code.

PHP code:

/*This code made by Muhammad Hasan Septiadi*/
if(isset($_POST['source']))
{
	$str = $_POST['source'];
	preg_match_all('/(?<!\\\)"(.*?)(?<!\\\)"|(?<!\\\)"(.*\n.*?)(?<!\\\)"|(?<!\\\)\'(.*?)(?<!\\\)\'|(?<!\\\)\'(.*\n.*?)(?<!\\\)\'/i',   $str, $found);//to capture text between " or '

	foreach($found[0] as $key => $val){$str = str_replace($val, '[mhseptiadi*['.$key.']*mhseptiadi]', $str);}//strip the text between quotes
	$str = preg_replace('@//(.*?)\n@i','',$str);//replace the comment for php and javascript that start with //
	$str = preg_replace('@/\*(.*?)\*/@i','',$str);//replace the comment for php and javascript that start with /* and end with */
	$str = preg_replace('@\<\!--(.*?)--\>@i','',$str);//replace the comment for html that start with <!-- and end with -->
	foreach($found[0] as $key => $val){$str = str_replace( '[mhseptiadi*['.$key.']*mhseptiadi]',$val, $str);}//the text between quotes back

	echo "<fieldset><legend>Result</legend>";
	echo htmlspecialchars(trim($str));
	echo "</fieldset>";
}

You can combine both of code into one file, that should be like:

<h1>Code Compressor by Muhammad Hasan Septiadi</h1>
<!--This code made by Muhammad Hasan Septiadi-->
<form action="" method="post" align="center">
<textarea name="source" style="width:100%;height:300px;" id="source"></textarea>
<input type="submit" value="Minimize"/>
</form>
<?php
/*This code made by Muhammad Hasan Septiadi*/
if(isset($_POST['source']))
{
	$str = $_POST['source'];
	preg_match_all('/(?<!\\\)"(.*?)(?<!\\\)"|(?<!\\\)"(.*\n.*?)(?<!\\\)"|(?<!\\\)\'(.*?)(?<!\\\)\'|(?<!\\\)\'(.*\n.*?)(?<!\\\)\'/i',   $str, $found);//to capture text between " or '

	foreach($found[0] as $key => $val){$str = str_replace($val, '[mhseptiadi*['.$key.']*mhseptiadi]', $str);}//strip the text between quotes
	$str = preg_replace('@//(.*?)\n@i','',$str);//replace the comment for php and javascript that start with //
	$str = preg_replace('@/\*(.*?)\*/@i','',$str);//replace the comment for php and javascript that start with /* and end with */
	$str = preg_replace('@\<\!--(.*?)--\>@i','',$str);//replace the comment for html that start with <!-- and end with -->
	foreach($found[0] as $key => $val){$str = str_replace( '[mhseptiadi*['.$key.']*mhseptiadi]',$val, $str);}//the text between quotes back

	echo "<fieldset><legend>Result</legend>";
	echo htmlspecialchars(trim($str));
	echo "</fieldset>";
}
?>

If we use the Code Compressor Ver 2 for our code, it should be:

<h1>Code Compressor by Muhammad Hasan Septiadi</h1> <form action="" method="post" align="center"> <textarea name="source" style="width:100%;height:300px;" id="source"></textarea> <input type="submit" value="Minimize"/> </form> <?php if(isset($_POST['source'])) { $str = $_POST['source']; preg_match_all('/(?<!\\\)"(.*?)(?<!\\\)"|(?<!\\\)"(.*\n.*?)(?<!\\\)"|(?<!\\\)\'(.*?)(?<!\\\)\'|(?<!\\\)\'(.*\n.*?)(?<!\\\)\'/i', $str, $found);	 foreach($found[0] as $key => $val){$str = str_replace($val, '[mhseptiadi*['.$key.']*mhseptiadi]', $str);}	$str = preg_replace('@//(.*?)\n@i','',$str);	$str = preg_replace('@/\*(.*?)\*/@i','',$str);	$str = preg_replace('@\<\!--(.*?)--\>@i','',$str);	foreach($found[0] as $key => $val){$str = str_replace( '[mhseptiadi*['.$key.']*mhseptiadi]',$val, $str);} echo "<fieldset><legend>Result</legend>"; echo htmlspecialchars(trim($str)); echo "</fieldset>"; } ?>

Little explanation:

preg_match_all('/(?&lt;!\\\)"(.*?)(?&lt;!\\\)"|(?&lt;!\\\)"(.*\n.*?)(?&lt;!\\\)"|(?&lt;!\\\)\'(.*?)(?&lt;!\\\)\'|(?&lt;!\\\)\'(.*\n.*?)(?&lt;!\\\)\'/i',   $str, $found);

The above code is used to capture all text between either sigle quotes (‘) or double quotes (“). However it will consider \’ and \” as the text. The code will also capture text that have newline character if it is reside between either sigle quotes (‘) or double quotes (“).

foreach($found[0] as $key => $val){$str = str_replace($val, '[mhseptiadi*['.$key.']*mhseptiadi]', $str);}

The above code will replace the text between quotes with something like [mhseptiadi*[‘.$key.’]*mhseptiadi].

$str = preg_replace('@//(.*?)\n@i','',$str);
$str = preg_replace('@/\*(.*?)\*/@i','',$str);
$str = preg_replace('@\<\!--(.*?)--\>@i','',$str);

The above code is the code for removing the comment in php, javascript, html and css. You can add your own script to remove comment in other programming language.

foreach($found[0] as $key => $val){$str = str_replace( '[mhseptiadi*['.$key.']*mhseptiadi]',$val, $str);}

The above code will replace [mhseptiadi*[‘.$key.’]*mhseptiadi] with the text between quotes.

If you found any bug in my code, fell free to tell me.

Good luck.

Related Posts:

Code Compressor

http://septiadi.com/2011/03/08/code-compressor-ver-2/

 


Five Methods for PHP Looping

Five Methods for PHP Looping

Looping is one of the most common process used by web developer while building a site. In this article, I will try to share Five Methods for PHP Looping processes.

Frist, You can use “while”:
while(condition){do something}
Exp in php:

$cond = 1;
while($cond &gt;= 10){echo $cond;$cond++;}

The above code will print “12345678910”.

Second, You can use “for”:
for(condition){do something}
Exp in php:

for($i=0;$i<=10;$i++){echo $i;}

The above code will print “12345678910”.

Third, you can use “do-while”:
do{do something}while(condition);
Different with while, do-while will execute the command first, then check the condition. Even if the condition is not match, the do-while will execute the command once.
Exp in php:

$i = 1;
do {echo $i;$i++;} while ($i <= 10);

The above code will print “12345678910”.
Exp in php:

$i = 1;
do {echo $i;} while ($i = 10);

The above code will print “1”.

Fourth, you can use “foreach”:
foreach(array as $keys => $vasl){do something}
Foreach is used to print out an array.
Exp in php:

$arrs = array("septiadi","hasan","muhammad");
foreach ($arrs as $keys => $vals) {
    echo $keys."=>".$vals." ";
}

The above code will print “0=>septiadi 1=>hasan 2=>muhammad”.

Fifth, you can use “goto”:
location:…. goto location; or goto location;…. location:
Exp in php:

$i=1;
loc:
echo $i;
goto loc;

The above code will print “1” continously.
Exp in php:

$i=1;
loc:
echo $i;$i++;
if($i>10)goto loc2;
goto loc;
loc2:

The above code will print “12345678910”.

Currently there are only Five Methods for PHP Looping processes that I know. There is posibility to do different way than the Five Methods for PHP Looping. May be you are the one that find the sixth method :D.

Good luck.

http://septiadi.com/2011/03/03/five-methods-for-php-looping/


Conversion from 12 Hour to 24 Hour

Conversion from 12 Hour to 24 Hour

Many people using either 12 hour time format or 24 hour time format. It also easy for us to convert it into time format that we familiar with. We also can use both. However, database time format can only accept 24 hour time format. Therefore Conversion from 12 Hour to 24 Hour is a must.

For people that does not familiar with Conversion from 12 Hour to 24 Hour, I’ll give an example.

12 hour time format 24 hour time format
00:00 am 00:00
01:00 am 01:00
11:00 am 11:00
12:00 pm 12:00
01:00 pm 13:00
11:00 pm 23:00
00:00 am 00:00

The php code that will handle this Conversion from 12 Hour to 24 Hour is below.

$ampm = "" //fill it either with am or pm
$hour = "" //fill it with hour
$min = "" //fill it with minute

if($ampm == 'PM' && $hour != 12)
{$hour = $hour + 12;}
echo "$hour:$min";

Congratulation we just made a simple Conversion from 12 Hour to 24 Hour programs.

Good luck.

http://septiadi.com/2011/03/01/conversion-from-12-hour-to-24-hour/


Mysql Backup with PHP

Mysql Backup with PHP

Database is one of the most important thing in building a website. Therefore, making database backup is also very important. Database backup will avoid loss if there is a crash in our database.

In this article I will try to share a method that i use to make Mysql Backup with PHP. The frist thing that we need to do is making the code it self.

The php code:

$current = date("Y-m-d_H-i-s");
$host = "";//fill it with host name
$user = "";//fill it with user name
$pass = "";//fill it with password
$database = "";//fill it with database name
exec("mysqldump --opt --host=$host --user=$user --password=$pass $database | gzip --best > $database_$current.sql.gz");

That is it, the code will automatically make a backup with extention .sql.gz and save it with the same directory with your code.

You can combine this code with Attachment Email with PHP

Cogratulation you just learn how to make Mysql Backup with PHP.

Good luck.

http://septiadi.com/2011/02/28/mysql-backup-with-php/