Pages

Your Ad Here

This Blog is not to read or go through

because, I have never been such a mess


Search the blog instead

Showing posts with label Dynamic programming. Show all posts
Showing posts with label Dynamic programming. Show all posts

Tuesday, May 17, 2011

base_url() function for php



function base_url(){
    $pathinfo = pathinfo($_SERVER["SCRIPT_NAME"]);
    $dirname = $pathinfo["dirname"];
    if($_SERVER["HTTPS"] == "on"){
    $protocol = "https";
    }else{
        $protocol = "http";
    }
    $base_url = $protocol."://".$_SERVER["HTTP_HOST"].$dirname."/";
    return $base_url;
}

Wednesday, July 14, 2010

PHP Jabber Web Chat

Searched a LOT And LOT and finally found one.


PHP/Ajax based Jabber Web Chat Client.


http://blog.jwchat.org/jwchat/

Friday, April 16, 2010

Automatic Base URL in PHP

# Generate the BASE_URL

$request = $_SERVER["REQUEST_URI"];
$script_path = $_SERVER["SCRIPT_NAME"];
$base_url_len = strlen($script_path) - strlen("index.php");
$arg = explode("/", substr($request, $base_url_len));
$base_url = "http://". $_SERVER["HTTP_HOST"] . substr($script_path, 0, $base_url_len);
define("BASE_URL", $base_url);

author -- acpmasquerade

Thursday, March 18, 2010

PHP array_splice vs. array_slice

Slice
array array_slice ( array $array , int $offset [,int $length [, bool $preserve_keys = false ]] )

Extract a slice of the array

Example :

$input= array("a", "b", "c", "d", "e");

$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));





Splice
array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )
Remove a portion of the array and replace it with something else

Example :

= array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
// "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
// "blue", "purple", "yellow");



Thanks - PHP.net

Pseudo Selectors CSS and JQuery

Pseudo Selectors Primarily for CSS and some for jquery too.
http://css-tricks.com/pseudo-class-selectors/

Saturday, January 9, 2010

17 javascript animation frameworks

http://www.admixweb.com/2010/01/07/17-javascript-animation-frameworks-worth-to-seing/

Monday, October 5, 2009

compress images gracefully without degrading quality

image compression service without degrading the original image quality.

http://www.gracepointafterfive.com/punypng
http://www.punypng.com

Wednesday, August 19, 2009

codeigniter tweak for find_in_set

It was really really frustrating when i could not find any good function in the Codeigniter Active Record Class for FIND_IN_SET type queries.

So, i just buit this.


$set = implode(',',$where);
$this->db->where('1 <=', "FIND_IN_SET(`".$field."`,".$this->db->escape($set).")",false);

Where $where is an array of values

And Yest , it works with a miracle now.

Sunday, August 16, 2009

not in the database

select src from (
select "node/1" as src
union select "node/2" as src
union select "node/3" as src
) temp where src not in (select src from drupal_url_alias)

Tuesday, June 9, 2009

Email validation in php

eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)

Thursday, April 30, 2009

select maximum value from an auto increment field

$table_name = "jos_menu";
$resultset = mysql_query("desc $table_name");
while($a = mysql_fetch_assoc($resultset))
{
if($a["Extra"] == "auto_increment"){
$query = "SELECT max(".$a["Field"].") as auto from $table_name";
$resultset1 = mysql_query($query);
$answer = mysql_fetch_assoc($resultset1);
die($answer["auto"]);
break;
}
}

Note: It can be done just by subtracting 1 from the current Auto_increment value in a table. But, I never found this justifiable because what if the last row is deleted.

Friday, November 7, 2008

Pass Sessions between subdomains in php

If needed to be able to pass session data between subdomains, add the following to the php.ini file.
session.cookie_domain = .mydomain.com

If unable to modify the the php.ini file, add the following before the session.start() function on any page which creates the session cookie.

ini_set("session.cookie_domain", ".mydomain.com")

Sunday, June 29, 2008

Position:fixed solved in IE

top:0px;
left:0px;
position:fixed;
background-color:#f0f0f0;
_position:absolute;
_top:expression(eval(document.body.scrollTop));

Friday, May 9, 2008

Unicode Problem in PHP and database used with it

Unicode Data with PHP 5 and MySQL 4.1




By Andrew Penry


Posted on 11.12.04




Unicode background



In the ever expanding world of e-commerce and information technology, one thing above all is coming to the forefront of internet design - globalization. For many large companies, web documents are translated into many different languages. However, the computer technologies we use for storing data weren't originally designed to deal with information in multiple languages. A web page could show only one set of characters, be it Latin, Cyrillic, Greek, Japanese, or any other character set. Luckily, there is now a standard that is implemented in most browsers called Unicode. This standard encodes characters differently than older technologies, allowing almost all the characters in all human printed languages to be displayed in one page.



Let's clarify the difference between some commonly used terms. A character is a textual unit, such as a letter, number, symbol, punctuation mark, etc. A character set is a set of characters you would like to use. For instance, English uses a Latin character set, while Russian uses a Cyrillic character set. Unicode is a character set that includes characters needed for almost all current written human languages.



When we request text data from the web the data must be encoded. As you know, all data is stored as numbers in computers, and this is what the encoding is. Think of the old decoder rings you would get in cereal boxes. "1" would stand for "A", "2" for "B", etc. The character encoding is the same thing, just on a much larger scale. In computers it matches up integers to characters. The Unicode standard provides several different character encodings, which may be appropriate for different technologies. The one that is leading the way in web development is called UTF-8. UTF-8 contains a numerical representation for over 100,000 characters (all the characters in the Unicode character set).



A glyph is a pictorial representation of a character. For instance the typeset "g" and the handwritten "g" are both glyphs. They look different, but they both mean "letter g." UTF-8 encodes characters, not glyphs. There is only one code for the "letter g." A font is a collection of glyphs. It takes the characters and maps them to glyphs. You must have a font capable of producing the correct glyphs to correctly view Unicode text. Most fonts only have glyphs for subsets of the entire Unicode character set, for instance Latin and Greek. If you have Cyrillic characters in a document and you attempt to render them with such a font, the Cyrillic characters may be rendered as open rectangle, question marks, or not at all. This does not mean that the data is not there, it just means that the font you have selected does not include the glyphs needed to display the data. Very few fonts have glyphs for all the characters in Unicode, primarily because creating more than 100,000 passes the point of diminishing returns for commercial fonts. Code2000 is a $5 shareware font that is the most comprehensive with over 61,000 glyphs. Other fonts can be found at Alan Wood's Unicode site.

How Unicode fits in your Dynamic Web Site



PHP 5 supports UTF-8 natively (without special compilation options) as does MySQL 4.1. However some care needs to be taken to ensure your data is stored and displayed correctly. This article is about storing and retrieving Unicode data in a MySQL 4.1 database using PHP 5. It is not about support for using Unicode characters in variable names and other PHP code, or in the names of tables and columns in MySQL. As Unicode support is still young, I would recommend avoiding such things at this time.

Preparing MySQL for Unicode



Although MySQL has support for UTF-8, it doesn't use it as its default character encoding. If you have control over your server, you can configure it at compilation or through its configuration files to use UTF-8 as default. But since most people don't have complete control, we'll focus on things you can do at the table level.



Let's create a table to hold our data. What is most important here is the "CHARACTER SET utf8" portion. This tells MySQL that all the text in this table will be encoded in UTF-8.

CREATE TABLE document (

id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,

unicodeText VARCHAR(45) NOT NULL

)

CHARACTER SET utf8 COLLATE utf8_general_ci;

Note that MySQL uses a non-standard name "utf8" to mean UTF-8. The COLLATE command is used to tell how to sort the data when using the SORT BY command. Also note that you should always use VARCHAR instead of CHAR with UTF-8. (UTF-8 uses variable sized numbers for different characters. For instance, Latin letters use 1 byte codes, while Japanesee characters are 3 bytes. Using CHAR(10) would force the database to reserve 30 bytes, because it doesn't know ahead of time which length with be used, so it reserves the maximum.)



Telling MySQL how to store the data is just half of the equation. You must also tell MySQL that the data you are passing into it is UTF-8 otherwise it will assume it is in its default encoding. (If you've been doing a lot of searching on Google, and haven't been able to get things to work, this is probably the information that you haven't found.) The command for this is:

SET NAMES 'utf8';

Using PHP and XHTML to encode



Here's our code snippet. You'll want to modify this so that it's valid XHTML before you use it in production:

 1 <?php 

2 $DB = new mysqli('localhost', 'user', 'root', 'dbname');

3 $DB->query("SET NAMES 'utf8'");

4 if (!empty($_POST['ta'])) {

5 $DB->query("UPDATE document SET unicodeText='{$_POST['ta']}' WHERE ID=1");

6 }

7 $result = $DB->query("SELECT unicodeText FROM document WHERE ID=1");

8 $return = $result->fetch_object();

9 $result->close();

10 ?>

11 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

12 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

13 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

14 <head>

15 <title>Test</title>

16 </head>

17 <body>

18 <p>Posted: <?php echo $_POST['ta'];?></p>

19 <form enctype="multipart/form-data" method="post" action="test2.php">

20 <fieldset>

21 <textarea name="ta"><?php echo $return->unicodeText;?></textarea>

22 <input type="submit" />

23 </fieldset>

24 </form>

25 </body>

26 </html>

Because we are using MySQL 4.1 with PHP 5 it makes sense to use the MySQLi extension. I like using the OO version of the extension. Line 2 is the connection to the database. Line 3 tells the database to expect UTF-8 data. Lines 4-6 update a row in the database with the Unicode data we send through the form. (Make sure to have some sample data in row 1 of the database when you test this code) Lines 7-8 pull the data back out of the database. Lines 11-12 are important. XHTML defaults to using UTF-8 encoding, unless you specifically tell it otherwise. Using the correct Doctype declaration will alert your browser to use UTF-8 encoding. You will see a lot of things if you search on Google about how you need to put tags about UTF-8 in all sorts of places, like the form, or the form controls, or in META tags. If you are serving valid XHTML this is not necessary. The rest of the code is the form. Lines 18 and 21 will let you compare the raw POST data with what the database returns.



By taking a little care with setting up the database, and using valid XHTML, one can properly store and serve UTF-8 code. Here's a link to a page that will allow you to copy some Unicode that you can paste into your form for testing.

Saturday, December 22, 2007

PHP: Dynamic Image Generation

PHP: Dynamic Image Generation Print Email

Creating images on the fly can be a very useful skill. PHP has some built-in image generation functions, further more, to generate new images or edit existing images on the fly using PHP, we need to have the GD library installed. In this tutorial we will show you how to get quite interesting and useful effects using image handling functions. We will review two practical tasks: creating security images (captcha) on the fly and building a bar chart using numerical values retrieved from MySQL database.

Creating security images on the fly

At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

//Send a generated image to the browser
create_image();
exit();

function create_image()
{
//Let's generate a totally random string using md5
$md5 = md5(rand(0,999));
//We don't need a 32 character long string so we trim it down to 5
$pass = substr($md5, 10, 5);

//Set the image width and height
$width = 100;
$height = 20;

//Create the image resource

$image = ImageCreate($width, $height);

//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);

//Make the background black
ImageFill($image, 0, 0, $black);

//Add randomly generated string in white to the image
ImageString($image, 3, 30, 3, $pass, $white);

//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image,0,0,$width-1,$height-1,$grey);
imageline($image, 0, $height/2, $width, $height/2, $grey);
imageline($image, $width/2, 0, $width/2, $height, $grey);

//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

//Output the newly created image in jpeg format
ImageJpeg($image);

//Free up resources
ImageDestroy($image);
}
?>

To create a new image or edit an existing one, we need to create image identifier. In the preceding example we created an empty canvas by calling ImageCreate() function, passing it width and height of a new image as a parameters. Another way to do it is to read the existing image from the file. Depending on the file format you can do it using one of the following functions: ImageCreateFromPNG(), ImageCreateFromGIF(), ImageCreateFromJPEG(). Parameter of each function is a file name.

Then, we need to choose colors to be used while painting. For this we can use ImageColorAllocate() function and image identifiers for red, green, and blue (RGB) components of necessary color will be passed as parameters.

On the next step, we will generate our image. First, using ImageFill() function we will create black background. Parameters of this function are: image identifier, initial coordinates of the area to be filled and fill color. Then, we will use ImageString() function to add text to the image. Its parameters are – image identifier, font, coordinates for the first text position and text color. Finally, we will draw two lines and a rectangular to protect our image a little bit. Please note, that the final point of the rectangular has the following coordinates: $width-1 and $height-1. If they were equal to $width and $height, than the rectangular would have exceeded canvas frame.

When we had created the image, we can output it either to a browser, or to a file. Our example shows how to output it to the browser. We need to inform the browser, that we will output the image, not the text or html-code. To do it, call Header() function, setting image MIME-type. It’s worth mentioning that Header() function can not be executed if HTTP header has already been sent. After sending the header we can output our image using ImageJpeg() function, passing it image identifier as a parameter.

When we have finished working with the image we need to free up resources using ImageDestroy() function.

Back to top

Building a bar chart

In the example below, using graphic functions we will build a bar chart based on the values stored in MySQL database. In our case, values represent poll results.

In this example we will use poll database. To create it run the following SQL script in your MySQL server:

CREATE DATABASE `poll`;
USE poll;

CREATE TABLE `results` (
book_type VARCHAR(50),
num_votes INT
);

INSERT INTO `results` values
('Classic', 15),
('Fantasy', 7),
('Humor', 32),
('Mystery', 12),
('Poetry', 25);

Script building a bar chart is quite long, so let's divide it into two parts and discuss them separately. The first part of the script connects to MySQL database and requests data that will be represented in the bar chart.

//Querying the database to get poll results

//connection to the database
$dbhandle = mysql_connect("localhost", "root", "")
or die("Unable to connect to MySQL");

//select a database to work with
$selected = mysql_select_db("poll",$dbhandle)
or die("Could not select examples");

//execute the SQL query and return records
$result = mysql_query("SELECT * FROM results");

$num_poller = mysql_num_rows($result);
$total_votes = 0;

//fetch the data from the database
while ($row = mysql_fetch_array($result)) {
$total_votes += $row{'num_votes'}; //calculating total number of votes
}

//nulling the pointer $result
mysql_data_seek($result,0);

//close the connection
mysql_close($dbhandle);

In the second part of the script first of all we will calculate variables needed to build the chart. Then, we prepare primary image and actually output data. Results for each genre are picked from the database one by one, percentage of votes is calculated, and then bars and explanatory notes are outputted.

In this script we are using TrueType fonts to get anti-aliased text. Functions that work with the TrueType fonts have its own peculiarities. First, you need to point where the fonts are located. For this, system variable GDFONTPATH is set. Then, we need to set the font name. TrueType fonts are rendered using ImageTTFText().

We have already discussed above all functions used for drawing, the code has been commented and is quite clear, so you shouldn’t have any trouble.

//Tell gd2, where your fonts reside
putenv('GDFONTPATH=C:\WINDOWS\Fonts');
$font = 'arial';

//Set starting point for drawing
$y = 50;

//Specify constant values
$width = 700; //Image width in pixels
$bar_height = 20; //Bars height
$height = $num_poller * $bar_height * 1.5 + 70; //Calculating image height
$bar_unit = ($width - 400) / 100; //Distance on the bar chart standing for 1 unit

//Create the image resource
$image = ImageCreate($width, $height);

//We are making four colors, white, black, blue and red
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$red = ImageColorAllocate($image, 255, 0, 0);
$blue = imagecolorallocate($image,0,0,255);

//Create image background
ImageFill($image,$width,$height,$white);
//Draw background shape
ImageRectangle($image, 0, 0, $width-1, $height-1, $black);
//Output header
ImageTTFText($image, 16, 0, $width/3 + 50, $y - 20, $black, $font, 'Poll Results');

while ($row = mysql_fetch_object($result)) {
if ($total_votes > 0)
$percent = intval(round(($row->num_votes/$total_votes)*100));
else
$percent = 0;

//Output header for a particular value
ImageTTFText($image,12,0,10, $y+($bar_height/2), $black, $font, $row->book_type);
//Output percentage for a particular value
ImageTTFText($image, 12, 0, 170, $y + ($bar_height/2),$red,$font,$percent.'%');

$bar_length = $percent * $bar_unit;

//Draw a shape that corresponds to 100%
ImageRectangle($image, $bar_length+221, $y-2, (220+(100*$bar_unit)), $y+$bar_height, $black);
//Output a bar for a particular value
ImageFilledRectangle($image,220,$y-2,220+$bar_length, $y+$bar_height, $blue);
//Output the number of votes
ImageTTFText($image, 12, 0, 250+100*$bar_unit, $y+($bar_height/2), $black, $font, $row->num_votes.' votes cast.');

//Going down to the next bar
$y = $y + ($bar_height * 1.5);

}

//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

//Output the newly created image in jpeg format
ImageJpeg($image);

//Free up resources
ImageDestroy($image);
?>

Back to top

Using dynamically generated images on the other pages

Since the header can be sent only once and it is the only way to tell the browser that you are going to send image, it is not so easy to insert automatically generated images to the regular pages. There are three ways to do it:

  • The whole page can consist of the image.
  • You can save image in the file and then refer to it using HTML descriptor.
  • You can put a script producing image in HTML descriptor, e.g.:
Dynamically generated image

Related Articles

How to connect to MySQL database using PHP

Back to top

Tags: DYNAMIC IMAGE GENERATION GD CAPTCHA GRAPH STORE CACHE

Add To: Add to dzone dzone | Digg this digg | Add to del.icio.us del.icio.us | Stumble it stumbleupon


Hide Comments | Add New
Thank you for really useful tutorial!
# Posted by noizze | 27 Nov 2006 05:26:34
Very well written, thank you for the tip with putting the image in a html descriptor.
# Posted by fips | 2 Jan 2007 20:45:34
Great tutorial for the captcha, but it lacks the mechanism on how to tell the server to store and validate the security code against the user's input.
# Posted by OJ | 10 Jan 2007 22:33:04
Hello Sir It's REALLY useful, But i cannot use it.

Becoz the functions here referred is not identified in my PHP. So pls help to Configure it in WAMP 1.4 . Pls any body know it,pls mail me with details,

Thanks alot ....
# Posted by Anes P.A | 14 Jan 2007 22:39:47
Check your PHP and GD version first.
Use the latest stable version.
# Posted by JOKERz | 26 Jan 2007 04:55:19
thanx! very simple yet usable code... it is really easy to understand...
# Posted by smiley_sheinnize | 20 Feb 2007 22:17:00
how can i create pie chart using this code pls send me one example source code.
# Posted by bhavu_tailor | 10 Mar 2007 03:11:35
This Tutorial Worked For Me! Thanks For That!

To Make Charts, However, I Use The PHP/SWF Charts Found Here: http://www.maani.us/charts/index.php. I Try To Add In One Or Two Of Those Into Every Backend I Create. It Really Makes The Admin Go, "Wow!" Every Time.
# Posted by Rick Clark | 20 Mar 2007 15:19:08
sir,
when i run this program,
i got an error
Warning: imagettftext() [function.imagettftext]: Could not find/open font
how to find it in my php.ini file

im using WAMP5 1.6.6 version.
i went to php.ini file and uncommented php_gd2.dll to enable gd
and also commented to generate images dynamically.
;tidy.clean_output = Off

this tutorial is very useful for me.
# Posted by nalini | 22 Mar 2007 22:39:28
If you get "Warning: imagettftext() [function.imagettftext]: Could not find/open font" One easy fix is to simply copy the font file (i.e., arial.ttf), and paste it directly in the same folder as your PHP file. With Windows, the arial.ttf font file is typically located in C:\WINDOWS\Fonts\arial.ttf. There are, of course, other solutions.
# Posted by Geri | 28 Mar 2007 10:09:07
Very nice code .. It is usefull
# Posted by vinoth | 16 Apr 2007 21:54:40
Thanks for your help, I have implemented it in one of my projects : vk-systems.com for image validation.
# Posted by kapinder | 11 May 2007 00:50:05
Good morning everyone,

I am stuck on this problem - I need to know how to deal with this issue - what I am trying to do is modify the original image's size and location, while keeping it's physical size. For example, a 200X200 image of a cat will be resized by $percent, BUT be imagecopyresampled() into an image of the same size as the original, or 200X200. This is necessary for my project. So, my problem is that, when imagecopyresampled() at 98%, the image actually looks like it is resampled at 102%. Can someone please tell me what I've done wrong?

Thank you!


if (isset($_GET['image'])) {
move_save_image($_GET['image'], $_GET['x'], $_GET['y'], $_GET['percent']);
}
else {
echo "Could not load image";
}

function move_save_image($image, $x=0, $y=0, $percent=100) {

$image_withpath = "../dynproducts/dynimages/" .$image;

if (file_exists($image_withpath)) {
header('content-type: image/jpeg');

$modified = imagecreatefromjpeg($image_withpath);
$modified_size = getimagesize($image_withpath);

$width = $percent / 100 * $modified_size[0];
$height = $percent / 100 * $modified_size[1];

$visible_image = imagecreatetruecolor($width, $height);

$dest_x = $x;
$dest_y = $y;
$dest_a = $x * -1;
$dest_b = $y * -1;

imagecopyresampled($visible_image, $modified, 0, 0, $dest_a, $dest_b, $modified_size[0],$modified_size[1], $width, $height);

imagejpeg($visible_image, '', 80);

imagedestroy($visible_image);
imagedestroy($modified);
}
else {
echo "File does not exist.";
}

}
# Posted by Derge | 1 Jun 2007 06:05:22
hello webcheatsheet!

you php notes very useful and easy to understanding.please send quiz program using php
# Posted by anitha | 26 Sep 2007 08:26:34
It's REALLY useful
can i use different color for each Strip?
and how i can create image for vertical graph

thx
# Posted by pankaj | 23 Nov 2007 05:57:51
Very good code
thank you
Your Ad Here