Sending emails in PHP & email injection attacks

Posted by Muhammad Shiraz Kamboh Sunday, 27 May 2012 0 comments

PHP’s inbuilt mail() function provides very limited mail functionality. Although its easy to send text emails, but thats pretty much the only thing you can do with it. If you need extended functionality like HTML emails or attachments, you can always go through a couple of hundred pages of mail specifications at IETF .
Or you can stop trying to reinvent the wheel and use existing PHP mail libraries. Two such excellent libraries are:
  1. PHPMailer
  2. Swift Mailer
PHPMailer has been around for a long time is definitely more popular and well known but its development seems to have petered out. There has been no new releases since July 2005.
Swift Mailer on the other hand is relatively new and is more actively developed. Both websites have enough documentation and examples to get you started.
PHPMailer offers no protection against header injections. I wasn’t sure about the Swift Mailer since I don’t have much experience with it. So I put the question to Chris Corbyn, Swift Mailer’s developer. Below is his response:
Characters outside the 7-bit printable ASCII range are encoded into a 7-bit format making them incapable of affecting the header structure.
So I guess that this another reason for choosing Swift Mailer.

Email injection or mail form spamming

Spammers can hijack your seemingly innocuous looking mail form to send out spam. They do so by posting specially formatted data to your mail script. This is known as email injection or mail form spamming.
Below is the PHP code to send a simple HTML email using the mail() function.
$to = 'recipient@somedomain.xxx';
$from = 'sender@anotherdomain.xxx';
$fromname = 'Dilbert';
$subject = 'HTML Email';
$headers = "Date: ".date('r')."\n";
$headers .= "Return-Path: ".$from."\n";
$headers .= "From: ".$fromname."\n";
$headers .= "Message-ID: <".md5(uniqid(time()))."@anotherdomain.xxx>\n";
$headers .= "X-Priority: 3\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$headers .= 'Content-Type: text/html; charset="iso-8859-1"'."\n";
$body ='

HTML Email Body

';
mail($to, $subject, $body, $headers);
If the you run the above script (after substituting the recipient and sender email addresses) you will receive a HTML email in your inbox. Everything fine so far. Now change the value of the $from variable to the following:
$from = "sender@anotherdomain.xxx
Cc:victim@domain2.xxx";
Run the script again and you will see that two emails are sent out this time. One to the recipient@somedomain.xxx and the second to victim@domain2.xxx . This is a simplified version of mail header injection attack but the basic methodology is the same. The spammers will try to inject headers into your mail script using newlines and carriage returns.
Most often than not, variables like $from and $subject are populated by data received from a form, thus leaving the door open for possible mail injection attacks. The least you should do is to strip newlines (\n) and carriage returns (\r).

Protection against email injections and mail form spamming

As mentioned earlier, you can prevent email header injections by removing the newlines and carriage returns from the incoming data. You can use the below two functions to protect your script.
Both the functions are essentially the same. The only difference is in their usage. The first function will replace the newlines and carriage returns. The second function is a validation function which returns true if it finds newlines or carriage returns in the passed string.
function heal($str) {
 $injections = array('/(\n+)/i',
 '/(\r+)/i',
 '/(\t+)/i',
 '/(%0A+)/i',
 '/(%0D+)/i',
 '/(%08+)/i',
 '/(%09+)/i'
 );
 $str= preg_replace($injections,'',$str);
 return $str;
}
function isInjected($str) {
 $injections = array('(\n+)',
 '(\r+)',
 '(\t+)',
 '(%0A+)',
 '(%0D+)',
 '(%08+)',
 '(%09+)'
 );
 $inject = join('|', $injections);
 $inject = "/$inject/i";
 if(preg_match($inject,$str)) {
  return true;
 }
 else {
  return false;
 }
}
You can use the second function to display an error to the spammer. But it would be better to send a “403 Forbidden” or “404 Page Not Found” headers rather than to display an insulting message. The spammer just might decide to take you on your challenge.

PHP MySQL Basics Tutorial

Posted by Muhammad Shiraz Kamboh 0 comments

PHP and MySql are the most common and popular combination you would come across on the Internet. Affordable Linux hosting, open source nature of these two technologies and the freedom from expensive proprietary licenses are the main reasons for the success of this combination.

Connecting to MySQL through PHP

To connect to a mysql database server, use the following function:



$link = mysql_connect($hostname, $username, $password, $newlink);
A call to mysql_connect returns a link identifier on success or FALSE on failure. Lets go through the arguments one at a time:
$hostname = The domain name of the mysql server. If both the web server and mysql are located on the same machine/computer, you can simply use “localhost”.
$username = Login ID/username of the mysql server
$password = Password for the mysql server
The fourth argument ($newlink) is not used very often and you can skip it in most cases. mysql_connect either opens a new connection to the mysql server or uses an existing connection. Calling mysql_connect multiple times will return the same connection or link identifier which was created by the previous call.



$link1 = mysql_connect("localhost", "user1", "secret");
$link2 = mysql_connect("localhost", "user1", "secret");
$link3 = mysql_connect("localhost", "user1", "secret");
//The three calls to mysql_connect above will return a link identifier to the same connection

$link4 = mysql_connect("localhost", "user2", "secret");
//A new connection will be returned since we have changed the username in the argume
In the above example, the second and third calls to mysql_connect will return the same connection which was created in the first call. No new connections will be established. This is as long as the same arguments are used in all the three calls. You can force the mysql_connect to create a new connection by setting the value of $newlink argument as TRUE.

Selecting Database

Now that we have a link identifier or connection to the mysql server, we need to “select” a database. A mysql server on a typical shared hosting server may have dozens or even hundreds of databases. So we need to select or specify a database against which we want to run our queries.



//Open a connection to the mysql server
$link = mysql_connect('localhost', 'user', 'secret');
if(!$link) {
 print('Failed to establish connection to mysql server!');
 exit();
}

//Select the database
$status = mysql_select_db('mydatabase');

Running Queries

We have connected to the database server and selected our database. Now we are ready to run queries using mysql_query function. See the example below:



//Open a connection to the mysql server
$link = mysql_connect("localhost", "user1", "secret");
if(!$link) {
 print("Failed to establish connection to mysql server!");
 exit();
}

//Select the database
$status = mysql_select_db("mydatabase");

//Run query
$query = "SELECT first_name,last_name FROM customers WHERE cust_id=23";
$rs = mysql_query($query);
if(!$rs) {
 print("Query Error: ".mysql_error());
}
$numrows = mysql_num_rows($rs);
print("Number of rows returned: $numrows");
mysql_query will return a result set on success and FALSE on error. This is true for “SELECT”, “SHOW”, “DESCRIBE”, and “EXPLAIN” queries. For other types of queries, it will return TRUE on success and FALSE on error.
Therefore in our example above, we will either get a result set or FALSE. Even if there is no customer with a cust_id of 23, we will still get a result set. You can check the number of rows returned by our query using mysql_num_rows function. Please note, mysql_num_rows is only meaningful for SELECT queries.

Using the result set

There are a number functions available which we can use to retrieve our values from the result set. If we know for sure that only a single row will be returned by the query, we can use the code below:



$query = "SELECT first_name,last_name FROM customers WHERE cust_id=23";
$rs = mysql_query($query);
if(!$rs) {
 print("Query Error: ".mysql_error());
}

//Number of rows reqturned by the query
$numrows = mysql_num_rows($rs);
print("Number of rows returned: $numrows");

//Fetch result set as an associative array
$customer = mysql_fetch_assoc($rs);
print($customer['first_name']);
print($customer['last_name']);
mysql_fetch_assoc returns an associative array. The column names correspond to the keys of this array and column values correspond to array values. In our example above, mysql_fetch_assoc will return an array similar to:



$customer['first_name'] = 'Jatinder';
$customer['last_name'] = 'Thind';
Other functions of interest while dealing with mysql databases are :
  1. mysql_unbuffered_query – This uses less memory than mysql_query. The downside is that you can not use mysql_num_rows if you use mysql_unbuffered_query
  2. mysql_real_escape_string – Escapes the special characters. Only available on PHP-4.3.0 and above
  3. addslashes – Similar to mysql_real_escape_string above. This is available in all PHP versions.
  4. mysql_error – Returns the error text from the previously called mysql function.

Submitting forms using PHP cURL

Posted by Muhammad Shiraz Kamboh 0 comments
In the previous article, we covered the PHP cURL basics. Specifically, we learned how to connect to a remote URL and retrieve the URL’s contents. In this article we will learn how to simulate form submission using PHP cURL.




To submit forms using cURL, we need to follow the below steps:
  1. Prepare the data to be posted
  2. Connect to the remote URL
  3. Post (submit) the data
  4. Fetch response and display it to the user
You may want to download the script used in this tutorial before starting.

Prepare data to be posted

Form data is essentially sent as name value pairs in the format “field1=field1_value&field2=field2_value&field3=field3_value”.
field1, field 2 etc. refer to the form fields and the field1_value, field2_value etc. refer to values of these fields. For our example we will assume that the data we want to post to the remote URL is contained in an associative array like so:
$data = array(); $data['first_name'] = 'Jatinder'; $data['last_name'] = 'Thind'; $data['password'] = 'secret'; $data['email'] = 'me@abc.com'; 
When a browser submits the form, it automatically urlencodes the data before sending it off. Similarly we will need to urlencode all data before posting it through cURL. You can find more about urlencode here.
 $post_str = ‘’; foreach($data as $key=>$val) { $post_str .= $key.’=’.urlencode($val).’&’; } $post_str = substr($post_str, 0, -1); 
The above code will leave us with string “first_name=Jatinder&last_name=Thind&password=secret&email=me%40abc.com” which can now be sent to the remote URL through cURL.

Connect to the remote URL

We have already covered this in the previous PHP cURL tutorial. Here is the code again in a nutshell.
 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ‘http://example.com/form-handler.php’ ); 

Post (submit) the form data

First we instruct cURL to a regular HTTP POST.
 curl_setopt($ch, CURLOPT_POST, TRUE); 
Next we tell cURL which data to send in the HTTP POST.
 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str); 

Execute request and fetch the response

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); curl_close($ch); echo $result; 
The above code snippet executes the cURL request, fetches the response of the form handler script and displays it to the user.
You can download the complete source code for the above PHP cURL tutorial here.

Facebook Funny Status

Posted by Muhammad Shiraz Kamboh 0 comments
Your Name: feels like getting some work done...and so he is sitting down until the feeling passes.


Your Name: used to play sports. Then she realized you can buy trophies. Now she's good at everything.


Your Name: is color blind and trying to solve a rubiks cube... This could take a while...


Your Name: dreams of a better world...where chickens can cross the road without having their motives questioned :0)


Your Name: says my computer just beat me at chess...but it was no match for me at kick boxing.


Your Name: is cle'a]ni.ng he'r ke]yb29oa;rd


Your Name: is wondering why his daughter's diaper holds no where near the 22-37 pounds it promises.


Your Name: is proud of herself. She finished a jigsaw puzzle in 6 months and the box said 2-4 years.


Your Name: doesn't suffer from insanity... he enjoys every minute of it.


Your Name: ║▌║█║▌║▌││║▌║█║▌│║▌║█║▌║▌││║▌║ *ZAP* *BEEP* Price: $7.95


Your Name: is wondering where noah kept woodpeckers on his ark


Your Name: thinks that if your relationship status says, "It's complicated" that you should stop kidding yourself and change it to "Single"


Your Name: before you use the bathroom in someones house make sure you check they have toilet paper!!


Your Name: Whoever says Paper beats Rock is an idiot. Next time I see someone say that I will throw a rock at them while they hold up a sheet of paper


Your Name: "Good morning...I see the assassins have failed."


Your Name: is cleaning out his medicine cabinet of expired prescriptions with a glass of water and several mystery pills at a time.


Your Name: Be nice to nerds, Chances are you will be working for them.


Your Name: is normally not a praying man, but if you're up there, please save me Superman.


Your Name: is experiencing life at a rate of several wtf's a minute


Your Name: just received a coupon in the mail: Buy one sock, get one FREE! While socks last.


Your Name: would rather check her facebook than face her checkbook.


Your Name: believes that if you tell your boss what you really think of him, the truth will set you free.


Your Name: ¡??i? ???s ??? ?? ?ooq???? ?sn pu? pu??spu?? ? op ????ui? u??


Your Name: Got out of jury duty by prefacing every answer with "according to the prophecy"


Your Name: is Loading ¦¦¦¦¦¦¦¦¦¦¦¦ 99%


Your Name: People reckon I'm too patronising (that means I treat them as if they're stupid).


Your Name: Have you ever had a fly or small bug land on your computer screen and your first reaction is to try and scare it with the cursor?


Your Name: I have an oven with a 'stop time' button. It's probably meant to be 'stop timer' but I don't touch it, just in case.


Your Name: It recently became apparent to me that the letters 'T' and 'G' are far too close together on a keyboard. This is why I'll never be ending an e-mail with the phrase "Regards" ever again.


Your Name: How To Be A Hero tip: When destroying the enemy be sure to kill all the criminals in reverse order of importance before confronting the kingpin himself.


Your Name: went to the book store earlier to buy a 'Where's Wally' book. When I got there, I couldn't find the book anywhere. Well played Wally, well played.


Your Name: Don't waste money on expensive ipods. Simply think of your favourite tune and hum it. If you want to "switch tracks", think of another song you like and hum that instead.
Your Name: What do we want? PROCRASTINATION! When do we want it?... Next week.


Your Name: My wife said I'm too immature and if I don't grow up it's going to erect a barrier between us. Ha ha ha, erect.


Your Name: Statistically, 6 out of 7 dwarfs aren't happy.


Your Name: Hi, my name is Damimeve. The 'mime' is silent.


Your Name: got her test results back this morning and is shocked to find that she's been diagnosed with OCD. She's rung the doctors nine times to check if they're correct.


Your Name: reckons anti-wrinkle cream doesn't work. If it did, women wouldn't have any fingerprints.
Your Name: will one day get even... with all the people that have helped her.


Your Name: Do you know what really makes me smile? Facial muscles.


Your Name: People who live in stone houses shouldn't throw glasses.


Your Name: Statistically, 132% of all people exaggerate.


Your Name: Statistically 5/4 of people have trouble with fractions.


Your Name: I hear there is scientific proof that birthdays are good for you... the more you have the longer you live.


Your Name: I just read a list of 'the 100 things to do before you die'. I'm pretty surprised 'yell for help' wasn't one of them...


Your Name: I've always wondered if film directors wake up screaming "CUT! CUT! CUUUUUT!" when they have nightmares.


Your Name: TEIAM - problem solved


Your Name: never questions authority, he annoys authority. More effect, less effort.


Your Name: never judges a book by its cover. She uses the paragraph on the back, it tells you what the story is about.


Your Name: Top Tip Of The Week: When going through airport customs and you are asked "do you have any firearms with you?" do not reply "what do you need?"

Delete Your Facebook Account Forever

Posted by Muhammad Shiraz Kamboh 0 comments

Whether you're trying to get a job and worried about snoopy new bosses, sick of maintaining a virtual profile constantly bombarded with increasingly useless updates and pings from people that you decreasingly actually know, fed up with Facebook's attitude towards their users, disgusted with your addiction to it, or just want you, your personal details and habits, and photos, out, deleting your Facebook profile can be done in a few easy steps:
1. Just go here
2. Hit submit. (See, even in parting Facebook demands your obedience)
3. Follow the instructions. You will see the following screens:




permadel.jpg



4. Put in your password and enter the words from the security check.

permadel2.jpg

5. Hit okay.


permadel3.jpg



6. You then get bumped to the Facebook login screen.
7. Look outside! It's a beautiful day. Go enjoy it. Perhaps call up a friend you haven't seen in a while and catch up on each other's lives over coffee.
Your account is then "deactivated" for two weeks. Don't login for those two weeks and then it will be permanently deleted.
Facebook sometimes changes the procedures for exiting the social networking service, but the Facebook group "How to permanently delete your facebook account" should have the most up to date method if the link above goes dead.

Beautiful Status Decorations

Posted by Muhammad Shiraz Kamboh 0 comments


▂ ▃ ▅ ▆ █ Your Status Here █ ▆ ▅ ▃ ▂
★·.·´¯`·.·★[Your Status Here] ★·.·´¯`·.·★
..♩.¸¸♬´¯`♬.¸¸¤ Your Status Here o ¤¸¸.♬´¯`♬¸¸.♩..
¤♥¤Oº°‘¨☜♥☞¤[Your Status Here] ¤☜♥☞¨‘°ºO¤♥¤
♬ •♩ ·.·´¯`·.·♭•♪ Your Status Here e ♪ •♭·.·´¯`·.·♩ •♬
»------(¯` Your Status Here ´¯)------»
¸.·'★¸.·'★*·~-.¸-(★[Your Status Here] ★)-,.-~*¸.·'★¸.·'★
•(♥).•*´¨`*•♥•(★) Your Status Here (★)•♥•*´¨`*•.(♥)•
O.o°<*)>>>=[Your Status Here] =<<<(*>°o.O
<<..•.¸¸•´¯`•.¸¸¤Your Status Here ¤¸¸.•´¯`•¸¸.•..>>
신◈기◈今天◈(★)[Your Status Here] o (★)◈동방◈기◈天
-漫~*'¨¯¨'*·舞~ Your Status Here o ~舞*'¨¯¨'*·~漫-
•☆.•*´¨`*••♥ Your Status Here ♥••*´¨`*•.☆•
•♥•♥•♥•♥ ☜[Your Status Here] ☞ ♥•♥•♥•♥•♥•
«-•·.·´¯`·.·•雪[Your Status Here] 雪•·.·´¯`·.·•-»
╰☆╮¤°.¸¸.·´¯`»® Your Status Here ®«´¯`·.¸¸.°¤╰☆╮
♥ⓛⓞⓥⓔ♥☜ [Your Status Here] ☞♥ⓛⓞⓥⓔ♥
●☆● ☆● ☆● ☆● Your Status Here ●☆● ☆● ☆● ☆●
◢♂◣◥♀◤[Your Status Here] ◢♂◣◥♀◤
๑۞๑,¸¸,ø¤º°`°๑۩ Your Status Here ۩๑ ,¸¸,ø¤º°`°๑۞๑
.•°¤*(¯`★´¯)*¤° [Your Status Here] °¤*(¯`★´¯)*¤°
..•.¸¸•´¯`•.¸¸.ஐ [Your Status Here] ஐ..•.¸¸•´¯`•.¸¸.
(¯`•.ゃ_ゃ.• Your Status Here •.ゃ_ゃ.•´¯)
¸.•♥•.¸¸.•♥• [Your Status Here] •♥•.¸¸.•♥•.¸
ஐ¤*¨¨*¤¨°o.O( Your Status Here )O.o°¤*¨¨*¤εïз
-~*'¨¯¨'*·~㊅[Your Status Here] ㊅~*'¨¯¨'*·~-
☆,.-~*'¨¯¨'*·~-.¸-(★ Your Status Here ★)-,.-~*'¨¯¨'*·~-.¸☆
☜♥☞ º°”˜`”°º☜( Your Status Here )☞ º°”˜`”°☜♥☞
(¯`'·.¸(♥)¸.·'´¯)[Your Status Here] (¯`'·.¸(♥)¸.·'´¯)
(¯`·._)♣ ♤ ♥♠(Your Status Here )♣ ♤ ♥♠(¯`·._)
((((¯♀'·.¸(★) Your Status Here (★)¸.·'♂ ´¯))))
<º))))><.•´¯`•.( Your Status Here )¸.•´¯`•.¸><((((º>
- -¤--^]([Your Status Here] )[^--¤- -
~²ººº~([Your Status Here] )~²ººº~
._|.<(+_+)>.|_.(Your Status Here )._|.<(+_+)>.|_.
• ••^v´¯`×)(Your Status Here )(×´¯`v^•• •
,.-~*'¨¯¨'*•~-.¸-(_( Your Status Here )_)-,.-~*'¨¯¨'*•~-.¸
- - --^[Your Status Here]^-- - -
••.•´¯`•.••([Your Status Here] ) ••.•´¯`•.••
`•.¸¸.•´´¯`••._.•( Your Status Here )•.¸¸.•´´¯`••._.•
(¯`•._)([Your Status Here] )(¯`•._)
¯¨'*•~-.¸¸,.-~*'( Your Status Here )¯¨'*•~-.¸¸,.-~*'
(¯`•._.•[Your Status Here]•._.•´¯)
¨°o.O([Your Status Here] )O.o°
×÷•.•´¯`•)»( Your Status Here )«(•´¯`•.•÷×
Oº°‘¨([Your Status Here] )¨‘°ºO
׺°”˜`”°º×( [Your Status Here] )׺°”˜`”°º×
.•´¯`•->( Your Status Here )<-•´¯`•. .. |..<(+_([Your Status Here] )_+>..|..
-•=»‡«=•-([Your Status Here] )-•=»‡«=•-
•°o.O(Your Status Heres )O.o°•
––––•(-•([Your Status Here] )•-)•––––
(¯`•¸•´¯)(Your Status Here )(¯`•¸•´¯)
••¤(`×[¤([Your Status Here] )¤]×´)¤••
»-(¯`v´¯)-»( [Your Status Here] )»-(¯`v´¯)-»
°l||l°([Your Status Here] )°l||l°
•°¤*(¯`°(☺)(( Your Status Here ))(☺)°´¯)*¤°•
—¤÷(`[¤*([Your Status Here] )*¤]´)÷¤—
¸.´)(`•[Your Status Here]•´)(` .¸
•÷±‡±( Your Status Here )±‡±÷
+*¨^¨*+([Your Status Here] )+*¨^¨*+
—(••÷[( Your Status Here )]÷••)—
•ï¡÷¡ï•( Your Status Here )•ï¡÷¡ï•
•!¦[•(Your Status Heres )•]¦!•
°º¤ø,¸¸,ø¤º°`°º¤ø,¸( Your Status Here )°º¤ø,¸¸,ø¤º°`°º¤ø,¸
,-*'^'~*-.,_,.-*~ Your Status Here ~*-.,_,.-*~'^'*-,
.•¯(_.•¯(_.•¯(_[Your Status Here] )¯`•._)¯`•._)¯`•.
©º°°º©©º°°º© Your Status Here ©º°°º©©º°°º©
||¯|_|¯|_([Your Status Here] )_|¯|_|¯||

It’s Time to Create a ‘Neo-Constructivist’ Poster with Photoshop

Posted by Muhammad Shiraz Kamboh 0 comments




Step 1

Open Photoshop and create a new document 1200px width by 1600px height, with an RGB color, and 72dpi. Then go to Create a new fill or adjustment layer in the Layers palette, select the Gradient Option and set the colors from #7D0000 to #480000. Set the angle value to 17 – 20º and hit OK.

 

Popular Posts

About Me

My photo
I create this Blog for learn the all kind of tutorial about web developing | HTML, Java, PHP, Graphic designing, Corel Draw, Photoshop, Micromedia Flash, Swish and many more related software and internet programming tutorials.

Followers

Blog Archive