FeatureUp News
Loading...

Recent Post

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Online Payment PHP Codes for your Website

Online Payment PHP Codes for your Website

 The Sample Code will not work without the following:
 
* cURL extension for PHP (http://www.php.net/manual/en/ref.curl.php)
* SSL Certificate
* Development Account setup with DPS

If you dont have access to a Development account please click here to request it.

Online Payment PHP Codes for your Website-featureup

Standard Request Page:

<?php
/*
#
# This function is a simple example of
# how to send and receive Payment Express XML
# messages to process a transaction.
#
*/
     
function process_request($name,$amount,$ccnum,$ccmm,$ccyy,$merchRef)
{
     
$cmdDoTxnTransaction .= "<Txn>";
$cmdDoTxnTransaction .= "<PostUsername>TestUsername</PostUsername>"; #Insert your DPS Username here
$cmdDoTxnTransaction .= "<PostPassword>TestPassword</PostPassword>"; #Insert your DPS Password here
$cmdDoTxnTransaction .= "<Amount>$amount</Amount>";
$cmdDoTxnTransaction .= "<InputCurrency>USD</InputCurrency>";
$cmdDoTxnTransaction .= "<CardHolderName>$name</CardHolderName>";
$cmdDoTxnTransaction .= "<CardNumber>$ccnum</CardNumber>";
$cmdDoTxnTransaction .= "<DateExpiry>$ccmm$ccyy</DateExpiry>";
$cmdDoTxnTransaction .= "<TxnType>Purchase</TxnType>";
$cmdDoTxnTransaction .= "<MerchantReference>$merchRef</MerchantReference>";
$cmdDoTxnTransaction .= "</Txn>";
               
$URL = "sec.paymentexpress.com/pxpost.aspx";
//echo "\n\n\n\nSENT:\n$cmdDoTxnTransaction\n\n\n\n\n$";
              
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://".$URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$cmdDoTxnTransaction);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //Needs to be included if no *.crt is available to verify SSL certificates
curl_setopt($ch,CURLOPT_SSLVERSION,3); 
$result = curl_exec ($ch);
curl_close ($ch);
                
parse_xml($result);
}
 
function parse_xml($data)
{
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
     
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
}
else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
             
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
     
/* Uncommenting this block will display the entire array and show all values returned.
echo "<pre>";
print_r ($params);
echo "</pre>";
*/
         
$success = $params[TXN][SUCCESS];
     
$MerchantReference = $params[TXN][$success][MERCHANTREFERENCE];
$CardHolderName = $params[TXN][$success][CARDHOLDERNAME];
$AuthCode = $params[TXN][$success][AUTHCODE];
$Amount = $params[TXN][$success][AMOUNT];
$CurrencyName = $params[TXN][$success][CURRENCYNAME];
$TxnType = $params[TXN][$success][TXNTYPE];
$CardNumber = $params[TXN][$success][CARDNUMBER];
$DateExpiry = $params[TXN][$success][DATEEXPIRY];
$CardHolderResponseText = $params[TXN][$success][CARDHOLDERRESPONSETEXT];
$CardHolderResponseDescription = $params[TXN][$success][CARDHOLDERRESPONSEDESCRIPTION];
$MerchantResponseText = $params[TXN][$success][MERCHANTRESPONSETEXT];
$DPSTxnRef = $params[TXN][$success][DPSTXNREF];
         
$html = "<table align='center' width='500' style='FONT-SIZE: 10pt; FONT-FAMILY: Arial, Helvetica, sans-serif'>";
$html .= "<BR><hr><BR>";
$html .= "<tr><td>Merchant Reference: </td><td>$MerchantReference</td></tr>";
$html .= "<tr><td>CardHolderName: </td><td>$CardHolderName</td></tr>";
$html .= "<tr><td>AuthCode: </td><td>$AuthCode</td></tr>";
$html .= "<tr><td>Amount: </td><td>$Amount</td></tr>";
$html .= "<tr><td>CurrencyName: </td><td>$CurrencyName</td></tr>";
$html .= "<tr><td>DateExpiry: </td><td>$DateExpiry</td></tr>";
$html .= "<tr><td>CardHolderResponseText: </td><td>$CardHOlderResponseText</td></tr>";
$html .= "<tr><td>CardHolderResponseDescription: </td><td>$CardHolderResponseDescription</td></tr>";
$html .= "<tr><td>MerchantResponseText: </td><td>$MerchantResponseText</td></tr>";
$html .= "<tr><td>TxnType: </td><td>$TxnType</td></tr>";
$html .= "<tr><td>DPSTxnRef: </td><td>$DPSTxnRef</td></tr>";
$html .= "</table>";
//$html .= "</body></html>";
         
echo $html;    
     
}
 
#main start
$Action = $_REQUEST["Action"];
$CardName = $_REQUEST["CardName"];
$Amount = $_REQUEST["Amount"];
$CardNum = $_REQUEST["CardNum"];
$ExMnth = $_REQUEST["ExMnth"];
$ExYear = $_REQUEST["ExYear"];
$MerchRef = $_REQUEST["MerchRef"];
 
If ($Action == "Submit")
{
 
process_request($CardName, $Amount, $CardNum, $ExMnth, $ExYear, $MerchRef);
 
}
 
?>
 
<html>
<head>
<title>DPS PXPost Sample -- PHP</title>
</head>
<body>
 
 
<form method="POST">
<input type="hidden" name="Action" value="Submit"><BR><BR>
<table align="center" width="550" style="FONT-SIZE: 10pt; FONT-FAMILY: Arial, Helvetica, sans-serif" border="0">
<tr>
<td width="280">
<table style="FONT-SIZE: 10pt; FONT-FAMILY: Arial, Helvetica, sans-serif">
<tr>
<td colspan="2">Name (as it appears on the card)<BR>
<input type="text" name="CardName" value="Mr John Smith" size="26">
</td>
</tr>
<tr><td colspan="2">Card Number<BR>
<input type="text" name="CardNum" value="4111111111111111" maxlength="16" size="26">
</td>
</tr>
<tr><td>Amount<BR>
<input type="text" name="Amount" value="1.80" size="9">
</td>
<td>Merchant Reference<BR>
<input type="text" name="MerchRef" value="invoice 84325" size="12">
</td>
</tr>
</table>
</td>
<td>Expiry Date<BR>
<select name="ExMnth"><option value="01">01</option>
    <option value="02">02</option>
    <option value="03">03</option>
    <option value="04">04</option>
    <option value="05">05</option>
    <option value="06">06</option>
    <option value="07">07</option>
    <option value="08">08</option>
    <option value="09">09</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12</option>
</select>
<select name="ExYear"><option value="05">05</option>
    <option value="06">06</option>
    <option value="07">07</option>
    <option value="08">08</option>
    <option value="09">09</option>
</select><BR><BR><BR><BR>
</td>
<td align="right"><img src="http://www.paymentexpress.com/dpslogo.gif">
<BR><BR><BR>
<input type="submit" value="process">
</td>
</tr>
</table>
</form>
 
</body>
</html>
Advance PHP Programming Tips

Advance PHP Programming Tips


Ternary Operators

A ternary operator is a different way to layout a simple if statement. Let's take a look at one and then break it down. We'll just use a simple check to see if a GET parameter is set and not empty, if it is we will default to the word John, otherwise use the value that was set as the GET parameter.
$name = (!empty($_GET['name'])? $_GET['name'] : 'John');
This might look complex to begin with but there are three sections to a ternary operator:
  1. The conditional !empty($_GET['name'])
  2. The true result $_GET['name']
  3. The false result 'John'
The ternary operator will return either the true or false conditional, and therefore it will be assigned to $name. If we write this as a normal if statement we'd have one of the following:
if(!empty($_GET['name'])){
    $name = $_GET['name'];
}else{
    $name = 'John';
}

// Or

$name = 'John';
if(!empty($_GET['name'])){
    $name = $_GET['name'];
}
The two above and the ternary operator will all end up with $name having something assigned to it.

Nesting

While not advisable, it is possible to nest ternary operators within each other much like you would with standard if statements, or to form a long string of if...else if...else if...elsestatements.
Ternary operators can be very helpful and clean up code, but don't over complicate them otherwise your code might become inundated with large amounts of complex rediculousness that will get you hunted down by a violent psychopath.

Class Autoloading

To make use of a class file, you have to ensure that the class you're using is available within the page that you're using it. In most cases this will be as easy as you just including the PHP file that contains the class.
But what if we have a very large number of classes that we could potentially use within one or many sections of our code? Well, we could include all of them within a common header file, or only include the ones that we know that we're going to use on that page. However, we then need to remember to include new classes whenever we want to use a different one etc.
So instead of including classes that might not get used, or we might remove later, we can employ class autoloading. When we autoload classes we can write what will happen - this might be to just throw an error to let us know that we've not included the class file, or, as in most cases, we make the function include the file that we need.

The Code

Here we'll be using the PHP function spl_autoload_register(), we'll only be interested in the first parameter, but there are two others that you can define if you wanted the function to behave differently. I'll jump straight into how to use it:
function loadMyClass($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
}

spl_autoload_register('loadMyClass');
This will pass the name of the class that we're trying to load as the first parameter of the function that we specified. As of PHP 5.3.0 we are able to use anonymous functions, basically a function thas has no name:
spl_autoload_register(function ($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
});
Which will work exactly the same as the method of implementation above. So now in future, we don't need to include the class files that we'll be using as this function will run if the class is undefined, include the class and then the instantiation will be called.

Dynamic Variables

Sometimes we want to be able to dynmically define a variable, or refer to a variable based on a user's input. Let's start with this code:
$myname = 'Michael';
$yourname = 'Ben';
if($_GET['whatname'] == 'your'){
    echo $yourname;
}else if($_GET['whatname'] == 'my'){
    echo $myname;
}else{
    echo 'No Name';
}
To use the value of a variable to then form another variable we use double dollar signs $$so for example we could do $who = 'myname'; then echo $$who. This will echo out the value of$myname.
Break it down like this (exemplary code, not actual working code):
$who = 'myname';
$$who = $'myname';
$$who = $myname;
echo $$who; // would return 'Michael'
In reference to the code above we could look to use something along the lines of the following for very dynamically defined variables:
$who = $_GET['whatname'] . 'name';
if(isset($$who)){
    echo $$who;
}else{
    echo 'No Name';
}
As with ternary operators, you should use these loosely, as in most situations there's not much need for them, but you will most probably find some crazy-ninja somewhere who uses this notation.

Referencing

Passing variables by reference, is a way to pass variables into functions so that the function can alter the original variable without having to return anything or define it as global etc. A function parameter that is going to be passed in as a reference is preceeded by an ampersand (&). Let's go with an example:
function lowercase(&$string){
    $string = strtolower($string);
}

$name = 'STEPHEN';
lowercase($name);
echo $name; // returns stephen
What you can see is that where we've called the lowercase() method and passed in $name, the function has altered the actual string that we passed in, as within the function $stringbecomes $name.
There are advantages of using references, for example you don't have to return anything from the function, nor do you have to look to define them as globally accessible.

Arrays

References are super awesome when you use them with arrays. Let's say we have a function that sets the first item in any array to potato - because you know, it'll be the most helpful function ever:
function potatoArray(&$array){
    $array[0] = 'potato';
}

$nonpotato = array(
    'john',
    'andrew',
    'cheese'
);

potatoArray($nonpotato);

print_r($nonpotato); // This will now have changed 'john' to 'potato'
References are very powerful things, and could be used extensively. You'll find them used with the array_walk() method other some other array methods that PHP have.

Relative Time Calculation

Everywhere you look people love their relative times, they're on Facebook, they're in most Twitter apps and they're here on Codular. Codular isn't too fussed about the specific time of when an action was made and so we have come up with a special class with handle the relative date for us.
We define a list of the days that exist, and then do some logic to find out what to display. We firstly check if it's today or yesterday, obviously returning the respective term. We then look to see if the date falls in the last 7 days (less than 8 days), this is so that we can display last Monday, last Sunday etc. But obviously the 'Last' prefix can only apply to one week.
Our method takes a second parameter with is a fallback format, this is the format that we use when the date falls out of the 'Last' date range. The first parameter is a simple UNIX timestamp.
<?php

class TimeClass {

    private static $days = array(
        'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
    );

    /**
     * relativeTime()
     * @param int $time
     * @param string $format
     */
    public static function relative($time, $format = 'jS F Y'){
        if(date('d/m/Y', $time) === date('d/m/Y')){
            return 'Today';
        }else if(date('d/m/Y', $time) === date('d/m/Y', time() - 3600 * 24)){
            return 'Yesterday';
        }else if((time() - $time) < 3600 * 24 * 8){
            return 'Last ' . self::$days[date('w', $time)];
        }else{
            return date($format, $time);
        }

    }

}
Usage would be as simple as doing:
echo TimeClass:relative(time());
That will always output Today as we are using the current timestamp.
Relative date calculations can be pretty smple, another that is commonly used is to round to the nearest multiple of a time frame - ie days, weeks, months years etc. Below is a quick function to finish off with that will do exactly that up to 10 years in time then fall back to a date:
<?php

function relativeTime($timestamp, $format = 'Y-m-d H:i'){
    $dif = time() - $timestamp;

    $dateArray = array(
        "second" => 60,     // 60 seconds in 1 minute
        "minute" => 60,     // 60 minutes in 1 hour
        "hour" => 24,       // 24 hours in 1 day
        "day" => 7,         // 7 days in 1 week
        "week" => 4,        // 4 weeks in 1 month
        "month" => 12,      // 12 months in 1 year
        "year" => 10        // Up to 10 years
    );

    foreach($dateArray as $key => $item){
        if($dif < $item)
            return $dif . ' ' . $key . ($dif == 1? '' : 's') . ' ago';
        $dif = round($dif/$item);
    }
    return date($format, $timestamp);
}
How to code Effective Chaptcha in PHP

How to code Effective Chaptcha in PHP

How to code Effective Chaptcha in PHP_FeatureUp
Simple but effective php chaptcha, coded on php only, means it doesnt require JavaScript. It's a simple chaptcha but it can do the job very well.

chaptcha.php code:

<?php
session_start();

// http://featureup.blogspot.com

$data = array(
0 => array('Are you human?' => 'yes'),
1 => array('2 + 2 =' => '4'),
2 => array('8 - 0 =' => '8'),
3 => array('5 + 2 =' => '7'),
4 => array('4 + 2 =' => '6'),
5 => array('Barac' => 'Obama'),
6 => array('Type snake' => 'snake'),
7 => array('Type bird' => 'bird'),
8 => array('Type google' => 'google'),
9 => array('Type firefox' => 'firefox'),
10 => array('Type music' => 'music'),
);

$rand = array_rand($data);
$key = key($data[$rand]);
            $ques = $key;
            $ans = $data[$rand][$key];

// create image
header("Content-type: image/png");
    $img = imagecreatetruecolor(270,40);

    $green = imagecolorallocate($img, 0, 255, 0);
    $red = imagecolorallocate($img, 255, 0, 0);

    imagefill($img, 0, 0, $green);
    imagettftext($img, 20, 0, 5, 25, $red, "blazed.ttf", $ques);

    imagepng($img);
    imagedestroy($img);
$_SESSION['answer'] = $ans;
?>


index.php or whatever you want to call it:

<?php
session_start();


if(isset($_SESSION['answer']) && !empty($_POST['answer'])){


if($_POST['answer'] == $_SESSION['answer']){
echo ('Welcome human');
unset($_SESSION['answer']);
}
else{
die('Hi bot');
unset($_SESSION['answer']);
}


}
else{
?>
<style type="text/css">
#code, #go{
outline: none;
background: #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #6495ED;
padding: 5px;
text-decoration: none;
color: #6495ED;
}
</style>
<img src="chaptcha.php"><br>
Enter code:<br>
<form action="d.php" method="post">
<input type="text" name="answer" id="code">
<input type="submit" id="go">
</form>
<?php
}
?>
How to get Protection against Session Hijacking and Hackers with PHP Session

How to get Protection against Session Hijacking and Hackers with PHP Session

How to get Protection against Session Hijacking and Hackers with PHP Session_FeatureUp

When it comes to session security lot of webmasters like to skip it. By myself i use sessions and not cookies, not for any big purpose but sessions are cool, easy to implement.

Steps to session security


1- Not filtered GET, POST, REQUEST data 
2- Using session_regenerate_id() 
3- Acsepting http only cookies 
4- Manually expiring sessions 
5- Php.ini modifications 

Lets move on


To start a session we start by: 
<?php
session_start(); // it starts sessions
?>

A live example is echoing "Hello World" 
<?php
session_start();
// string to print
$string = "Hello World";
$_SESSION['string'] = $string;
// printing it out
echo $_SESSION['string'];
?>
Simple and cool :D 

Not filtered GET, POST, REQUEST data


If you are giving to a session a value from forms make sure to filter all bad charachters. 

Here is a live example of a vulnerability: 
<?php
session_start();
/* attacker using an evil javascript like:
<script>alert(0)</script>
which will popup a "0"
*/
$string = $_GET['string'];
$_SESSION['string'] = $string;
// printing it out
echo $_SESSION['string'];
?>

What happened here is that GET data are not filterd against Cross Site Scripting(XSS Attacks), think when the data get posted in mysql database and attacker executes sql injection scripts. 
Make sure this kind of data is always filtered. 

Using session_regenerate_id()


Whats all about this function ?? 
Well this function is very inportant! 

a- When you refresh the page you get a new session id 
b- When you close the browser the session gets destroyed 
c- It will prevent session stealing 

To implement it just simply do: 
<?php
session_start();
session_regenerate_id();
?>

Acsepting http only cookies


This is an php.ini function, php.ini explains it as: Whether or not to add the httpOnly flag to the cookie, which makes it inaccessible to browser scripting languages such as JavaScript. for more about it you can read on php.net 

To implement it just simply do: 
<?php
session_start();
session_regenerate_id();
// setting ini rule
ini_set('session.cookie_httponly', true);
?>

Manually expiring sessions



We can use time() to create a session when we last logged in and destroy it after X time. 
<?php
session_start();
session_regenerate_id();
// setting ini rule
ini_set('session.cookie_httponly', true);
// record last login
$_SESSION['lastlogin'] = time();
?>
When we nextly access it we do a check for expiration: 
<?php
session_start();
session_regenerate_id();
// setting ini rule
ini_set('session.cookie_httponly', true);
// check if session is more old than 20 seconds
if($_SESSION['lastlogin'] > time() - 20){
die("Session expired, please relogin.");
}
?>

Php.ini modifications



We gonna make some modifications on php.ini file. 
You can use ctrl+f to search for strings. 
session.save_path = "c:/wamp/tmp" (where the sessions will be saved)
session.gc_maxlifetime = 1440 (maximum time session will be alive)
it is good to change this 2 options or more (depending on your needs) 

Dont's


It is not a good recomandation to save sessions on a mysql database, it will slow page speed and if data is not filtered things may go bad. 

Thanks for reading, I worked alot on writing this tutorial, a bit of share of this post would be nice :D
Quick Message
Press Esc to close
Copyright © 2013 FeatureUp All Right Reserved. The content is copyrighted to FeatureUp and may not be reproduced on other websites without permission or credit.