Saturday, July 28, 2012

Advanced PHP session start

If a session based web application is used by a visitor using Internet Explorer it's possible that this user get some trouble. This will happen if parts of the application are accessed for example via a shortcut on the desktop and the application opens then in a new Explorer window. At this moment a second session is started with a different ID, if the used web application has some session based authentication system the user has to login again. At the same time the user has to logout twice! In browsers like Mozilla Firefox new windows are treated the same way then tabs where the problem doesn't exists. This function will use a real cookie for the session ID and updates the expiration time with every script execution. The expiration is equal to the PHP directive "gc_maxlifetime" (default) or every custom value.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

// $expire = the time in seconds until a session have to expire
function start_session($expire = 0) {
    if ($expire == 0) {
        $expire = ini_get("session.gc_maxlifetime");
    } else {
        ini_set("session.gc_maxlifetime", $expire);
    }
    if (empty($_COOKIE['PHPSESSID'])) {
        session_set_cookie_params($expire);
        session_start();
    } else {
        session_start();
        setcookie("PHPSESSID", session_id(), time() + $expire);
    }
}
// this example will start a session with an expire time given by the php configuration
start_session();
// start_session(600) will start a session which will expire after 10 minutes (60*10 seconds)
?>



Friday, July 27, 2012

Five Steps to Secure your PHP Website


Unfortunately there will always be some one out there on the world wide web who will attempt to break any thing they can find on the Internet so you owe it to your visitors/ members to ensure nothing malicious is being hidden on your site and there info isn't being stolen. In this article i will cover 5 important steps you need to take to make sure your web site's secure.

MySQL Injection

Every single piece of user inputted data should be treated as if it was an attack on your script. When running MySQL queries if you don't treat user inputted data before using it in the query a hacker could cause you a number of problems, for example.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$sql = mysql_query("SELECT FROM users WHERE username = '". $_POST["username"] ."' && password = '". $_POST["password"] ."');


?>

Lets say you were using this code to allow users to login, What if instead of a user entering a password they entered ' OR username = 'admin then the query would look like this.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$sql = mysql_query("SELECT FROM users WHERE username = '' && password = '' OR username = 'admin'");


?>

They would now be logged in as the admin and gain access to all your administrative tools. Using this method of exploitation hackers would also be able to delete records, force errors and all sorts. So to prevent this we use a php function called mysql_real_escape_string, so before using this user inputted data in our query we would simply do this.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$username = mysql_real_escape_string( $_POST["username"] );
$password = mysql_real_escape_string( $_POST["password"] );

$sql = mysql_query("SELECT FROM users WHERE username = '". $username ."' && password = '". $password .'");


?>

mysql_real_escape_string is a MySQL function which prepends backslashes to the following characters x00, n, r, , ', " and x1a.

CSRF Attacks

CSRF pronounced sea-surf is an abbreviation of "Cross Site Request Forgery". The basic principal behind CSRF attacks is instead of gaining access to a site's control's forcing actions on a user, for example.

 pages.php
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

echo '
';


?>

 delete.php
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

if( logged_in() == false ) {
 // User not logged in
 die();
}
// User logged in
$page_id = mysql_real_escape_string( $_GET["page_id"] );
$query = mysql_query("DELETE FROM pages WHERE page_id = '". $page_id ."'");


?>

Lets say this was part of your script and you as an admin used it to delete pages, Now obviously if a hacker were to visit this page they wouldn't be able to do any thing because we have a check at the very top to see if the user is logged in or not. But if you were logged in and then some one told you to visit a web page and on that page was an image like this.


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/




?>

You would have just deleted what ever page had the id "20" to fix this issue its very simple all you need to do is use tokens so on pages.php you would generate a unique id and set it as a session and then you would check for that id on delete.php if they don't match then kill the script.


pages.php
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

session_start();
$id = md5(uniqid(mt_rand(), true));
$_SESSION["token"] = $id;
echo '
';


?>
delete.php
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

if( logged_in() == false ) {
 // User not logged in
 die();
}
// User logged in
$page_id = mysql_real_escape_string( $_GET["page_id"] );
$token = mysql_real_escape_string( $_GET["token"] );
if( $_GET["token"] != $_SESSION["token"] ) {
 die();
}
$query = mysql_query("DELETE FROM pages WHERE page_id = '". $page_id ."'");


?>

Using this simple solution we can prevent CSRF attacks and prevent a number of security issues.


XSS Attacks

XSS (Cross site scripting) can cause web site's huge problems. The general idea of XSS is embedding code on your web site without you know which will cause your visitors to download something they don't want to. For example if you had a comment system on your web site and no checks were run on comments being posted any one could come along and make a comment like this.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


What a wonderful news entry


?>

Now all you would see is "What a wonderful news entry" but that comment could be doing all sorts such as collecting cookie information off your visitors, downloading viruses onto their computers and so on. Luckily we have a simple fix for this, When you are about to save the comment in your database you should of course escape the comment text to prevent mysql injections but also you should use htmlspecialchars this will stop any bad code making it into your comments or other user posted data by changing characters such as < into their html codes e.g <.

Script functionality

This may be pretty obvious but i've seen a number of web site's that function poorly thus making there service less secure for their users. For example a user should not be able to attempt to login hundreds of times if they keep getting there password wrong, After about 5 attempts they should be frozen out for about 15 mins. If you are building a "forgot your password" facility into your script then by entering there username, email address and date of birth they should not be able to recover their password to another email address. You should also force people to enter a captcha when they are leaving a comment or post on your web site to make sure you don't have problems with bots and if they are posting any thing on your site they should have to wait at least 30 seconds between posts to stop people trying to crash your site by getting a bot to submit thousands of comments at once.

Error reporting

If there is an issue with your web site, The last person in the world you want knowing about it is a potential hacker because there is a chance that error could lead them to a way to exploit your script. So make sure that any script you put live you turn error reporting off.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

error_reporting(0);


?>

Now if your script throws any sort of error at you it will not be seen by your users.

I hope this tutorial has helped you understand some of the vital measures that must be taken to stop hackers ripping your web sites to pieces.
  



Friday, July 20, 2012

Find visitor's IP address in php script

Every php developer want to store IP address of visitor for tracking and other different purpose. Here is the function which i'm using in my script to store ip address in database.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
function visitorIPAdd()
{
/*
This returns the IP of the visitor calling the requested page
Checks to see if HTTP_X_FORWARDED_FOR has a value then the client is operating via a proxy
*/
       $visitorIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
       if($visitorIP == "")
      { 
         $visitorIP = $_SERVER['REMOTE_ADDR'];  
      }

      return $visitorIP;       // return the IP address
}
?>

Saturday, July 14, 2012

Remove HTML Tags from string in PHP

If your strings have any html code, you can easily remove using following code.

Using regular expression:

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$string = preg_replace("/<.*?>/", "", $string_contain_html_code);


?>

Stop SQL Injection in MYSQL with PHP Script


Every PHP-MYSQL programmer need to know Anti-SQL Injection. Please take a look at very simple function which can save your database!!

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


function ClearInput($dirtyInput){
 
 if (get_magic_quotes_gpc()) {
 
 $clean = mysql_real_escape_string(stripslashes($dirtyInput));
 
 }else{
 
 $clean = mysql_real_escape_string($dirtyInput);
 
 }
 return $clean;
 
}

?>

Post XML data using CURL php


Recently I was working in a hotel booking engine and found a couple of methods to post XML to server; I thought this might be good to share with my friends who want to post xml via HTTP POST method.
There are several ways to Send XML requests via HTTP POST. I am going to show you post XML data using CURL 
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$xml_data =''.
    ''.
        '1234567890'.
        'lgsoftwares'.
        'mypassword'.
        'example.com'.
    ''.
    ''.
        ''.
        ''.
    ''.
''.
'JHM'.
        'OGGSHE'.
        '101009'.
        '101509'.
        '1'.
  ''.  
  '';
 
 
$URL = "https://www.yourwebserver.com/path/";
 
   $ch = curl_init($URL);
   curl_setopt($ch, CURLOPT_MUTE, 1);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
   curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $output = curl_exec($ch);
   curl_close($ch);
 
?>

Friday, July 13, 2012

Prevent XSS attacks with php

There are a number of ways hackers put to use for XSS attacks, PHP’s built-in functions do not respond to all sorts of XSS attacks. Hence, functions such as strip_tags, filter_var, mysql_real_escape_string, htmlentities, htmlspecialchars, etc do not protect us 100%. You need a better mechanism, here is what is solution:

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
 
// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
 
// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
 
// Only works in IE: 
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
 
// Remove namespaced elements (we do not need them)
$data = preg_replace('#]*+>#i', '', $data);
 
do
{
        // Remove really unwanted tags
        $old_data = $data;
        $data = preg_replace('#]*+>#i', '', $data);
}
while ($old_data !== $data);
 
// we are done...
return $data;
}

?>

Tuesday, July 10, 2012

Post or Submit Form Data with PHP CURL

Last Sunday, I was working with website form to collect data from third party website. If you have to just submit form its easy website does not restrict to use CURL in order to post data but my requirement was to post website from data and store that data in my database too. This is easy and simple and has a lot of ways to do.

Now I would like to show you PHP CURL way to post form data. You can use PHP Jquery and Ajax to make it more fancy. But I want to keep it simple.

Step 1 -
I am using one sales force form as example.
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

<form action="curl.php" method="POST">
<input type=hidden name="oid" value="70D400000009mU7">
<input type=hidden name="retURL" value="http://www.site.com/thankyou.html">
<label for="first_name">First Name</label><input  id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br>
<label for="last_name">Last Name</label><input  id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br>
<label for="street">Address</label><textarea name="street"></textarea><br>
<label for="city">City</label><input  id="city" maxlength="40" name="city" size="20" type="text" /><br>
<label for="zip">Zip</label><input  id="zip" maxlength="20" name="zip" size="20" type="text" /><br>
<label for="email">Email</label><input  id="email" maxlength="80" name="email" size="20" type="text" /><br>
<label for="phone">Phone</label><input  id="phone" maxlength="40" name="phone" size="20" type="text" /><br>
<input type="submit" name="submit">
</form>

Step 2  - 
This is standard PHP CURL script (curl.php) to post from you can use anywhere without any modification in from you can add more fields if you need.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//Initialize the $query_string variable for later use
$query_string = "";
 
//If there are POST variables
if ($_POST) {
 
//Initialize the $kv array for later use
$kv = array();
 
//For each POST variable as $name_of_input_field => $value_of_input_field
foreach ($_POST as $key => $value) {
 
//Set array element for each POST variable (ie. first_name=lakhsidhu)
$kv[] = stripslashes($key)."=".stripslashes($value);
 
}
 
//Create a query string with join function separted by &
$query_string = join("&", $kv);
}
//Check to see if cURL is installed ...
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
 
//The original form action URL from Step 2 :)
$url = 'https://www.site.com/path.php';
 
//Open cURL 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($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
 
//Set some settings that make it all work :)
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
 
//Execute SalesForce web to lead PHP cURL
$result = curl_exec($ch);
 
//close cURL connection
curl_close($ch);
if($result=='ok')
{
echo '<script>alert("Posted -- ")</script>';
}
// Here you can write mysql query to insert data in table.
 
$insert_tbl_index_page= "insert into tbl_form_data(first_name,last_name,street,city,zip,phone,email)values('$first_name','$last_name','$street','$city','$zip','$phone','$email')";

?>



Sunday, July 1, 2012

Connecting to ODBC using PHP



<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


// connect to a DSN "database" with a user and password "4evertutorials"
$connect = odbc_connect("database", "4evertutorials", "4evertutorials");


// query the users table for name and surname
$query = "SELECT name, surname FROM users";



// perform the query
$result = odbc_exec($connect, $query);



// fetch the data from the database

while(odbc_fetch_row($result))
{
  $name = odbc_result($result, 1);
  $surname = odbc_result($result, 2);
  print("$name $surname\n");

}


// close the connection
odbc_close($connect);

?>

Get Unique Value from PHP Array

array_unique()

array_unique — Removes duplicate values from an array

Description:

Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

Example:

/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$_input = array("a" => "1", "2", "3" => "1", "2", "3");
$result = array_unique($_input);
print_r($result);


Result:

Array
(
  [a] => 1
  [0] => 2
  [2] => 3
)
?>
 
 

© 2014 4everTutorials. All rights resevered.

Back To Top