Saturday, September 1, 2012

How to Prevent SQL injections by adding slashes to Query String (GET / POST Parameters)


<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    $_POST[$key] = addslashes($input_arr);
}
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_GET as $key => $input_arr) {
    $_GET[$key] = addslashes($input_arr);
}
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_REQUEST as $key => $input_arr) {
    $_REQUEST[$key] = addslashes($input_arr);
}

?>

How to do Paging in PHP MYSQL ?



<?php 
///////database connection here
include("../include/database.php");
?>
<?php
$currentPage = $_SERVER["PHP_SELF"];
////////////no. of pages to display $maxRows_profile = 5;////////////////////////edit here
$pageNum_profile = 0;
if (isset($_GET['pageNum_profile'])) {
  $pageNum_profile = $_GET['pageNum_profile'];
}
$startRow_profile = $pageNum_profile * $maxRows_profile;
$colname_profile = "-1";
if (isset($_GET['Id'])) {
  $colname_profile = (get_magic_quotes_gpc()) ? $_GET['Id'] : addslashes($_GET['Id']);
}
/////////////////////your query goes here
$query_profile ="SELECT * FROM student where STUDENT_NAME like '%".$_GET['Id']."%'"; /////////////edit here
$query_limit_profile = sprintf("%s LIMIT %d, %d", $query_profile, $startRow_profile, $maxRows_profile);
$profile = mysql_query($query_limit_profile) or die(mysql_error());
$row_profile = mysql_fetch_assoc($profile);
/////////////////////////////////////////////PAGING LOGIC STARTS HERE ///////////////////////////////
///////////!!!!!!!!!!DO NOT EDIT BELOW THIS!!!!!!!!!!!/////////////
if (isset($_GET['totalRows_profile'])) {
  $totalRows_profile = $_GET['totalRows_profile'];
} else {
  $all_profile = mysql_query($query_profile);
  $totalRows_profile = mysql_num_rows($all_profile);
}
$totalPages_profile = ceil($totalRows_profile/$maxRows_profile)-1;
//////////////////////////////////////////////////////////Paging
$queryString_profile = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_profile") == false && 
        stristr($param, "totalRows_profile") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_profile = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_profile = sprintf("&totalRows_profile=%d%s", $totalRows_profile, $queryString_profile);
///////////////////////////////////////////////////////////////////PAGING END LOGIC////////////////////////////////////
?>
<!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>My Document</title>
</head>

<body>
<!--------------Paging Status starts here-------------->
<p>&nbsp;
Records <?php echo ($startRow_profile + 1) ?> to <?php echo min($startRow_profile + $maxRows_profile, $totalRows_profile) ?> of <?php echo $totalRows_profile ?> </p>

<!--------------Paging Status ends here-------------->
<table border="1">
  <tr>
    <td>Id</td>
    <td>Child_Name</td>
    <td>Gender</td>
  </tr>
  <?php do { ?>
    <tr>
      <td><?php echo $row_profile['MD5']; ?></td>
      <td><?php echo $row_profile['STUDENT_NAME']; ?></td>
      <td><?php echo $row_profile['SURNAME']; ?></td>
    </tr>
    <?php } while ($row_profile = mysql_fetch_assoc($profile)); ?>
</table>
<!--------------Paging Links starts here-------------->
<table border="0" width="42%" >
  <tr>
    <td width="23%" align="center"><?php if ($pageNum_profile > 0) { // Show if first page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, 0, $queryString_profile); ?>">&lt;&lt;First</a>
          <?php } else  { echo '&lt;&lt;First';  }   ?>
    </td>
    <td width="31%" align="center"><?php if ($pageNum_profile > 0) { // Show if not first page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, max(0, $pageNum_profile - 1), $queryString_profile); ?>">&lt;Previous</a>
          <?php }else   { echo '&lt;Previous';  }   ?>
    </td>
    <td width="23%" align="center"><?php if ($pageNum_profile < $totalPages_profile) { // Show if not last page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, min($totalPages_profile, $pageNum_profile + 1), $queryString_profile); ?>">Next&gt;</a>
          <?php }  else  { echo 'Next&gt;';  }       ?>
    </td>
    <td width="23%" align="center"><?php if ($pageNum_profile < $totalPages_profile) { // Show if last page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, $totalPages_profile, $queryString_profile); ?>">Last&gt;&gt;</a>
          <?php } else  { echo 'Last&gt;&gt;';  }   ?>

    </td>
  </tr>
</table>
<!--------------Paging Links ends here-------------->
</body>
</html>
<?php
mysql_free_result($profile);
?>

How to use PHP MYSQL and AJAX together


index.php

Code listing:

<!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>Untitled Document</title>
<script src="ajax.js"></script>
</head>

<body>
<form action="" method="get">
  <p> Enter no </p>
  <p>
    <input name="no" type="text" onkeyup="sq(this.value)" />
  </p>
  <p><div id="res"></div></p>
</form>
</body>
</html>

result.php

Code listing:

<?php
echo $_REQUEST['no']*$_REQUEST['no'];

?>


ajax.php

Code listing:

var xmlhttp

function sq(str)
{
  
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support XMLHTTP!");
  return;
  }
var url="result.php";
url=url+"?no="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("res").innerHTML=xmlhttp.responseText;
}
else
{
  document.getElementById("res").innerHTML="PROCESSING..<img src='images/3.gif' />";
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

How to use PHP MYSQL and AJAX together


index.php

Code listing:

<!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>Untitled Document</title>
<script src="ajax.js"></script>
</head>

<body>
<form action="" method="get">
  <p> Enter no </p>
  <p>
    <input name="no" type="text" onkeyup="sq(this.value)" />
  </p>
  <p><div id="res"></div></p>
</form>
</body>
</html>

result.php

Code listing:

<?php
echo $_REQUEST['no']*$_REQUEST['no'];

?>


ajax.php

Code listing:

var xmlhttp

function sq(str)
{
  
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support XMLHTTP!");
  return;
  }
var url="result.php";
url=url+"?no="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("res").innerHTML=xmlhttp.responseText;
}
else
{
  document.getElementById("res").innerHTML="PROCESSING..<img src='images/3.gif' />";
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

PHP HTML DOM PARSER

Description, Requirement & Features

  • A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way!
  • Require PHP 5+.
  • Supports invalid HTML.
  • Find tags on an HTML page with selectors just like jQuery.
  • Extract contents from HTML in a single line.

How to get HTML Element
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>';

How to modify HTML element
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$html->find('div', 1)->class = 'bar';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

Extract Content from HTML
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;

Scrapping Slashdot
// Create DOM from URL
$html = file_get_html('http://slashdot.org/');

// Find all article blocks
foreach($html->find('div.article') as $article) {
    $item['title']     = $article->find('div.title', 0)->plaintext;
    $item['intro']    = $article->find('div.intro', 0)->plaintext;
    $item['details'] = $article->find('div.details', 0)->plaintext;
    $articles[] = $item;
}

print_r($articles);

Sample uses
// Include the library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html = file_get_html('http://davidwalsh.name/');

// Find all "A" tags and print their HREFs
foreach($html->find('a') as $e)
    echo $e->href . '<br>';

// Retrieve all images and print their SRCs
foreach($html->find('img') as $e)
    echo $e->src . '<br>';

// Find all images, print their text with the "<>" included
foreach($html->find('img') as $e)
    echo $e->outertext . '<br>';

// Find the DIV tag with an id of "myId"
foreach($html->find('div#myId') as $e)
    echo $e->innertext . '<br>';

// Find all SPAN tags that have a class of "myClass"
foreach($html->find('span.myClass') as $e)
    echo $e->outertext . '<br>';

// Find all TD tags with "align=center"
foreach($html->find('td[align=center]') as $e)
    echo $e->innertext . '<br>';
   
// Extract all text from a given cell
echo $html->find('td[align="center"]', 1)->plaintext.'<br><hr>';

AJAX Multiple request / Load Multiple Pages Simlultaneously in Ajax


     In this example we are loading first.php, second.php and third.php asynchronously in the same page simultaneously by making multiple ajax function calls.


index.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax Multiple Calls</title>
<script type="text/javascript" src="content_loader.js"></script>

<script type="text/javascript">
function loader(){
f=GetXmlHttpObject(); 
vloader(f,'first.php','con1');
s=GetXmlHttpObject(); 
vloader(s,'second.php','con2');
t=GetXmlHttpObject(); 
vloader(t,'third.php','con3');
}</script>
</head>

<body onload="loader();">

<h1>First.php</h1>
<div id="con1" ></div>
<h1>Second.php</h1>
<div id="con2" ></div>
<h1>Third.php</h1>
<div id="con3" ></div>

</body>
</html>


Content loader.js
function vloader(xmlhttp,url,container)
{
//alert('hi'+url+container);
if(xmlhttp==null)
{alert ("Your browser does not support XMLHTTP!");return;}  
if(url.indexOf("?")>= 0){}
else{url=url+"?";}
url=url+"&sid="+Math.random();
        xmlhttp.onreadystatechange= function (){
if (xmlhttp.readyState==4)
{ document.getElementById(container).innerHTML=xmlhttp.responseText; } else
{ document.getElementById(container).innerHTML="<img src='loader.gif' />"; } };
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
/////////////////////////////////////////////////////////////////////////////////////////////
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

first.php

<?php
for($i=0;$i<1000000;$i+=0.1);/////just to show  animated loading gif
echo 'First.php..loaded';
?>

second.php

<?php
for($i=0;$i<1000000;$i+=0.1);/////just to show  animated loading gif
echo 'second.php..loaded';
?>

third.php
<?php
for($i=0;$i<1000000;$i+=0.1);/////just to show  animated loading gif
echo 'third.php..loaded';
?>

How to run c and c++ program in gcc on linux platform


Running C Program in gcc on Linux Platform:


Steps:
1. Create a file demo.c with a C code inside it.
      $gedit <filename>
      $gedit demo.c
                  - It will create and open demo.c file in gedit text editor where you can type your c code, save and close it.  e.g.,
#include<stdio.h>
void main()
{
    printf("Hello C");
}
2. Compile demo.c
      $gcc <source file name>
      $gcc demo.c
                 - It will compile C program and create a.out executable binary file.
3. Running demo.c
      $./<executable file name>
      $./a.out
         
Note: If you are dealing with multiple c files at a time, then it is favorable to specify a name executable which can be done as below during compile time.
    $gcc <Source file name> -o <output file name>
    $gcc demo.c -o demoout
    now you can run it as
    $./demoout  


     

Running C++ Program in gcc on Linux Platform:


Steps:

1. Install the 'build-essential' package.
$ sudo apt-get install build-essential                         { For Ubuntu }

2. Create a file demo.cpp with a CPP code inside it.
      $gedit <filename>
      $gedit demo.cpp
                  - It will create and open demo.cpp file in gedit text editor where you can type your cpp code, save and close it.  e.g.,
#include <iostream>
using namespace std;

int main()
{
cout << "Hello  C++";
return 0;
}
3. Compile demo.cpp
      $g++ <source file name> -o <output file name>
      g++ demo.cpp -o hellocpp
                 - It will compile C program and create a.out executable binary file.
4. Running demo.cpp
      $./<executable file name>
     $ ./hellocpp
         

Debugging C Program in GCC on Linux platform:

  • Create C program as below
    • $ gedit demo.c
  • type your code in this demo.c file
  • example:
#include<stdio.h>
void main()
{
   int i=0;
  while(i<10)
  {
      printf("\n %d",i); 
      i++;
  }
}
  • Compile this program with -g option so that compiler can embed debugging information in executable.
  • $gcc -g demo.c -o demo
  • Next to start debugger run below given command.
  • $gdb demo
  • gdb --- debugger gets loaded.
  • Now make us of below commands for various operations.
  • Important gdb commands
    • help [gdb-command]
    • run args
      • Run the program till breakpoint / end
    • break [function-name | line-number]
      • Insert breakpoint at specific line.
      • You can have one or more breakpoints.
    • delete [bp-number]
      • To delete breakpoint.
    • next [N]
      • Debugger will execute the next line as single instruction.
      • next 3,  jumps 3 lines.
    • step [N]
      • Same as next, but does not treats function as a single instruction, instead goes into the function and executes it line by line.
    • finish
      • run till end.
    • continue
      • continue until next breakpoint.
    • where
      • Same as next, but does not treats function as a single instruction, instead goes into the function and executes it line by line.
    • quit
      • quit debugger.