Understanding Regular Expression
Regular expression is the most important part in form validations and it is widely used for search, replace and web crawling systems. If you want to write a selector engine (used to find elements in a DOM), it should be possible with Regular Expressions. In this post we explained few tips that how to understand and write the Regular Expression in simple way.
Will discuss about basic regular expression in three stages.
Stage 1
Symbol Explanation
^ Start of string
$ End of string
. Any single character
+ One or more character
\ Escape Special characters
? Zero or more characters
Input exactly match with “abc”
var A = /^abc$/;
Input start with “abc”
var B = /^abc/;
Input end with “abc”
var C = /abc$/;
Input “abc” and one character allowed Eg. abcx
var D = /^abc.$/;
Input “abc” and more than one character allowed Eg. abcxy
var E = /^abc.+$/;
Input exactly match with “abc.def”, cause (.) escaped
var F = /^abc\.def$/;
Passes any characters followed or not by “abc” Eg. abcxyz12….
var G = /^abc.+?$/
Stage 2
Char Group Explanation
[abc] Should match any single of character
[^abc] Should not match any single character
[a-zA-Z0-9] Characters range lowercase a-z, uppercase A-Z and numbers
[a-z-._] Match against character range lowercase a-z and ._- special chats
(.*?) Capture everything enclosed with brackets
(com|info) Input should be “com” or “info”
{2} Exactly two characters
{2,3} Minimum 2 characters and Maximum 3 characters
{2,} More than 2 characters
Put together all in one URL validation.
var URL = /^(http|https|ftp):\/\/(www+\.)?[a-zA-Z0-9]+\.([a-zA-Z]{2,4})\/?/;
URL.test(“http://selvabalaji.com); // pass
URL.test(“http://www.selvabalaji.com”); // pass
URL.test(“https://selvabalaji.com/”); // pass
URL.test(“http://selvabalaji.com/index.php”); // pass
Stage 3
Short Form Equivalent Explanation
\d [0-9] Any numbers
\D [^0-9] Any non-digits
\w [a-zA-Z0-9_] Characters,numbers and underscore
\W [^a-zA-Z0-9_] Except any characters, numbers and underscore
\s – White space character
\S – Non white space character
var number = /^(\+\d{2,4})?\s?(\d{10})$/; // validating phone numbernumber.test(1111111111); //pass
number.test(+111111111111); //pass
number.test(+11 1111111111); //pass
number.test(11111111); //Fail
Get line number of the code
<!--?
class myTest
{
function addMyAddress($street)
{
echo "
In class function at:".__LINE__;
echo "
class function called from:";
$e = new Exception();
$trace = $e->getTrace();
echo '
';print_r($trace);
// OR print_r(debug_backtrace());
}
}
echo "
Class created at:".__LINE__; $obj = new myTest();
echo "
Function called at:".__LINE__; $obj->addMyAddress('A/13 Skyline');
?>
Jquery Timeago Implementation with PHP.
Nowadays timeago is the most important functionality in social networking sites, it helps to updating timestamps automatically. Recent days I received few requests from 9lessons readers that asked me how to implement timeago plugin with dynamic loading live data using PHP. In this post I am just presenting a simple tip to implement timeago in a better way.
Why Live Query
LiveQuery utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
Code
Contains javascipt code. $(this).timeago()- here this element is refers to timeagoclass selector of the anchor tag.
// <![CDATA[
javascript” src=”js/jquery.min.js”>
// ]]>
// <![CDATA[
javascript” src=”js/jquery.livequery.js”>
// ]]>
// <![CDATA[
javascript” src=”js/jquery.timeago.js”>
// ]]>
<script type=”text/javascript”>
$(document).ready(function(){
$(“.timeago”).livequery(function() // LiveQuery
{
$(this).timeago(); // Calling Timeago Funtion
});
});
</script>//HTML & PHP Code
<!–?php
$time=time(); // Current timestamp eg: 1371612613
$mtime=date(“c”, $time); // Converts to date formate 2013-06-19T03:30:13+00:00
?>You opened this page <a href=’#’ class=’timeago’ title=”<!–?php echo$mtime; ?>“></a>
Login with Facebook using PHP SDK in CakePHP
Here we used PHP SDK 3.0 and CakePHP 2.X for the process of authentication and authorizing users for your app.
For Creating an App, which you can obtain from the App Dashboard.
You need App Id and App Secret for integration of the facebook login in cakephp.
In this CakePHP module we included the Facebook PHP SDK 3.0 in vendors of the app directory.And we define Some variables in Core.php
And We create one file which is facebook.php in config folder for the define of AppId and Appsecret.
$config
=
array
(
'Facebook'
=>
array
(
'appId'
=>
'YOUR APP ID'
,
'secret'
=>
'YOUR APP SECRET'
,
)
);
We create one Controller which is FacebookCpsController.php
<?php
App::uses(
'Controller'
,
'Controller'
);
App::import(
'Vendor'
,
'Facebook'
,
array
(
'file'
=>
'Facebook'
.DS.
'facebook.php'
));
class
FacebookCpsController
extends
AppController {
public
$name
=
'FacebookCps'
;
public
$uses
=
array
();
public
function
index(){
$this
->layout=false;
}
function
login()
{
Configure::load(
'facebook'
);
$appId
=Configure::read(
'Facebook.appId'
);
$app_secret
=Configure::read(
'Facebook.secret'
);
=
new
Facebook(
array
(
'appId'
=>
$appId
,
'secret'
=>
$app_secret
,
));
$loginUrl
=
->getLoginUrl(
array
(
'scope'
=>
'email,read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos'
,
'redirect_uri'
=> BASE_URL.
'facebook_cps/facebook_connect'
,
'display'
=>
'popup'
));
$this
->redirect(
$loginUrl
);
}
function
facebook_connect()
{
Configure::load(
'facebook'
);
$appId
=Configure::read(
'Facebook.appId'
);
$app_secret
=Configure::read(
'Facebook.secret'
);
=
new
Facebook(
array
(
'appId'
=>
$appId
,
'secret'
=>
$app_secret
,
));
$user
=
->getUser();
if
(
$user
){
try
{
$user_profile
=
->api(
'/me'
);
$params
=
array
(
'next'
=> BASE_URL.
'facebook_cps/facebook_logout'
);
$logout
=
->getLogoutUrl(
$params
);
$this
->Session->write(
'logout'
,
$logout
);
}
catch
(FacebookApiException
$e
){
error_log
(
$e
);
$user
= NULL;
}
}
else
{
$this
->Session->setFlash(
'Sorry.Please try again'
,
'default'
,
array
(
'class'
=>
'msg_req'
));
$this
->redirect(
array
(
'action'
=>
'index'
));
}
}
function
facebook_logout(){
$this
->Session->
delete
(
'User'
);
$this
->Session->
delete
(
'logout'
);
$this
->redirect(
array
(
'action'
=>
'index'
));
}
}
?>
Here We create two view files for the FacebookCpsController which are located in app/View/FacebookCps directory.
index.ctp
<!--DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<head>
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=utf-8"
/>
<title>Login with Facebook In CakePHP</title>
<?php
echo
$this
->Html->script(
'oauthpopup'
); ?>
<script type=
"text/javascript"
>
$(document).ready(
function
(){
$(
'#facebook'
).click(
function
(e){
$.oauthpopup({
path:
'facebook_cps/login'
,
width:600,
height:300,
callback:
function
(){
window.location.reload();
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<?php
$ses_user
=
$this
->Session->read(
'User'
);
$logout
=
$this
->Session->read(
'logout'
);
if
(!
$this
->Session->check(
'User'
) &&
empty
(
$ses_user
)) {
echo
$this
->Html->image(
'facebook.png'
,
array
(
'id'
=>
'facebook'
,
'style'
=>
'cursor:pointer;float:left;margin-left:550px;'
));
}
else
{
echo
'<img src="https://graph.facebook.com/'
.
$ses_user
[
'id'
] .
'/picture" width="30" height="30"/><div>'
.
$ses_user
[
'name'
].
'</div>'
;
echo
'<a href="'
.
$logout
.
'">Logout</a>'
;
}
?>
</body>
</html>
facebook_connect.ctp
<script type=
"text/javascript"
>
window.close();
</script>
Here I used one jquery plugin oauthpopup.jswhich is used for popup
(this file is located in app/webroot/js directory)
oauthpopup.js
(function (jQuery) {
jQuery.oauthpopup = function (options) {
options.windowName = options.windowName || ‘ConnectWithOAuth’;
options.windowOptions = options.windowOptions || ‘location=0,status=0,width=’+options.width+’,height=’+options.height+’,scrollbars=1′;
options.callback = options.callback || function () {
window.location.reload();
};
var that = this;
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
that._oauthInterval = window.setInterval(function () {
if (that._oauthWindow.closed) {
window.clearInterval(that._oauthInterval);
options.callback();
}
}, 1000);
};
})(jQuery);
In the PHP SDK 3.0,we change the facebook.php file.For the Session We uses the CakePHP core data source which is CakeSession. facebook.php file is located at app/Vendor/Facebook directory
facebook.php
//included this line the above class
App::uses(
'CakeSession'
,
'Model/Datasource'
);
public
function
__construct(
$config
) {
if
(!session_id()) {
//insted of session_start() we used CakeSession::start()
CakeSession::start();
}
parent::__construct(
$config
);
if
(!
empty
(
$config
[
'sharedSession'
])) {
$this
->initSharedSession();
}
}
Payment System with Paypal
I received a tutorial requests from my reader that asked to me how to implement payment gateway system with Paypal API. In this post I want to explain how to work with Paypal Sandbox test accounts for payment system development and sending arguments while click buy now button. It’s simple and very easy to integrate in your web projects.
Sample database design for Payment system. Contains there table users,products and sales.
Users
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(255),
`email` varchar(255) UNIQUE KEY,
)
Products
(
`pid` int(11) AUTO_INCREMENT PRIMARY KEY,
`product` varchar(255),
‘product_img` varchar(100),
`price` int(11),
`currency` varchar(10),
)
Sales
(
`sid` int(11) AUTO_INCREMENT PRIMARY KEY,
`pid` int(11),
`uid` int(11),
`saledate` date,
`transactionid` varchar(125),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(pid) REFERENCES products(pid)
)
Create a Paypal Sandbox account at https://developer.paypal.com/
Now create test accounts for payment system. Take a look at Sandbox menu left-side top Sandbox->Test Accounts
Here I have created two accounts Buyer (personal) and Seller(merchant/business)
products.php
Contains PHP code. Displaying records from products table product image,product name and product price. Here you have to give your business(seller)$paypal_id id. Modify paypal button form return and cancel_return URLs.
<?php
session_start();
require ‘db_config.php’;
$uid=$_SESSION[‘uid’];
$username=$_SESSION[‘username’];
$paypal_url=’https://www.sandbox.paypal.com/cgi-bin/webscr‘; // Test Paypal API URL
$paypal_id=’your_seller_id‘; // Business email ID
?>
<body>
<h2>Welcome, <?php echo $username;?></h2>
<?php
$result = mysql_query(“SELECT * from products”);
while($row = mysql_fetch_array($result))
{
?>
<img src=”images/<?php echo $row[‘product_img’];?>” />
Name: <?php echo $row[‘product’];?>
Price: <?php echo $row[‘price’];?>$
// Paypal Button
<form action=’<?php echo $paypal_url; ?>‘ method=’post’ name=’form<?php echo $row[‘pid’]; ?>’>
<input type=’hidden’ name=’business’ value=’<?php echo $paypal_id; ?>‘>
<input type=’hidden’ name=’cmd’ value=’_xclick’>
<input type=’hidden’ name=’item_name’ value=’<?php echo$row[‘product’];?>‘>
<input type=’hidden’ name=’item_number’ value=’<?php echo$row[‘pid’];?>‘>
<input type=’hidden’ name=’amount’ value=’<?php echo $row[‘price’];?>‘>
<input type=’hidden’ name=’no_shipping’ value=’1′>
<input type=’hidden’ name=’currency_code’ value=’USD‘>
<input type=’hidden’ name=’cancel_return‘ value=’http://yoursite.com/cancel.php’>
<input type=’hidden’ name=’return‘ value=’http://yoursite.com/success.php’>
<input type=”image” src=”https://paypal.com/en_US/i/btn/btn_buynowCC_LG.gif” name=”submit”>
</form>
<?php
}
?>
</body>
success.php
Paypal payment success return file. Getting Paypal argument like item_number. Paypal data success.php?tx=270233304D340491B&st=Completed&amt=22.00&cc=USD&cm=&item_number=1
session_start();
require ‘db_config.php’;
$uid = $_SESSION[‘uid’];
$username=$_SESSION[‘username’];
$item_no = $_GET[‘item_number’];
$item_transaction = $_GET[‘tx’]; // Paypal transaction ID
$item_price = $_GET[‘amt’]; // Paypal received amount
$item_currency = $_GET[‘cc’]; // Paypal received currency type//Getting product details
$sql=mysql_query(“select product,price,currency from producst where pid=’$item_no'”);
$row=mysql_fetch_array($sql);
$price=$row[‘price’];
$currency=$row[‘currency’];//Rechecking the product price and currency details
if($item_price==$price && item_currency==$currency)
{
$result = mysql_query(“INSERT INTO sales(pid, uid, saledate,transactionid) VALUES(‘$item_no’, ‘$uid’, NOW(),’$item_transaction’)”);
if($result)
{
echo “<h1>Welcome, $username</h1>”;
echo “<h1>Payment Successful</h1>”;
}
}
else
{
echo “Payment Failed”;
}
?>
PHP Innovation Award Winner of 2012
The PHP Programming Innovation Award Winner of 2012 was announced. An interview with the winner, Karl Holz from Canada, was one of the main topics of the episode 33 of the Lately in PHP podcast conducted by Manuel Lemos and Ernani Joppert.
They also discussed the usual batch of PHP topics of interest like Zend Optimizer+ source code that was released, the PHP 5.5 feature freeze and roadmap, as well an article that compares PHP to an Hobbit, as well other languages to Lord Of The Rings story characters.
Listen to the podcast, or watch the podcast video, or read the transcript to learn about these and other interesting PHP topics.
Upload Cover Photo to Facebook via PHP
Here is a tutorial to upload a Cover Photo on Facebook via PHP. We will need Facebook Application ID and Secret, and Facebook files from Github.com then upload to your web space only the src folder. Now create a file called upload.php and upload it to your web space. Open upload.php with notepad and add this code:
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require 'src/facebook.php'; $facebook = new Facebook(array( 'appId' => "xxxxxxxxxxxxxxxxxxx", //Facebook App ID 'secret' => "xxxxxxxxxxxxxxxxxxx", // Facebook App Secret "cookie" => true, 'fileUpload' => true )); $user_id = $facebook->getUser(); if($user_id == 0 || $user_id == "") { $login_url = $facebook->getLoginUrl(array( 'redirect_uri' => 'https://selvabalaji.wordpress.com/upload.php?cover='.$_GET['cover'].'', // Replace with your site url 'scope' => "publish_stream,user_photos")); echo "<script type='text/javascript'>top.location.href = '$login_url';</script>"; exit(); } //get user album $albums = $facebook->api("/me/albums"); $album_id = ""; foreach($albums["data"] as $item){ if($item["type"] == "cover_photo"){ $album_id = $item["id"]; break; } } //set timeline cover atributes $full_image_path = realpath($_GET['cover']); $args = array('message' => 'Uploaded from hhttps://selvabalaji.wordpress.com/'); $args['image'] = '@' . $full_image_path; //upload cover photo to Facebook $data = $facebook->api("/me/photos", 'post', $args); $picture = $facebook->api('/'.$data['id']); $fb_image_link = 'http://www.facebook.com/profile.php?preview_cover='.$data['id'].''; //redirect to uploaded facebook cover and change it echo "<script type='text/javascript'>top.location.href = '$fb_image_link';</script>"; ?>
Now that just type in the URL of your site followed by the name of the image file and you’re done!
Example : http://yoursitename.com/upload.php?cover=selvabalaji.gif
This article teaches you how to create pagination like twitter using jquery, PHP and MySQL. The content can be loaded at the end of old content when we scroll the page. Your can create your own pagination after completing this article. It is very easy to implement, you can just copy and paste the code. Please follow the steps given below to create your won pagination style.
1. Create table in MySQL using following query statement
CREATE TABLE IF NOT EXISTS `job` ( `job_id` INT(11) NOT NULL AUTO_INCREMENT, `job_name` INT(11) NOT NULL, PRIMARY KEY (`job_id`) ) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
2. Create database connection file ie connection.php
$DB_Username = "root"; $DB_Password = ""; $DB_DATABASE = "database_name"; $DB_HOST = "localhost"; $Connect = @mysql_connect($DB_HOST, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL: " . mysql_error() . " " . mysql_errno()); //select database $Db = @mysql_select_db($DB_DATABASE, $Connect) or die("Couldn't select database: " . mysql_error(). " " . mysql_errno());
3. Create index.php where you can write following codes
<?php
/*
Author: selvaBalaji
Email:selvabalaji@gmail.com
Date: oct 26 2012
*/
include(“connection.php”);
if(isset($_GET[‘lastID’]) && is_numeric($_GET[‘lastID’]))
$lastID =intval($_GET[‘lastID’]);
if(!isset($_GET[‘lastID’]))
{
?>
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js”>
</script>
<style>
#loader {
border:1px solid #ccc;
padding:10px;
margin:10px 0 0 0;
text-align:center;
}
.contentpane{}
.rowHolder{
border:1px solid #ccc;
padding:10px;
margin:10px 0 0 0;
}
</style>
<script type=”text/javascript”>
$(document).ready(function(){
function lastRecord()
{
$(‘div#loader’).html(‘<img src=”loader.gif” alt=”Loading…”>’);
$.post(“index.php?lastID=”+$(“.contentpane table tr:last”).attr(“id”),
function(data){
if (data != “”) {
$(“.contentpane table tr:last”).after(data);
}
$(‘div#loader’).empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() – $(window).height()){
lastRecord();
}
});});
</script>
</head>
<body>
<h1>Pagination </h1>
<p class=”hr” style=”padding:2px 0 2px 0;”></p>
<div class=”contentpane”>
<table width=”100%” border=”0″ cellpadding=”0″ cellspacing=”0″>
<?php
$sql=”SELECT * FROM job ORDER BY job_id DESC limit 30″;
$result = mysql_query($sql);
while($record = mysql_fetch_array($result))
{
$lastID = $record[‘job_id’];
?>
<tr id=”<?php echo $record[‘job_id’];?>”>
<td><div class=”rowHolder”><?php echo $record[‘job_name’];?></div></td>
</tr>
<?php
}
?>
</table>
</div>
<div id=”loader”></div>
</body>
</html>
<?php
}
else
{
$sql=”SELECT * FROM job WHERE job_id < $lastID
ORDER BY job_id DESC LIMIT 3″;
$result = mysql_query($sql);
while($record = mysql_fetch_array($result))
{
?>
<tr id=”<?php echo $record[‘job_id’];?>”>
<td><div class=”rowHolder”><?php echo $record[‘job_name’];?></div></td>
</tr>
<?php
}
}
?>
India soon to be the biggest source of PHP developers?
The number of Indian PHP developers has been growing at a large pace in the last few years, when compared to other countries. A few years ago, India was just one of the top ten countries with more PHP developers. Now India is number 2 and is almost surpassing United States, which is still number 1.
While it is difficult to take such broad conclusions seriously based on member statistics of a single community, PHPClasses does have a large user base and can arguably be considered representative. Any article tagged India and software these days attract the usual crap about how Indian developers are the worst and how everybody who outsources to India never does it again. So I was surprised when some of the usually ‘silent’ majority of the client base who continue outsourcing development to India came out to defend their decision.
I did come away with a very interesting statistic; Indian developers have won most awards this year for their contribution against sizable competition. Most Indian developers I meet have difficulty understanding the concept of giving back to the community, so it’s always refreshing to see a number of people doing exactly that.
How to Make a Slick Ajax Contact Form with jQuery and PHP
Contact forms can be useful way for visitors to contact the owner of a site. They’re easy to use, and since they don’t expose the site owner’s email address in the page, they cut down on spam too.
However, contact forms can also be cumbersome, especially as they’re usually on a separate page. The visitor has to visit the contact form page, fill in the details, view yet another response page, and then try to make their way back to the page they were originally reading.
Fortunately, Ajax gives us a way round this problem. By embedding the form in the page, and submitting the form data via Ajax, the user never has to leave the current page. It also provides a smoother experience for the user.
In this tutorial we’ll build a nice-looking, embedded Ajax contact form that the user can summon up by clicking a link in the page. Along the way, we’ll explore various topics, including:
- HTML5 form fields
- How to use fallback techniques to make the form function even if the browser has JavaScript turned off
- Using CSS techniques to create attractive forms
- Writing a secure form mailer using PHP
- Animating page elements with jQuery, and, of course…
- Using jQuery to make Ajax requests
Before you begin, check out the finished product by clicking the View Demo button above. This opens a new page with some dummy content, and a couple of “Send us an email” links. Click one of these links to display the form.
Step 1: Create the markup
Let’s start with the HTML for our page. This includes the form itself — we’ll hide it initially using JavaScript when the page loads — and also some dummy content and a couple of “Send us an email” links that will display the form when clicked:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<!doctype html> < html lang = "en" > < head > < title >A Slick Ajax Contact Form with jQuery and PHP</ title > </ head > < body > < div id = "content" > < p style = "padding-bottom: 50px; font-weight: bold; text-align: center;" >< a href = "#contactForm" >~ Send us an email ~</ a ></ p > <!-- Content here --> < p style = "padding-top: 50px; font-weight: bold; text-align: center;" >< a href = "#contactForm" >~ Send us an email ~</ a ></ p > </ div > < form id = "contactForm" action = "processForm.php" method = "post" > < h2 >Send us an email...</ h2 > < li > < input type = "text" name = "senderName" id = "senderName" placeholder = "Please type your name" required = "required" maxlength = "40" /> </ li > < li > < label for = "senderEmail" >Your Email Address</ label > < input type = "email" name = "senderEmail" id = "senderEmail" placeholder = "Please type your email address" required = "required" maxlength = "50" /> </ li > < li > < label for = "message" style = "padding-top: .5em;" >Your Message</ label > < textarea name = "message" id = "message" placeholder = "Please type your message" required = "required" cols = "80" rows = "10" maxlength = "10000" ></ textarea > </ li > </ ul > < div id = "formButtons" > < input type = "submit" id = "sendMessage" name = "sendMessage" value = "Send Email" /> < input type = "button" id = "cancel" name = "cancel" value = "Cancel" /> </ div > </ form > < div id = "sendingMessage" class = "statusMessage" >< p >Sending your message. Please wait...</ p ></ div > < div id = "successMessage" class = "statusMessage" >< p >Thanks for sending your message! We'll get back to you shortly.</ p ></ div > < div id = "failureMessage" class = "statusMessage" >< p >There was a problem sending your message. Please try again.</ p ></ div > < div id = "incompleteMessage" class = "statusMessage" >< p >Please complete all the fields in the form before sending.</ p ></ div > </ body > </ html > |
I’ve omitted the dummy content in the above code, since it’s not relevant to the tutorial.
The form sends its data to a processForm.php
script that does the actual emailing. (We’ll write this PHP script in a moment.) By setting the form’s action
attribute to "processForm.php"
, we ensure that the form is usable even with JavaScript disabled. Later, our JavaScript will read this action
attribute so that it knows where to send the Ajax request.
The form itself uses some HTML5 form features such as placeholders, the email
field type, and the required
attribute to ensure that all the fields have been filled in. We’ll also add JavaScript validation for browsers that don’t yet support HTML5 validation.
Step 2: Add the CSS
Now we’ll add the CSS to our HTML page in order to style the page and form. The bulk of the CSS positions the form and status messages in the centre of the window, and styles the form and form fields.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
|
<style type= "text/css" > /* Add some margin to the page and set a default font and colour */ body { margin : 30px ; font-family : "Georgia" , serif ; line-height : 1.8em ; color : #333 ; } /* Set the content dimensions */ #content { width : 800px ; padding : 50px ; margin : 0 auto ; display : block ; font-size : 1.2em ; } #content h 2 { line-height : 1.5em ; } /* Add curved borders to various elements */ #contactForm, .statusMessage, input[type= "submit" ], input[type= "button" ] { - moz-border-radius : 10px ; - webkit-border-radius : 10px ; border-radius : 10px ; } /* Style for the contact form and status messages */ #contactForm, .statusMessage { color : #666 ; background-color : #ebedf2 ; background : -webkit-gradient( linear, left bottom , left top , color-stop( 0 , #dfe1e5 ), color-stop( 1 , #ebedf2 ) ); background : -moz-linear-gradient( center bottom , #dfe1e5 0% , #ebedf2 100% ); border : 1px solid #aaa ; - moz-box-shadow : 0 0 1em rgba( 0 , 0 , 0 , . 5 ); - webkit-box-shadow : 0 0 1em rgba( 0 , 0 , 0 , . 5 ); box-shadow : 0 0 1em rgba( 0 , 0 , 0 , . 5 ); opacity : . 95 ; } /* The form dimensions */ #contactForm { width : 40em ; height : 33em ; padding : 0 1.5em 1.5em 1.5em ; margin : 0 auto ; } /* Position the form in the middle of the window (if JavaScript is enabled) */ #contactForm.positioned { position : fixed ; top : 0 ; bottom : 0 ; left : 0 ; right : 0 ; margin-top : auto ; margin-bottom : auto ; } /* Dimensions and position of the status messages */ .statusMessage { display : none ; margin : auto ; width : 30em ; height : 2em ; padding : 1.5em ; position : fixed ; top : 0 ; bottom : 0 ; left : 0 ; right : 0 ; } .statusMessage p { text-align : center ; margin : 0 ; padding : 0 ; } /* The header at the top of the form */ #contactForm h 2 { font-size : 2em ; font-style : italic ; letter-spacing : . 05em ; margin : 0 0 1em -. 75em ; padding : 1em ; width : 19.5em ; color : #aeb6aa ; background : #dfe0e5 url ( 'images/stamp.jpg' ) no-repeat 15em -3em ; /* http://morguefile.com/archive/display/606433 */ border-bottom : 1px solid #aaa ; - moz-border-radius : 10px 10px 0 0 ; - webkit-border-radius : 10px 10px 0 0 ; border-radius : 10px 10px 0 0 ; } /* Give form elements consistent margin, padding and line height */ #contactForm ul { list-style : none ; margin : 0 ; padding : 0 ; } #contactForm ul li { margin : . 9em 0 0 0 ; padding : 0 ; } #contactForm input, #contactForm label { line-height : 1em ; } /* The field labels */ label { display : block ; float : left ; clear : left ; text-align : right ; width : 28% ; padding : . 4em 0 0 0 ; margin : . 15em . 5em 0 0 ; font-weight : bold ; } /* The fields */ input, textarea { display : block ; margin : 0 ; padding : . 4em ; width : 67% ; font-family : "Georgia" , serif ; font-size : 1em ; border : 1px solid #aaa ; - moz-border-radius : 5px ; - webkit-border-radius : 5px ; border-radius : 5px ; - moz-box-shadow : rgba( 0 , 0 , 0 ,. 2 ) 0 1px 4px inset ; - webkit-box-shadow : rgba( 0 , 0 , 0 ,. 2 ) 0 1px 4px inset ; box-shadow : rgba( 0 , 0 , 0 ,. 2 ) 0 1px 4px inset ; background : #fff ; } textarea { height : 13em ; line-height : 1.5em ; resize: none ; } /* Place a border around focused fields, and hide the inner shadow */ #contactForm *:focus { border : 1px solid #66f ; outline : none ; box-shadow : none ; - moz-box-shadow : none ; - webkit-box-shadow : none ; } /* Display correctly filled-in fields with a green background */ input:valid, textarea:valid { background : #dfd ; } /* The Send and Cancel buttons */ input[type= "submit" ], input[type= "button" ] { float : right ; margin : 2em 1em 0 1em ; width : 10em ; padding : . 5em ; border : 1px solid #666 ; - moz-border-radius : 10px ; - webkit-border-radius : 10px ; border-radius : 10px ; - moz-box-shadow : 0 0 . 5em rgba( 0 , 0 , 0 , . 8 ); - webkit-box-shadow : 0 0 . 5em rgba( 0 , 0 , 0 , . 8 ); box-shadow : 0 0 . 5em rgba( 0 , 0 , 0 , . 8 ); color : #fff ; background : #0a0 ; font-size : 1em ; line-height : 1em ; font-weight : bold ; opacity : . 7 ; - webkit-appearance : none ; - moz-transition : opacity . 5 s; - webkit-transition : opacity . 5 s; - o-transition : opacity . 5 s; transition : opacity . 5 s; } input[type= "submit" ]:hover, input[type= "submit" ]:active, input[type= "button" ]:hover, input[type= "button" ]:active { cursor : pointer ; opacity : 1 ; } input[type= "submit" ]:active, input[type= "button" ]:active { color : #333 ; background : #eee ; - moz-box-shadow : 0 0 . 5em rgba( 0 , 0 , 0 , . 8 ) inset ; - webkit-box-shadow : 0 0 . 5em rgba( 0 , 0 , 0 , . 8 ) inset ; box-shadow : 0 0 . 5em rgba( 0 , 0 , 0 , . 8 ) inset ; } input[type= "button" ] { background : #f33 ; } /* Header/footer boxes */ .wideBox { clear : both ; text-align : center ; margin : 70px ; padding : 10px ; background : #ebedf2 ; border : 1px solid #333 ; } .wideBox h 1 { font-weight : bold ; margin : 20px ; color : #666 ; font-size : 1.5em ; } </style> <!-- Some IE 7 hacks and workarounds --> <!--[if lt IE 8 ]> <style> /* IE7 needs the fields to be floated as well as the labels */ input, textarea { float : right ; } #formButtons { clear : both ; } /* IE7 needs an ickier approach to vertical/horizontal centring with fixed positioning. The negative margins are half the element's width/height. */ #contactForm.positioned, .statusMessage { left : 50% ; top : 50% ; } #contactForm.positioned { margin-left : -20em ; margin-top : -16.5em ; } .statusMessage { margin-left : -15em ; margin-top : -1em ; } </style> <![endif]--> |
Let’s look at some interesting sections of the CSS:
- Style for the contact form and status messages
We give the form and status boxes a nice gentle top-to-bottom gradient using-webkit-gradient
and-moz-linear-gradient
, and we also add a drop shadow withbox-shadow
(and its vendor-specific variants). Finally, we give the form and message boxes an opacity of .95 (95%), which makes the page content just show through — a nice subtle effect. - Position the form in the middle of the window (if JavaScript is enabled)
Initially, we simply place the form inline after the page content. This is so that the form can be used for non-JavaScript-enabled browsers without getting in the way of the content. However, for JavaScript browsers, we want the form to appear in the centre of the window, over the top of the content.Our#contactForm.positioned
rule does just that. It uses fixed positioning, sets thetop
,bottom
,left
andright
values all to zero, and ensures that all 4 margins are set toauto
. This centres the element both horizontally and vertically in most modern browsers. Later we’ll use our JavaScript to add thepositioned
class to the form.We also position the status message boxes in the same way. - The header at the top of the form
Our form includes a nice “Send us an email…” header with an image of a postage stamp. Our#contactForm h2
rule styles this header. We give the text a large italic style and space the letters out slightly. We also add margin and padding to create space around and inside the header. We use some negative left margin (-.75em) on the header to bypass the padding on the form, so that the header goes right to the left edge of the form. We also set the width of the header to 19.5em so that it exactly matches the width of the form.Why -.75em and 19.5em? Because ems cascade, and we’ve set our font size to 2em. So -.75em actually becomes -1.5em (the width of the form’s padding), and 19.5em becomes 39em (the width of the form, minus 1em for theh2
‘s padding). Phew! Maybe I’ll use pixels next time… :)We also set the heading’s colour, give it a dark background, position the postage stamp image in the top right corner, add a thin bottom border, and add curved top corners. - The fields
We give theinput
andtextarea
fields an attractive font, a rounded border usingborder-radius
, and a gentle inner shadow usingbox-shadow
. We also float the field labels left so that they sit alongside the fields. When a field is focused (clicked on or moved to with the Tab key), we give it a blue border and remove the shadow. We also setoutline: none
to remove the blue outline added by some browsers. Finally, we use the:valid
pseudo-class to give correctly completed fields a green background, for those browsers that support HTML5 form validation. - The Send and Cancel buttons
input[type="submit"]
selects the Send Email button, whileinput[type="button"]
selects the Cancel button. We float them right to position them side by side, and add some margin to give them space. We give them a fixed width, and some padding to make them a decent size. We add a rounded border and subtle drop shadow, and specify text and background colours. We also make the buttons slightly transparent (opacity: .7
), and make them fully transparent when hovered over to highlight them. We use a CSS transition to fade the opacity slowly. Finally, when the buttons are clicked (:active
) we move the shadow inside the buttons to give a “pressed” appearance, and give them a black-on-white colour scheme.
Step 3: Build the PHP form mailer
We’ve now created our form page, and styled the form. The next step is to build a short PHP script to actually send the email messages. This script will reside on the web server. When the user submits the form, the form’s data is sent to the PHP script, which then sends the email and returns a response indicating whether or not the email was sent successfully.
Here’s the PHP script — call it processForm.php
, and save it in the same folder as the form page you created in Steps 1 and 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<?php // Define some constants define( "RECIPIENT_NAME" , "John Smith" ); define( "RECIPIENT_EMAIL" , "john@example.com" ); define( "EMAIL_SUBJECT" , "Visitor Message" ); // Read the form values $success = false; $senderName = isset( $_POST [ 'senderName' ] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/" , "" , $_POST ['senderName'] ) : "" ; $senderEmail = isset( $_POST [ 'senderEmail' ] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/" , "" , $_POST [ 'senderEmail' ] ) : "" ; $message = isset( $_POST [ 'message' ] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/" , "" , $_POST [ 'message' ] ) : "" ; // If all values exist, send the email if ( $senderName && $senderEmail && $message ) { $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">" ; $headers = "From: " . $senderName . " <" . $senderEmail . ">" ; $success = mail( $recipient , EMAIL_SUBJECT, $message , $headers ); } // Return an appropriate response to the browser if ( isset( $_GET [ "ajax" ]) ) { echo $success ? "success" : "error" ; } else { ?> <html> <head> <title>Thanks!</title> </head> <body> <?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?> <?php if ( ! $success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?> <p>Click your browser's Back button to return to the page.</p> </body> </html> <?php } ?> |
This script is fairly straightforward. Let’s break it down:
- Define some constants
First we define some config options for the name and email address of the person who will receive the email message. (Change these to your own name and email address.) We also set a subject for the message. - Read the form values
Next we check for our 3 form fields,senderName
,senderEmail
andmessage
, in the posted form data. For each field, we check if it exists. If it does then we pass its value through a regular expression to remove any potentially malicious characters that a spammer might try to use, and store the result in a variable. If it doesn’t exist then we set the variable to an empty value. - If all values exist, send the email
If the 3 field values all contain data then we send the email. First we construct the recipient string from the recipient name and email address. Then we add a"From:"
header to the message using the name and email address that the visitor entered in the form. This is the “From:” value that the recipient will see in their email program. Finally, we use the PHPmail()
function to send the email message, storing the return value in the variable$success
. (mail()
returnstrue
if it managed to send the email, orfalse
otherwise.) - Return an appropriate response to the browser
Once we’ve attempted to send the email, we send a “success” or “error” message back to the browser as appropriate. If the request URL contained an"ajax"
parameter then we know the form was submitted via Ajax using our JavaScript code, so we simply return the value"success"
or"error"
to the JavaScript, which will then display an appropriate message to the user. However, if the form was submitted without using Ajax then the user must have JavaScript turned off in their browser. In this situation, we display a more helpful error message in the browser, with instructions to the user to use their Back button to return to the page.Our JavaScript will add theajax
parameter to the URL when it submits the form, as you’ll see in Step 6.
Step 4: Include the jQuery library and set the delay
Our form is actually functional now. You can open the page in a browser, click the “Send us an email” link to jump to the form, fill in the fields, and submit the form to send the message.
However, we’re now going to enhance our form using JavaScript to make the experience nicer for the user.
We’ll use jQuery to do most of the heavy lifting, so the first step is to include the jQuery library in the page’s head
element:
1
|
< script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></ script > |
Here we’ve linked directly to the jQuery library on Google’s CDN, but you can download the library and host it on your own server if you prefer.
We’ll also add a global config variable, messageDelay
, to control how long the message boxes appear on the screen. This value is in milliseconds. Feel free to change it to a shorter or longer time:
1
2
3
|
<script type= "text/javascript" > var messageDelay = 2000; // How long to display status messages (in milliseconds) |
Step 5: Write the init()
function
The first stage of our form-enhancing JavaScript is the init()
function. This sets up the form so that it can be shown and hidden on demand, and also modifies the form so that it will be submitted using our JavaScript, rather than sent natively by the browser.
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
// Init the form once the document is ready $( init ); // Initialize the form function init() { // Hide the form initially. // Make submitForm() the form’s submit handler. // Position the form so it sits in the centre of the browser window. $( '#contactForm' ).hide().submit( submitForm ).addClass( 'positioned' ); // When the "Send us an email" link is clicked: // 1. Fade the content out // 2. Display the form // 3. Move focus to the first field // 4. Prevent the link being followed $( 'a[href="#contactForm"]' ).click( function () { $( '#content' ).fadeTo( 'slow' , .2 ); $( '#contactForm' ).fadeIn( 'slow' , function () { $( '#senderName' ).focus(); } ) return false ; } ); // When the "Cancel" button is clicked, close the form $( '#cancel' ).click( function () { $( '#contactForm' ).fadeOut(); $( '#content' ).fadeTo( 'slow' , 1 ); } ); // When the "Escape" key is pressed, close the form $( '#contactForm' ).keydown( function ( event ) { if ( event.which == 27 ) { $( '#contactForm' ).fadeOut(); $( '#content' ).fadeTo( 'slow' , 1 ); } } ); } |
Let’s look at each chunk of the above code:
- Init the form once the document is ready
We use the jQuery object,$
, to trigger ourinit()
function once the DOM is ready. - Hide the form, set the submit handler, and position the form
The first thing we do inside theinit()
function itself is make some changes to our form,#contactForm
.First we hide it from the page using the jQueryhide()
method. Then we set itssubmit
event handler to oursubmitForm()
function (which we’ll write in a moment). This ensures that, when the user submits the form,submitForm()
is called instead of the native browser form submission kicking in. Finally, we add thepositioned
CSS class to the form to reposition it in the centre of the browser window. - Make the “Send us an email” links open the form
Next we bind an anonymous event handler function to the “Send us an email” links’click
events. This function fades out the page content so it’s only just visible in the background; fades the contact form in; and sets the focus on the “Your Name” field, ready for the user to start filling in the form. Finally, the function returnsfalse
to prevent the links from being followed. - When the “Cancel” button is clicked, close the form
Now we bind another anonymous function to the “Cancel” button’sclick
event, so that the user can close the form by clicking the button. The function simply fades the form out, and fades the page content back in. - When the “Escape” key is pressed, close the form
Similarly we bind a function to the contact form’skeydown
event, so that we can read any key the user presses when they’re viewing the form. In this function, we check if the user has pressed the “Escape” key (character code: 27). If they have then we close the form by fading it out, and fading the content in.
Step 6: Write the submitForm()
function
We’ve now set up our form so that, rather than being submitted in the usual fashion, it will trigger the submitForm()
function when the user submits it. This function needs to do some validation and, if all is well, submit the form data to the PHP script via Ajax.
Here’s the function in full:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
// Submit the form via Ajax function submitForm() { var contactForm = $( this ); // Are all the fields filled in? if ( !$( '#senderName' ).val() || !$( '#senderEmail' ).val() || !$( '#message' ).val() ) { // No; display a warning message and return to the form $( '#incompleteMessage' ).fadeIn().delay(messageDelay).fadeOut(); contactForm.fadeOut().delay(messageDelay).fadeIn(); } else { // Yes; submit the form to the PHP script via Ajax $( '#sendingMessage' ).fadeIn(); contactForm.fadeOut(); $.ajax( { url: contactForm.attr( 'action' ) + "?ajax=true" , type: contactForm.attr( 'method' ), data: contactForm.serialize(), success: submitFinished } ); } // Prevent the default form submission occurring return false ; } |
Here’s how the function works:
- Store the contact form in a variable
Since we’ll be using it a lot throughout the function, we start off by storing the contact form element in acontactForm
variable. This element is available to our function as thethis
variable, since the function is the event handler for the element’ssubmit
event. We wrap the element in a jQuery object to make it easier to work with. - Check all the fields are filled in
Now we check that each field’s value is not empty by using the jQueryval()
method on each field. - Display a warning if the form isn’t completed
If 1 or more of the fields are empty, we fade out the form, then fade in the#incompleteMessage
div
, which contains the “Please complete all the fields…” message. We keep the message there for the time specified by themessageDelay
variable, then fade it out again. Once it’s faded out, we fade the form back in so that the user can complete it. - Submit the form if it is completed
Now we get to the meat of the JavaScript. If the form is completed then we first fade out the form, and fade in the “Sending your message…” box. Now we call the jQueryajax()
method to submit the form via Ajax to the PHP script. We pass the following arguments to the method:url
- The URL to send the form to. We grab this from the form’s
action
attribute, and append anajax=true
parameter to the query string so that our PHP script knows the form was sent via Ajax, rather than via the usual method. type
- The type of request to make (
"POST"
or"GET"
). We grab this from the form’smethod
attribute, which in this case is set to"POST"
. data
- The data to send with the request. For this, we call the jQuery
serialize()
method on the contact form object. This method takes all the field names and values in the form and encodes the data in a query string. We then pass this string to theajax()
method so it can send the data to the PHP script. success
- This is a callback function that will be called once the Ajax request has finished and the browser has received the response from the server. We set this to our
submitFinished()
function, which we’ll write in a moment.
- Prevent the default form submission occurring
Finally, our event handler returnsfalse
to prevent the form being submitted in the usual way.
Step 7: Write the submitFinished()
function
The last function we need to write is submitFinished()
, which is called once the Ajax response from the PHP script has been received by the browser. This function needs to check the response and display a success or error message as appropriate:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
// Handle the Ajax response function submitFinished( response ) { response = $.trim( response ); $( '#sendingMessage' ).fadeOut(); if ( response == "success" ) { // Form submitted successfully: // 1. Display the success message // 2. Clear the form fields // 3. Fade the content back in $( '#successMessage' ).fadeIn().delay(messageDelay).fadeOut(); $( '#senderName' ).val( "" ); $( '#senderEmail' ).val( "" ); $( '#message' ).val( "" ); $( '#content' ).delay(messageDelay+500).fadeTo( 'slow' , 1 ); } else { // Form submission failed: Display the failure message, // then redisplay the form $( '#failureMessage' ).fadeIn().delay(messageDelay).fadeOut(); $( '#contactForm' ).delay(messageDelay+500).fadeIn(); } } </script> |
The function works as follows:
- Get the response
jQuery passes the response from the PHP script as an argument to thesubmitFinished()
function. We take this string and pass it through the jQuerytrim()
method to remove any whitespace. - Fade out the “sending” message
Next we fade out the “Sending your message…” box by calling the jQueryfadeOut()
method. - If email was sent successfully, display a success message
If theresponse
variable holds the string"success"
, as returned by our PHP script, then we know that the email was successfully queued for delivery. So we fade in the success message, hold it for a couple of seconds, then fade it out. We also reset the form fields to empty values, in case the user wants to send another message. Finally, once the success message has faded out, we fade the page content back in. - If there was a problem, display a failure message
If the PHP script returned anything other than"success"
then we know there was a problem with the submission, so we display the failure message stored in the#failureMessage
div
, then fade the form back in so that the user can correct any problems with the form.
And that’s the end of our JavaScript!
Summary
We’ve now built our slick Ajax contact form. Not only does it look good, but it’s easy to use, and the visitor can send an email without ever having to leave the page they are reading. Nice!
Related articles
- AjaxQ jQuery Plugin – A Tiny, Simple jQuery Plugin For Sequential Ajax Requests (functionn.blogspot.com)
- jQuery Roundup: Joconut, jQuery Table Sort, jQuery.pushevent (dailyjs.com)
- useful php,jquery scripts (bput4all.wordpress.com)
50 Essential PHP Tutorial and Examples for Beginners
In addition, PHP is one of the most popular server running side scripting languages today. It is used to create dynamic web pages that interact with the user offering customized information. PHP offers many advantages: it is fast, stable, secure, easy to use and open source (free).
Web applications have been improving user experience thanks to a lot of recently developed new technology such jQuery, CSS3, HTML5. The new feature improvement was create to fix all the design solutions. You can create php project easy with CSS3, HTML5 and jQuery. Recently, responsive design platform layout was a useful part for web designer to learn more.
You may interested with php tutorials with examples bellow:
XML to Array in php Function
function xml2array($contents, $get_attributes=1, $priority = ‘tag‘) {
if(!$contents) return array();
if(!function_exists(‘xml_parser_create’)) {
//print “‘xml_parser_create()’ function not found!”;
return array();
}//Get the XML parser of PHP – PHP must have this module for the parser to work
$parser = xml_parser_create(”);
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, “UTF-8“); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);if(!$xml_values) return;//Hmm…
//Initializations
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();$current = &$xml_array; //Refference
//Go through the tags.
$repeated_tag_index = array();//Multiple tags with same name will be turned into an array
foreach($xml_values as $data) {
unset($attributes,$value);//Remove existing values, or there will be trouble//This command will extract these variables into the foreach scope
// tag(string), type(string), level(int), attributes(array).
extract($data);//We could use the array by itself, but this cooler.$result = array();
$attributes_data = array();if(isset($value)) {
if($priority == ‘tag’) $result = $value;
else $result[‘value’] = $value; //Put the value in a assoc array if we are in the ‘Attribute‘ mode
}//Set the attributes too.
if(isset($attributes) and $get_attributes) {
foreach($attributes as $attr => $val) {
if($priority == ‘tag’) $attributes_data[$attr] = $val;
else $result[‘attr’][$attr] = $val; //Set all the attributes in a array called ‘attr’
}
}//See tag status and do the needed.
if($type == “open”) {//The starting of the tag ‘<tag>’
$parent[$level-1] = &$current;
if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
$current[$tag] = $result;
if($attributes_data) $current[$tag. ‘_attr’] = $attributes_data;
$repeated_tag_index[$tag.’_’.$level] = 1;$current = &$current[$tag];
} else { //There was another element with the same tag name
if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
$current[$tag][$repeated_tag_index[$tag.’_’.$level]] = $result;
$repeated_tag_index[$tag.’_’.$level]++;
} else {//This section will make the value an array if multiple tags with the same name appear together
$current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
$repeated_tag_index[$tag.’_’.$level] = 2;if(isset($current[$tag.’_attr’])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag][‘0_attr’] = $current[$tag.’_attr’];
unset($current[$tag.’_attr’]);
}}
$last_item_index = $repeated_tag_index[$tag.’_’.$level]-1;
$current = &$current[$tag][$last_item_index];
}} elseif($type == “complete”) { //Tags that ends in 1 line ”
//See if the key is already taken.
if(!isset($current[$tag])) { //New Key
$current[$tag] = $result;
$repeated_tag_index[$tag.’_’.$level] = 1;
if($priority == ‘tag’ and $attributes_data) $current[$tag. ‘_attr’] = $attributes_data;} else { //If taken, put all things inside a list(array)
if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array…// …push the new element into that array.
$current[$tag][$repeated_tag_index[$tag.’_’.$level]] = $result;if($priority == ‘tag’ and $get_attributes and $attributes_data) {
$current[$tag][$repeated_tag_index[$tag.’_’.$level] . ‘_attr’] = $attributes_data;
}
$repeated_tag_index[$tag.’_’.$level]++;} else { //If it is not an array…
$current[$tag] = array($current[$tag],$result); //…Make it an array using using the existing value and the new value
$repeated_tag_index[$tag.’_’.$level] = 1;
if($priority == ‘tag’ and $get_attributes) {
if(isset($current[$tag.’_attr’])) { //The attribute of the last(0th) tag must be moved as well$current[$tag][‘0_attr’] = $current[$tag.’_attr’];
unset($current[$tag.’_attr’]);
}if($attributes_data) {
$current[$tag][$repeated_tag_index[$tag.’_’.$level] . ‘_attr’] = $attributes_data;
}
}
$repeated_tag_index[$tag.’_’.$level]++; //0 and 1 index is already taken
}
}} elseif($type == ‘close’) { //End of tag ”
$current = &$parent[$level-1];
}
}return($xml_array);
}
DownloadUrlContent from other site using Curl Method
function DownloadUrlContent($Url,$fields=array(”)){
if (!function_exists(‘curl_init’)){
die(‘CURL is not installed!’);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_REFERER, “http://www.google.com/”);
curl_setopt($ch, CURLOPT_USERAGENT,’Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18′);
curl_setopt($ch, CURLOPT_HTTPHEADER,array(‘Expect:’));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
if(count($fields)>0){
foreach($fields as $key=>$value) { @$fields_string .= trim($key).’=’.trim($value).’&’; }rtrim(trim($fields_string),’&’);
$fields_string = substr($fields_string,0,strlen($fields_string)-1);curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
}
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
Related articles
- Lets begin curl scripting (ravidhavlesha.wordpress.com)
- Facebook like fetch url data using PHP Curl, Jquery and Ajax (itzurkarthi.com)
- Creating Custom Widgets for dashEE (christophermonnat.com)
- Intelligent (Pharma) Spam Decoded (sucuri.net)
- cURL how to make program continue after failing to connect to certain host (stackoverflow.com)
Calculate image aspect ratio in PHP
Calculating image aspect ratio in PHP is very simple. First you need to find greatest common divisor(GCD). You can do that by using following function:
function GCD($a, $b) {
while ($b != 0)
$remainder = $a % $b;
$a = $b;
$b = $remainder;
}
return abs ($a);
}
If you compiled your PHP version with GMP functions, you can also use following:
$gcd = gmp_gcd($a, $b);
After finding GCD, simply divide both sides with it:
$a = 2048; // screen width
$b = 1152; // screen height
$gcd = GCD($a, $b);
$a = $a/$gcd;
$b = $b/$gcd;
$ratio = $a . “:” . $b;
Recent Comments