//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Internet is vague. It has nothing left to be covered now. However, things get messed up sometimes and I forgot where I used to find the materials I had just searched for some days ago. So, I am now gathering all those into this blog. This is just my bookmark or my scrapbook or anything you wish to say. If you think these are helpful, you can take references, no any rights to be defined here. No styles and no colorful designs, just an area to jot down some scraps and all. Enjoy
Pages
Tuesday, May 14, 2013
curl post (php)
Sunday, September 25, 2011
A Simple readout on VAR keyword and SCOPE #PHP #javascript
var means opposite of global :)
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
PHP/Ajax based Jabber Web Chat Client.
http://blog.jwchat.org/jwchat/
Tuesday, May 11, 2010
PHP DOMElement innerHTML
Just a quick tip.
Use
DOMElement-Object->nodeValue;
Friday, April 16, 2010
Automatic Base URL in PHP
$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
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
Wednesday, October 21, 2009
0utput results to a file in SQL
Note:
File path should be writable, and should not exist.
Wednesday, August 19, 2009
codeigniter tweak for find_in_set
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.
Tuesday, June 9, 2009
Email validation in php
Thursday, April 30, 2009
select maximum value from an auto increment field
$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
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")
Thursday, May 15, 2008
Error 1 in APACHE
Greetings,
I have been using xampp for linux for a long time, and had not reported with any errors. But, just today I got an error reporting. Error 1: ..... So, I went through FAQ pages and searched in other search engines too, but could not find any proper answer that could solve my exact problem.
Then I started to have trials on my own. But, it was mystical when I found a log file named apachestart.log. Since the error was reported while starting apache, it had the error which i had expected. Why I mentioned this here, is because this file name is not included in the FAQ page, And as you have mentioned to email at this address, I am doing the same.
Regards,
Dhruba Adhikari
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 (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.)
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
unicodeText VARCHAR(45) NOT NULL
)
CHARACTER SET utf8 COLLATE utf8_general_ci;
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 <?phpBecause 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.
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>
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 | | |
| 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. 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); ?> 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:
Related Articles |
Tags: DYNAMIC IMAGE GENERATION GD CAPTCHA GRAPH STORE CACHE
Add To: dzone |
digg |
del.icio.us |
stumbleupon
- Comments (16)
- Blog 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 ....
Use the latest stable version.
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.
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.
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.";
}
}
you php notes very useful and easy to understanding.please send quiz program using php
can i use different color for each Strip?
and how i can create image for vertical graph
thx
thank you
Monday, December 3, 2007
Saturday, November 17, 2007
mysql_fetch_object
website:http://www.php.net/manual/en/function.mysql-fetch-object.php
mysql_fetch_object
(PHP 4, PHP 5, PECL mysql:1.0)
mysql_fetch_object — Fetch a result row as an object
Description
object mysql_fetch_object ( resource $result [, string $class_name [, array $params]] )Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.
Parameters
- result
The result resource that is being evaluated. This result comes from a call to mysql_query().
- class_name
The name of the class to instantiate, set the properties of and return. If not specified, a
stdClassobject is returned.- params
An optional array of parameters to pass to the constructor for class_name objects.
Return Values
Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
ChangeLog
| Version | Description |
|---|---|
| 5.0.0 | Added the ability to return as a different object. |
Examples
Example 1428. mysql_fetch_object() example
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>
Example 1429. mysql_fetch_object() example
$row = mysql_fetch_object($result);
/* this is valid */
echo $row->field;
/* this is invalid */
// echo $row->0;
?> Notes
Performance: Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).
Note: mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to PHP NULL value.
PHP, BLOB and picture
$sql = "SELECT Pic FROM Pictures WHERE ID=$id";
if(!($result=@mysql_query($sql))) showerror;
$data=@mysql_fetch_array($result);
if (!empty($data['Pic']))
{
//Change content type to your file type
header("Content-Type: image/gif");
print $data['Pic'] ;
}