Posts filed under 'PHP'

PHP Cookies: How to Set Cookies & Get Cookies

Cookies don’t have to be an essential part of a website but can provide some of the “little things” that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client’s computer so that you can access them next time they visit the website. Session ID’s are also usually held in cookies.

So what are the most popular uses of cookies? They are:

  • To store username/password information so that the user doesn’t have to log in every time they visit the website (”remember me” sign ins).
  • To simply remember the user’s name.
  • To keep track of a user’s progress during a specified process.
  • To remember a user’s theme.

(more…)

Add comment April 15, 2009

XPath

XPath uses path expressions to select nodes or node-sets in an XML document.
The node is selected by following a path or steps.
(more…)

Add comment December 28, 2007

AJAX/Javascript XML Processing Example/Tutorial

xml.html:

<script type="text/javascript" language="javascript">

   var http_request = false;

   function makeRequest(url, parameters) {

      http_request = false;

      if (window.XMLHttpRequest) { // Mozilla, Safari,...

         http_request = new XMLHttpRequest();

         if (http_request.overrideMimeType) {

            http_request.overrideMimeType('text/xml');

         }

      } else if (window.ActiveXObject) { // IE

         try {

            http_request = new ActiveXObject("Msxml2.XMLHTTP");

         } catch (e) {

            try {

               http_request = new ActiveXObject("Microsoft.XMLHTTP");

            } catch (e) {}

         }

      }

      if (!http_request) {

         alert('Cannot create XMLHTTP instance');

         return false;

      }

      http_request.onreadystatechange = alertContents;

      http_request.open('GET', url + parameters, true);

      http_request.send(null);

   }   function alertContents() {

      if (http_request.readyState == 4) {

         if (http_request.status == 200) {

var xmldoc = http_request.responseXML;

            var root = xmldoc.getElementsByTagName('root').item(0);

for (var iNode = 0; iNode < root.childNodes.length; iNode++) {

               var node = root.childNodes.item(iNode);

               for (i = 0; i < node.childNodes.length; i++) {

                  var sibl = node.childNodes.item(i);

                  var len = parseInt(sibl.childNodes.length / 2);

                  var arr = new Array(len);

                  var cnt = 0;

                  for (x = 0; x < sibl.childNodes.length; x++) {

                     var sibl2 = sibl.childNodes.item(x);

                     var sibl3;

                     if (sibl2.childNodes.length > 0) {

                        sibl3 = sibl2.childNodes.item(0);

                        arr[cnt] = sibl3.data;

                        cnt++;

                     }

                  }

                  addrow("mytable", arr);

               }

            }

         } else {

            alert('There was a problem with the request.');

         }

      }

   }

   function do_xml() {

      makeRequest('xml.php', '?test=2');

   }

   function addrow(tablename, arr) {

   var tbl = document.getElementById(tablename);

   var lastRow = tbl.rows.length;

   var row = tbl.insertRow(lastRow);

      for (r = 0; r < arr.length; r++) {

         var cell = row.insertCell(r);

         cell.innerHTML = arr[r];

      }

   }

</script>

<input type="button" name="button" value="GET XML"

   onclick="javascript:do_xml();">

<br><br>

Table filled with data requested from the server:<br>

<table border="1" id="mytable">

</table>

xml.php
<?echo "<?xml version=\"1.0\" ?>";?>

<root>

 <data>

 	<row>

 		<cell>Name</cell>			<cell>Fruit</cell>

 		<cell>Vegetable</cell>

 	</row>

 	<row>

 		<cell>Captain</cell>

<cell>Banana</cell>

 		<cell>Zucchini</cell>

 	</row>

 	<row>

 		<cell>Admiral</cell>

<cell>Melon</cell>

 		<cell>Carrot</cell>

 	</row>

 	<row>

 		<cell>Midshipman</cell>

<cell>Orange</cell>

 		<cell>Potatoe</cell>

 	</row>

 </data>

</root>

Add comment December 28, 2007

file access

<?php

function permission($filename)
{
$perms = fileperms($filename);

if     (($perms & 0xC000) == 0xC000) { $info = ’s’; }
elseif (($perms & 0xA000) == 0xA000) { $info = ‘l’; }
elseif (($perms & 0×8000) == 0×8000) { $info = ‘-’; }
elseif (($perms & 0×6000) == 0×6000) { $info = ‘b’; }
elseif (($perms & 0×4000) == 0×4000) { $info = ‘d’; }
elseif (($perms & 0×2000) == 0×2000) { $info = ‘c’; }
elseif (($perms & 0×1000) == 0×1000) { $info = ‘p’; }
else                                 { $info = ‘u’; }

// владелец
$info .= (($perms & 0×0100) ? ‘r’ : ‘-’);
$info .= (($perms & 0×0080) ? ‘w’ : ‘-’);
$info .= (($perms & 0×0040) ? (($perms & 0×0800) ? ’s’ : ‘x’ ) : (($perms & 0×0800) ? ‘S’ : ‘-’));

// группа
$info .= (($perms & 0×0020) ? ‘r’ : ‘-’);
$info .= (($perms & 0×0010) ? ‘w’ : ‘-’);
$info .= (($perms & 0×0008) ? (($perms & 0×0400) ? ’s’ : ‘x’ ) : (($perms & 0×0400) ? ‘S’ : ‘-’));

// все
$info .= (($perms & 0×0004) ? ‘r’ : ‘-’);
$info .= (($perms & 0×0002) ? ‘w’ : ‘-’);
$info .= (($perms & 0×0001) ? (($perms & 0×0200) ? ‘t’ : ‘x’ ) : (($perms & 0×0200) ? ‘T’ : ‘-’));

return $info;
}

function dir_list($dir)
{
if ($dir[strlen($dir)-1] != ‘/’) $dir .= ‘/’;

if (!is_dir($dir)) return array();

$dir_handle  = opendir($dir);
$dir_objects = array();
while ($object = readdir($dir_handle))
if (!in_array($object, array(‘.’,’..’)))
{
$filename    = $dir . $object;
$file_object = array(
‘name’ => $object,
’size’ => filesize($filename),
‘perm’ => permission($filename),
‘type’ => filetype($filename),
‘time’ => date(“d F Y H:i:s”, filemtime($filename))
);
$dir_objects[] = $file_object;
}

return $dir_objects;
}

print_r(dir_list(‘../’));

?>

Add comment December 19, 2007

CAPTCHA

Instructions:
Create the following SQL table:
CREATE TABLE captcha (
confirm_id char(32) DEFAULT ” NOT NULL,
session_id char(32) DEFAULT ” NOT NULL,
code char(8) DEFAULT ” NOT NULL,
PRIMARY KEY (session_id,confirm_id)
);

Modify the settings in the script.

This script uses TTF fonts to display the code. You can upload your own fonts to use. Just be sure to change $font_dir to wherever your fonts are stored. (A default font without rotation is used if none are available.)

Snippet

  1. <?php

  2. //

  3. // Settings

  4. //

  5. $dbhost = ‘localhost’;

  6. $dbuser = ‘username’;

  7. $dbpass = ‘password’;

  8. $database = ‘database’;

  9. $min_char = 4;

  10. $max_char = 8;

  11. $font_dir = ‘./*.ttf’;

  12. //

  13. // Initial start

  14. //

  15. mysql_connect($dbhost, $dbuser, $dbpass);

  16. mysql_select_db($database);

  17. session_start();

  18. //

  19. // Initiate image

  20. //

  21. header(“content-type: image/png”);

  22. header(“Cache-control: no-cache, no-store”);

  23. $width = rand(200, 300);

  24. $height = rand(50, 70);

  25. $img = imagecreate($width, $height);

  26. $background = imagecolorallocate($img, rand(200, 255), rand(200, 255), rand(200, 255));

  27. //

  28. // Compile code

  29. //

  30. $array = array();

  31. for ($i = 0; $i < $max_char; $i++)

  32. {

  33.   $alpha = chr(rand(1, 26) + 64);

  34.   $numeric = rand(0, 9);

  35.   $array[] = (rand(0, 1) == 0 || count($array) < $min_char) ? ((rand(0, 1) == 0) ? $alpha : $numeric) : ;

  36. }

  37. $code = str_replace(‘0′, ‘Z’, implode(, $array));

  38. //

  39. // Query database

  40. //

  41. $confirm_id = (eregi(‘^[a-z0-9]{32}$’, $_GET['id'])) ? $_GET['id'] : md5(uniqid($_SERVER['REMOTE_ADDR']));

  42. $session_id = (eregi(“^[a-z0-9]{32}$”, session_id())) ? session_id() : ;

  43. mysql_query(“DELETE FROM captcha WHERE session_id = ‘$session_id’”);

  44. mysql_query(“INSERT INTO captcha (confirm_id, session_id, code) VALUES (‘$confirm_id’, ‘$session_id’, ‘$code’)”);

  45. //

  46. // Create background

  47. //

  48. for ($i = 0; $i < rand(5, 20); $i++)

  49. {

  50.   $color = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));

  51.   $loc_x = rand(-100, $width + 100);

  52.   $loc_y = rand(-50, $height + 50);

  53.   $end_x = rand(-100, $width + 100);

  54.   $end_y = rand(-50, $height + 50);

  55.   // Background shapes

  56.   $shape = rand(1, 3);

  57.   switch ($shape)

  58.   {

  59.     case 1:

  60.       // Draw an ellipse

  61.       imageellipse($img, $loc_x, $loc_y, rand(100, 400), rand(50, 400), $color);

  62.     break;

  63.     case 2:

  64.       // Draw a rectangle

  65.       imagerectangle($img, $loc_x, $loc_y, $end_x, $end_y, $color);

  66.     break;

  67.     case 3:

  68.       // Draw a line

  69.       imageline($img, $loc_x, $loc_y, $end_x, $end_y, $color);

  70.     break;

  71.   }

  72. }

  73. //

  74. // Compile image

  75. //

  76. $x_move = $width / (strlen($code) + 1);

  77. $current_pos = rand(0, $x_move / 2);

  78. $less_rotate = array(‘N’, ‘Z’, ‘6′, ‘9′);

  79. for ($i = 0; $i < strlen($code); $i++)

  80. {

  81.   $size = rand(15, 20);

  82.   $angle = (in_array($code[$i], $less_rotate)) ? rand(-15, 15) : rand(-30, 30);

  83.   $x_pos = $current_pos + rand($size + 1, $x_move);

  84.   $y_pos = $height/2 + rand(-8, 8);

  85.   $current_pos = $x_pos;

  86.   $fonts = glob($font_dir);

  87.   $font = $fonts[array_rand($fonts)];

  88.   $color = imagecolorallocate($img, rand(0, 127), rand(0, 127), rand(0, 127));

  89.   if (!empty($font))

  90.     imagettftext($img, $size, $angle, $x_pos, $y_pos, $color, $font, $code[$i]);

  91.   else

  92.     imagestring($img, 5, $x_pos, $y_pos, $code[$i], $color);

  93. }

  94. //

  95. // Create image

  96. //

  97. imagepng($img);

  98. imagedestroy($img);

  99. /* —— MySQL Query ——

  100. CREATE TABLE captcha (

  101. confirm_id char(32) DEFAULT ” NOT NULL,

  102. session_id char(32) DEFAULT ” NOT NULL,

  103. code char(8) DEFAULT ” NOT NULL,

  104. PRIMARY KEY  (session_id,confirm_id)

  105. );

  106. */

  107. ?>

  108. ### TEST PAGE ###

  109. <?php

  110. mysql_connect(‘localhost’, ‘username’, ‘password’);

  111. mysql_select_db(‘database’);

  112. session_start();

  113. if (isset($_POST['submit']))

  114. {

  115.   $confirm_id = (eregi(‘^[a-z0-9]{32}$’, $_POST['confirm_id'])) ? $_POST['confirm_id'] : ;

  116.   $result = mysql_query(“SELECT * FROM captcha WHERE confirm_id = ‘$confirm_id’ LIMIT 1″);

  117.   $row = mysql_fetch_assoc($result);

  118.   if (!$row || $_POST['confirm'] !== $row['code'])

  119.   {

  120.     echo ‘<b>Invalid Code:</b>’;

  121.   }

  122.   else

  123.   {

  124.     $session_id = (eregi(“^[a-z0-9]{32}$”, session_id())) ? session_id() : ;

  125.     mysql_query(“DELETE FROM captcha WHERE session_id = ‘$session_id’”);

  126.     session_destroy();

  127.     echo ‘<b>Valid:</b>’;

  128.   }

  129.   echo $_POST['confirm'] . ‘|’ . $row['code'] . ‘<br />’;

  130. }

  131. $confirm_id = md5(uniqid($_SERVER['REMOTE_ADDR']));

  132. ?>

  133. <img src=“captcha.php?id=<?php echo $confirm_id; ?>”>

  134. <form method=“post”>

  135. <input type=“hidden” name=“confirm_id” value=“<?php echo $confirm_id; ?>”>

  136. <input type=“text” name=“confirm” size=“30″>

  137. <input type=“submit” name=“submit” value=“Submit”>

  138. </form>

Add comment November 24, 2007


Categories

Category Cloud

.Net Business HTML & CSS & DOM Javascript PHP Tool

Tags

.Net ADO.NET ajax Business Javascript Oracle ADO.NET Subversion .Net Subversion SVN Source VB.Net

Recent Posts

Archives

Blogroll

Recent Comments

Asaduzzaman Arif on Encrypt/Decrypt string VB…
Pranav on Encrypt/Decrypt string VB…
ntcnet on Encrypt/Decrypt string VB…
Elena on Encrypt/Decrypt string VB…
Elena on Encrypt/Decrypt string VB…

Twitter