I am attempting to construct a postcode checker for a small number of stores in Australia. Basically, the customer enters their zip code and the site will then redirect to appropriate local pricing/services.
I am using this as a base but I am having a problem (listed by one of the comments on that site too) that no matter what value is entered for some reason the code marks the zip as SA even when it is completely different.
The code I am using is below.
<?php
// v1.0 Postcode Checker Just iStuff
// Copyright Ben Green 2014
// Redirect Customers to Appropriate Local Pricing and Services
// Sets cookie upon entering postcode, will then remember postcode for 3 days on customer's system
if (preg_match('#^\d+$#', $_POST['cf_postcode'])):
else:
print "Please enter your postcode correctly.";
endif;
$postcode = $_POST['cf_postcode'];
function findState($postcode) {
$ranges = array(
'NSW' => array(
1000, 1999,
2000, 2599,
2619, 2898,
2921, 2999
),
'ACT' => array(
200, 299,
2600, 2618,
2900, 2920
),
'VIC' => array(
3000, 3999,
8000, 8999
),
'QLD' => array(
4000, 4999,
9000, 9999
),
'SA' => array(
5000, 5999
),
'WA' => array(
6000, 6797,
6800, 6999
),
'TAS' => array(
7000, 7999
),
'NT' => array(
800, 999
)
);
$exceptions = array(
0800 => 'NT',
872 => 'NT',
2540 => 'NSW',
2611 => 'ACT',
2620 => 'NSW',
3500 => 'VIC',
3585 => 'VIC',
3586 => 'VIC',
3644 => 'VIC',
3707 => 'VIC',
2899 => 'NSW',
6798 => 'WA',
6799 => 'WA',
7151 => 'TAS'
);
$postcode = intval($postcode);
if ( array_key_exists($postcode, $exceptions) ) {
return $exceptions[$postcode];
}
foreach ($ranges as $state => $range)
{
$c = count($range);
for ($i = 0; $i < $c; $i+=2) {
$min = $range[$i];
$max = $range[$i+1];
if ( $postcode >= $min && $postcode <= $max ) {
return $state;
}
}
}
return null;
}
//Redirect for NT
if ($state = NT)
{
header( "Location: http://www.justistuff.com.au/ntrepairs.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for QLD
if ($state = QLD)
{
header( "Location: http://www.justistuff.com.au/mailin.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for VIC
if ($state = VIC)
{
header( "Location: http://www.justistuff.com.au/mailin.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for ACT
if ($state = ACT)
{
header( "Location: http://www.justistuff.com.au/mailin.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for NSW
if ($state = NSW)
{
header( "Location: http://www.justistuff.com.au/mailin.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for WA
if ($state = WA)
{
header( "Location: http://www.justistuff.com.au/mailin.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for TAS
if ($state = TAS)
{
header( "Location: http://www.justistuff.com.au/mailin.php" );
setcookie("postcode", $postcode, time()+259200);
}
//Redirect for SA
if ($state = SA)
{
header( "Location: http://www.justistuff.com.au/sarepairs.php" );
setcookie("postcode", $postcode, time()+259200);
}
I can't seem to work out what is causing it to redirect to SA even when the value entered (for example 2142) is clearly marked as NSW
if ($state = VIC)
That has two issues. First of all = is used for assignment, not for comparison. Secondly VIC is a string and should be in quotes like
if ($state == 'VIC')
Fix that for all your if statements and you're good.
Also, you are not calling findState function anywhere, before you start comparing the list of states you need to call that function to see what state your postcode belongs to
$state=findState($postcode);
//if($state=="thisthat")
it is classic == problem, in your if you have assignment operator used instead of equality operator.
Also, I suggest using exit whenever you use header redirect, it ensure the next line of code didn't get executed.
To explain the problem from your partial code. you are using if statement to compare and then instead of equality you are assigning the value to $state. this result in true for if and hence the code instead if block will get executed. Since you don't have exit it parse next if.
I suggest changing your if to switch with break in there.
Related
So I have been working on an API app using Riot's API. And I need to store massive amounts of API endpoint data into a SQL DB so I can pull stats from the DB.
I have tested just about everything I can, no spelling errors, no connection errors, but for some reason the data is never getting loaded into the server and the page is just stuck on refreshing.
This initially made me think it was an infinite loop, however I tested the loop and it is not an infinite loop, or at least as far as I could test.
My next thought was that this script will just take awhile to run, so I waited for over an hour and it still was stuck on loading the page.
I haven't even gotten to update statements yet, but if you guys could take a look at my code and see if you're finding anything wrong or even if there is a better approach to do this, thanks!
Also if you need any more information or questions about my goals/layout feel free to ask for clarification.
Also I've removed the apiKey and db credentials for obvious reasons, if you need an API key to test the script they are avaialable at https://developer.riotgames.com/
<?php
$data = [
'IRON' => 'I',
'IRON' => 'II',
'IRON' => 'III',
'IRON' => 'IV',
'BRONZE' => 'I',
'BRONZE' => 'II',
'BRONZE' => 'III',
'BRONZE' => 'IV',
'SILVER' => 'I',
'SILVER' => 'II',
'SILVER' => 'III',
'SILVER' => 'IV',
'GOLD' => 'I',
'GOLD' => 'II',
'GOLD' => 'III',
'GOLD' => 'IV',
'PLATINUM' => 'I',
'PLATINUM' => 'II',
'PLATINUM' => 'III',
'PLATINUM' => 'IV',
'DIAMOND' => 'I',
'DIAMOND' => 'II',
'DIAMOND' => 'III',
'DIAMOND' => 'IV'
];
function update_DB($param, $region)
{
foreach ($param as $tier => $division) {
$page = 1;
while ($page >= 1) {
$apiKey = '';
$url = 'https://' . $region . '.api.riotgames.com/tft/league/v1/entries/' . $tier . '/' . $division . '?page=' . $page . '&api_key=' . $apiKey;
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
$output = curl_exec($curl);
curl_close($curl);
$arr = json_decode($output, true);
if ($arr === []) { //Empty Quit Loop
$page = 0;
}
if (count($arr) > 0) { //Not empty move to next page and store/update data
$i = 0;
while ($i < count($arr)) {
$conn = mysqli_connect("localhost", "root", "", "");
$leagueId = $arr[$i]['leagueId'];
$queueType = $arr[$i]['queueType'];
$tier = $arr[$i]['tier'];
$rank = $arr[$i]['rank'];
$summonerId = $arr[$i]['summonerId'];
$summonerName = $arr[$i]['summonerName'];
$leaguePoints = $arr[$i]['leaguePoints'];
$wins = $arr[$i]['wins'];
$losses = $arr[$i]['losses'];
$stmt = $conn->prepare("INSERT INTO allusersna (leagueId, queueType, tier, rank, summonerId, summonerName, leaguePoints, wins, losses) VALUES (?,?,?,?,?,?,?,?,?)");
if (!$stmt) {
echo 'ERROR INSERT STATEMENT';
exit();
}
$stmt->bind_param("ssssssiii", $leagueId, $queueType, $tier, $rank, $summonerId, $summonerName, $leaguePoints, $wins, $losses);
$stmt->execute();
$i++;
}
$page++;
}
}
}
}
I have been struggling to implement Google's Measurement Protocol on a Wordpress site.
Apache Server, using PHP 5.4.35.
What I want to do is get server-side visitor data loaded into Google Analytics. The site has huge discrepancies between server logs and GA data, and I'm hoping to get the two to (somewhat) match up.
I have taken the code published by Stu Miller on his website, and made some slight edits hoping to reflect my use case. I've added the following to my wp-includes/functions.php file:
require( ABSPATH . WPINC . '/http.php' );
require( ABSPATH . WPINC . '/class-http.php' );
require( ABSPATH . WPINC . '/general-template.php' );
// Handle the parsing of the _ga cookie or setting it to a unique identifier
// Generate UUID v4 function - needed to generate a CID when one isn't available
function gaGenUUID() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
// 16 bits for "time_mid"
mt_rand( 0, 0xffff ),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand( 0, 0x0fff ) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand( 0, 0x3fff ) | 0x8000,
// 48 bits for "node"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
function gaParseCookie() {
if (isset($_COOKIE['_ga'])) {
list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"],4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2);
$cid = $contents['cid'];
}
else $cid = gaGenUUID();
return $cid;
}
function gaBuildHit( $method = null, $info = null ) {
if ( $method && $info) {
// Standard params
$v = 1;
$tid = "UA-xxxxxxx"; // Put your own Analytics ID in here
$cid = gaParseCookie();
// Register a PAGEVIEW
if ($method === 'pageview') {
// Send PageView hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
't' => 'pageview',
'dt' => $info['title'],
'dp' => $info['slug']
);
gaFireHit($data);
} // end pageview method
// Register an ECOMMERCE TRANSACTION (and an associated ITEM)
else if ($method === 'ecommerce') {
// Set up Transaction params
$ti = uniqid(); // Transaction ID
$ta = 'SI';
$tr = $info['price']; // transaction value (native currency)
$cu = $info['cc']; // currency code
// Send Transaction hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
't' => 'transaction',
'ti' => $ti,
'ta' => $ta,
'tr' => $tr,
'cu' => $cu
);
gaFireHit($data);
// Set up Item params
$in = urlencode($info['info']->product_name); // item name;
$ip = $tr;
$iq = 1;
$ic = urlencode($info['info']->product_id); // item SKU
$iv = urlencode('SI'); // Product Category - we use 'SI' in all cases, you may not want to
// Send Item hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
't' => 'item',
'ti' => $ti,
'in' => $in,
'ip' => $ip,
'iq' => $iq,
'ic' => $ic,
'iv' => $iv,
'cu' => $cu
);
gaFireHit($data);
} // end ecommerce method
}
}
global $post;
$data = array(
// Get the queried object and sanitize it
'title' => $title = $post->post_title,
'slug' => $slug = $post->post_name
);
gaBuildHit( 'pageview', $data);
// See https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
function gaFireHit( $data = null ) {
if ( $data ) {
$getString = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
$result = wp_remote_get( $getString );
#$sendlog = error_log($getString, 1, "ME#EMAIL.COM"); // comment this in and change your email to get an log sent to your email
return $result;
}
return false;
}
I have received several errors along the way, which started with the wp_remote_get() function being not defined, which resulted in my including the:
require( ABSPATH . WPINC . '/http.php' );
This inclusion moved up the error list to WP_Http() class not found, which resulted in my inclusion of:
require( ABSPATH . WPINC . '/class-http.php' );
... and so on. I don't quite remember the error which prompted my inclusion of:
require( ABSPATH . WPINC . '/general-template.php' );
I believe it was a PHP Fatal error: Call to undefined function get_bloginfo().
Anyway, I think I'm doing includes wrong. The latest fatal error is: Fatal error: Call to undefined function home_url() in /home/user/public_html/domain/wp-includes/general-template.php on line 658
I looked up the Wordpress Codex a bit and it also seems like the wp_remote_safe_post() would have been the better option, with Google recommending POST instead of GET due to the restricted payload on GET.
Unfortunately I lack the experience to make sense of how the code is supposed to be used, I had been hoping the initial code would be good enough to make happen, with maybe some tweaks.
Am I doing something wrong with the includes? Or has wordpress 4.6.1 moved so far ahead that all of this is deprecated? Or maybe I'm using the wrong functions.php file?
How to track the movement of the user between the two domains?
scheme:
1) the user clicks the button in doman-exemple1.com and go out from doman-exemple1.com and comes to doman-exemple2.com
login
2) doman-exemple2.com executed only on the server (that is not possible to use javascript)
<?php
// executed something codes... ;
// go with result to doman-exemple1.com
header('Location: http://doman-exemple1.com/?good='.$code);
?>
3) user returned to the http://doman-exemple1.com/?good=t45ygsw45t4
I need that google analytics understand that this same user and it not different users
This works:
https://support.google.com/analytics/answer/1034342?hl=en
But I cannot use thit becouse doman-exemple2.com executed only PHP and cannot use javascript
please help how to do this without javascript and only with PHP
P.S.
I read this: https://github.com/thomasbachem/php-ga but not understand if i can use this in my situations
If you are using Universal Analytics of GA, then have a look at the Measurement Protocol.
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
That can allow you to track through PHP only, and by using the same cid you can continue to track (using the same profile) the session.
thenx for Marcel Dumont
code get from this example: http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
doman-exemple1.com:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
//https://support.google.com/analytics/answer/1034342?hl=uk
//https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain
ga('create', 'UA-33396333-20', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['doman-exemple2.com'] );
ga('send', 'pageview');
</script>
doman-exemple2.com:
<?php
if (isset($_GET["_ga"])) {
setcookie('_ga_my', $_GET["_ga"],time()+3600*24*24);
list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_GET["_ga"],4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2);
$cid = $contents['cid'];
$ga = "GA1.2.".$cid;
setcookie('_ga', $ga,time()+3600*24*24);
}
function gaParseCookie() {
if (isset($_COOKIE['_ga'])) {
list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"],4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2);
$cid = $contents['cid'];
}
else $cid = gaGenUUID();
return $cid;
}
// Generate UUID v4 function - needed to generate a CID when one isn't available
function gaGenUUID() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
// 16 bits for "time_mid"
mt_rand( 0, 0xffff ),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand( 0, 0x0fff ) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand( 0, 0x3fff ) | 0x8000,
// 48 bits for "node"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
//echo gaParseCookie();
function gaBuildHit( $method = null, $info = null ) {
if ( $method && $info) {
// Standard params
$v = 1;
$tid = "UA-33396333-20"; // Put your own Analytics ID in here
$cid = gaParseCookie();
// Register a PAGEVIEW
if ($method === 'pageview') {
// Send PageView hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
't' => 'pageview',
'dt' => $info['title'],
'dp' => $info['slug']
);
gaFireHit($data);
} // end pageview method
}
}
// See https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
function gaFireHit( $data = null ) {
if ( $data ) {
$getString = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
$result = file_get_contents( $getString );
#$sendlog = error_log($getString, 1, "ME#EMAIL.COM"); // comment this in and change your email to get an log sent to your email
return $result;
}
return false;
}
$data = array(
'title' => 'Login doman-exemple2.com',
'slug' => 'doman-exemple2.com'
);
gaBuildHit( 'pageview', $data);
$secrret="111";
if (isset($_COOKIE['_ga_my'])) {
$gogl='&_ga='.$_COOKIE['_ga_my'];
header('Location: https://doman-exemple1.com/mass-add-email?utm_source=good&secret='.$secrret.'&utm_medium=good&utm_campaign=good'.$gogl);
} else {
header('Location: https://doman-exemple1.com/mass-add-email?utm_source=good&secret='.$secrret.'&utm_medium=good&utm_campaign=good');
}
exit();
?>
I created this piece of code to use Google Analytics Measurement Protocol instead of the google provided javascript, analytics.js in one of my page.
Recently I was playing with analytics javascript code, and I found that many times it will not collect data if something is blocking tracking codes (eg.: analytics.js) like when PrivDog is installed (amongs others).
The original idea is coming from here, but this is for wordpress.
http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
I modified the code to send data with sockets. (and without the wordpress functions library)
$gclid = $_GET['gclid'];
if (!empty($gclid)) {
setcookie("gclid", $gclid, time() + (10 * 365 * 24 * 60 * 60));
}
// Handle the parsing of the _ga cookie or setting it to a unique identifier
function gaParseCookie()
{
if (isset($_COOKIE['_ga'])) {
list($version, $domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"], 4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1 . '.' . $cid2);
$cid = $contents['cid'];
} else {
$cid = gaGenUUID();
}
return $cid;
}
// Generate UUID v4 function - needed to generate a CID when one isn't available
function gaGenUUID()
{
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
function gaBuildHit($method = null, $info = null)
{
global $gclid;
if ($method && $info) {
// Standard params
$v = 1;
$tid = "UA-XXXXXXX-XX"; // Put your own Analytics ID in here
$cid = gaParseCookie();
if (empty($gclid)) {
$gclid = $_COOKIE['gclid'];
}
// Register a PAGEVIEW
if ($method === 'pageview') {
// Send PageView hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
't' => 'pageview',
'dt' => $info['title'],
'dp' => $info['slug']
);
gaFireHit($data);
} // end pageview method
//
// Register an ECOMMERCE TRANSACTION (and an associated ITEM)
else if ($method === 'ecommerce') {
// Send Transaction hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
't' => 'transaction',
'ti' => $info['tid'], // Transaction ID
'ta' => 'SI',
'tr' => $info['price'], // transaction value (native currency)
'ts' => $info['shipping'], // transaction shipping (native currency)
'cu' => $info['cc'] // currency code
);
gaFireHit($data);
// Set up Item params
if ($info['info']->product_name) {
$in = urlencode($info['info']->product_name); // item name;
$ip = $tr;
$iq = 1;
$ic = urlencode($info['info']->product_id); // item SKU
$iv = urlencode('SI'); // Product Category - we use 'SI' in all cases, you may not want to
// Send Item hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
't' => 'item',
'ti' => $ti,
'in' => $in,
'ip' => $ip,
'iq' => $iq,
'ic' => $ic,
'iv' => $iv,
'cu' => $cu
);
gaFireHit($data);
}
} else if ($method === 'event') {
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
'gclid' => $gclid,
'ec' => $info['category'],
'ea' => $info['event'],
'el' => $info['label'],
'ev' => $info['value']
);
gaFireHit($data);
}
}
}
// See ttps://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
function gaFireHit($data = null)
{
if ($data) {
$url = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
$result = socketPost($url, $getString, $_SERVER['HTTP_USER_AGENT']);
return $result;
}
return false;
}
function socketPost($url, $post_string, $ua = null)
{
$parts = parse_url($url);
// workout port and open socket
$port = isset($parts['port']) ? $parts['port'] : 80;
$success = $fp = fsockopen($parts['host'], $port, $errno, $errstr, 30);
if ($fp) {
// create output string
$output = "POST " . $parts['path'] . " HTTP/1.1\r\n";
if (is_string($ua)) {
$output .= "User-Agent: " . $ua . "\r\n";
}
$output .= "Host: " . $parts['host'] . "\r\n";
$output .= "Content-Type: application/x-www-form-urlencoded\r\n";
$output .= "Content-Length: " . strlen($post_string) . "\r\n";
$output .= "Connection: Close\r\n\r\n";
$output .= isset($post_string) ? $post_string : '';
// send output to $url handle
$success = fwrite($fp, $output);
fclose($fp);
}
return $success ? true : false;
}
//examples:
//page hit
$data = array(
'title' => 'Page title',
'slug' => $_SERVER["REQUEST_URI"]
);
gaBuildHit('pageview', $data);
//ecommerce
$data = array(
'tid' => $order_id_in_merchant_system,
'cc' => 'AUD', // the currency code
'price' => $order_total, // the price
'shipping' => $order_shipping, // the shipping cost
'country' => 'AU' // the country ISO code
);
gaBuildHit('ecommerce', $data);
The code itself is working just fine. I put here for you to get the idea.
Question is, I dont really see the flow, how could an Adwords Click get tracked here. Like, if there is no _ga cookie set before (then gaParseCookie creates one), how could analytics connect the tracked event into eg.: an Analytics keyword the click coming from? Is that possible with Measurement Protocol?
I need help with this code, is a credit card validation, I been trying to make it work in my code but I can't, I just need to obtain 2 variables, is the card is working it should return true that works, but if not it shows an error message, but I also need to obtain a return false, here is the code:
<?php
$cardnumber = $_POST['CardNumber'];
$cardname = $_POST['CardType'];
$cards = array ( array ('name' => 'American Express',
'length' => '15',
'prefixes' => '34,37',
'checkdigit' => true
),
array ('name' => 'Diners Club Carte Blanche',
'length' => '14',
'prefixes' => '300,301,302,303,304,305',
'checkdigit' => true
),
array ('name' => 'Diners Club',
'length' => '14,16',
'prefixes' => '36,38,54,55',
'checkdigit' => true
),
array ('name' => 'Discover',
'length' => '16',
'prefixes' => '6011,622,64,65',
'checkdigit' => true
),
array ('name' => 'Diners Club Enroute',
'length' => '15',
'prefixes' => '2014,2149',
'checkdigit' => true
),
array ('name' => 'JCB',
'length' => '16',
'prefixes' => '35',
'checkdigit' => true
),
array ('name' => 'Maestro',
'length' => '12,13,14,15,16,18,19',
'prefixes' => '5018,5020,5038,6304,6759,6761,6762,6763',
'checkdigit' => true
),
array ('name' => 'MasterCard',
'length' => '16',
'prefixes' => '51,52,53,54,55',
'checkdigit' => true
),
array ('name' => 'Solo',
'length' => '16,18,19',
'prefixes' => '6334,6767',
'checkdigit' => true
),
array ('name' => 'Switch',
'length' => '16,18,19',
'prefixes' => '4903,4905,4911,4936,564182,633110,6333,6759',
'checkdigit' => true
),
array ('name' => 'VISA',
'length' => '16',
'prefixes' => '4',
'checkdigit' => true
),
array ('name' => 'VISA Electron',
'length' => '16',
'prefixes' => '417500,4917,4913,4508,4844',
'checkdigit' => true
),
array ('name' => 'LaserCard',
'length' => '16,17,18,19',
'prefixes' => '6304,6706,6771,6709',
'checkdigit' => true
)
);
$ccErrorNo = 0;
$ccErrors [0] = "Unknown card type";
$ccErrors [1] = "No card number provided";
$ccErrors [2] = "Credit card number has invalid format";
$ccErrors [3] = "Credit card number is invalid";
$ccErrors [4] = "Credit card number is wrong length";
// Establish card type
$cardType = -1;
for ($i=0; $i<sizeof($cards); $i++) {
// See if it is this card (ignoring the case of the string)
if (strtolower($cardname) == strtolower($cards[$i]['name'])) {
$cardType = $i;
break;
}
}
// If card type not found, report an error
if ($cardType == -1) {
$errornumber = 0;
$errortext = $ccErrors [$errornumber];
return true;
}
// Ensure that the user has provided a credit card number
if (strlen($cardnumber) == 0) {
$errornumber = 1;
$errortext = $ccErrors [$errornumber];
return true;
}
// Remove any spaces from the credit card number
$cardNo = str_replace (' ', '', $cardnumber);
// Check that the number is numeric and of the right sort of length.
if (!preg_match("/^[0-9]{13,19}$/",$cardNo)) {
$errornumber = 2;
$errortext = $ccErrors [$errornumber];
return true;
}
// Now check the modulus 10 check digit - if required
if ($cards[$cardType]['checkdigit']) {
$checksum = 0; // running checksum total
$mychar = ""; // next char to process
$j = 1; // takes value of 1 or 2
// Process each digit one by one starting at the right
for ($i = strlen($cardNo) - 1; $i >= 0; $i--) {
// Extract the next digit and multiply by 1 or 2 on alternative digits.
$calc = $cardNo{$i} * $j;
// If the result is in two digits add 1 to the checksum total
if ($calc > 9) {
$checksum = $checksum + 1;
$calc = $calc - 10;
}
// Add the units element to the checksum total
$checksum = $checksum + $calc;
// Switch the value of j
if ($j ==1) {$j = 2;} else {$j = 1;};
}
// All done - if checksum is divisible by 10, it is a valid modulus 10.
// If not, report an error.
if ($checksum % 10 != 0) {
$errornumber = 3;
$errortext = $ccErrors [$errornumber];
return true;
}
}
// The following are the card-specific checks we undertake.
// Load an array with the valid prefixes for this card
$prefix = explode(',',$cards[$cardType]['prefixes']);
// Now see if any of them match what we have in the card number
$PrefixValid = false;
for ($i=0; $i<sizeof($prefix); $i++) {
$exp = '/^' . $prefix[$i] . '/';
if (preg_match($exp,$cardNo)) {
$PrefixValid = true;
break;
}
}
// If it isn't a valid prefix there's no point at looking at the length
if (!$PrefixValid) {
$errornumber = 3;
$errortext = $ccErrors [$errornumber];
return true;
}
// See if the length is valid for this card
$LengthValid = false;
$lengths = explode(',',$cards[$cardType]['length']);
for ($j=0; $j<sizeof($lengths); $j++) {
if (strlen($cardNo) == $lengths[$j]) {
$LengthValid = true;
break;
}
}
// See if all is OK by seeing if the length was valid.
if (!$LengthValid) {
$errornumber = 4;
$errortext = $ccErrors [$errornumber];
return true;
};
// The credit card is in the required format.
return true;
echo $errortext;
?>
you can see there is return true, but I also need to change this to false when the card is not validated so I can make other validation, thanks for any help.
I find other code that do what I need, is a little more simple, is possible to add the $verified variable of this new code to the first one? here is the code:
<?php
$cc_number = $_POST['CardNumber'];
$type = $_POST['CardType'];
$cc_num = str_replace (' ', '', $cc_number);
if($type == "AX") {
$denum = "American Express";
} elseif($type == "DC") {
$denum = "Diner's Club";
} elseif($type == "DS") {
$denum = "Discover";
} elseif($type == "MC") {
$denum = "Master Card";
} elseif($type == "VI") {
$denum = "Visa";
}
if($type == "AX") {
$pattern = "/^([34|37]{2})([0-9]{13})$/";//American Express
if (preg_match($pattern,$cc_num)) {
$verified = true;
} else {
$verified = false;
}
} elseif($type == "DC") {
$pattern = "/^([30|36|38]{2})([0-9]{12})$/";//Diner's Club
if (preg_match($pattern,$cc_num)) {
$verified = true;
} else {
$verified = false;
}
} elseif($type == "DS") {
$pattern = "/^([6011]{4})([0-9]{12})$/";//Discover Card
if (preg_match($pattern,$cc_num)) {
$verified = true;
} else {
$verified = false;
}
} elseif($type == "MC") {
$pattern = "/^([51|52|53|54|55]{2})([0-9]{14})$/";//Mastercard
if (preg_match($pattern,$cc_num)) {
$verified = true;
} else {
$verified = false;
}
} elseif($type == "VI") {
$pattern = "/^([4]{1})([0-9]{12,15})$/";//Visa
if (preg_match($pattern,$cc_num)) {
$verified = true;
} else {
$verified = false;
}
}
if($verified == false) {
//Do something here in case the validation fails
echo "Credit card invalid. Please make sure that you entered a valid <em>" . $denum . "</em> credit card ";
} else { //if it will pass...do something
echo "Your <em>" . $denum . "</em> credit card is valid";
}
?>
Declare a variable at the top of your function:
$invalid = false;
Then everywhere in your code where you have return true; change it to: $invalid = true;.
Then you can just do return $invalid; at the end of your function. It will return true if there was an error. If there is no error it will return false.
Look at all the if statements that look like this:
$errornumber = whateverNumber;
$errortext = $ccErrors [$errornumber];
return true;
Those are what return true when there is an error. Simply change the return statement to return false; in those places to make the script return false.
The only return true; should be at the end of your function.
thanks for help, here is the final code, I just make some changes and works great:
$cards = array ( array ('name' => 'American Express',
'length' => '15',
'prefixes' => '34,37',
'checkdigit' => true
),
array ('name' => 'Diners Club Carte Blanche',
'length' => '14',
'prefixes' => '300,301,302,303,304,305',
'checkdigit' => true
),
array ('name' => 'Diners Club',
'length' => '14,16',
'prefixes' => '36,38,54,55',
'checkdigit' => true
),
array ('name' => 'Discover',
'length' => '16',
'prefixes' => '6011,622,64,65',
'checkdigit' => true
),
array ('name' => 'Diners Club Enroute',
'length' => '15',
'prefixes' => '2014,2149',
'checkdigit' => true
),
array ('name' => 'JCB',
'length' => '16',
'prefixes' => '35',
'checkdigit' => true
),
array ('name' => 'Maestro',
'length' => '12,13,14,15,16,18,19',
'prefixes' => '5018,5020,5038,6304,6759,6761,6762,6763',
'checkdigit' => true
),
array ('name' => 'MasterCard',
'length' => '16',
'prefixes' => '51,52,53,54,55',
'checkdigit' => true
),
array ('name' => 'Solo',
'length' => '16,18,19',
'prefixes' => '6334,6767',
'checkdigit' => true
),
array ('name' => 'Switch',
'length' => '16,18,19',
'prefixes' => '4903,4905,4911,4936,564182,633110,6333,6759',
'checkdigit' => true
),
array ('name' => 'VISA',
'length' => '16',
'prefixes' => '4',
'checkdigit' => true
),
array ('name' => 'VISA Electron',
'length' => '16',
'prefixes' => '417500,4917,4913,4508,4844',
'checkdigit' => true
),
array ('name' => 'LaserCard',
'length' => '16,17,18,19',
'prefixes' => '6304,6706,6771,6709',
'checkdigit' => true
)
);
$ccErrorNo = 0;
$ccErrors [0] = "Unknown card type";
$ccErrors [1] = "No card number provided";
$ccErrors [2] = "Credit card number has invalid format";
$ccErrors [3] = "Credit card number is invalid";
$ccErrors [4] = "Credit card number is wrong length";
// Establish card type
$cardType = -1;
for ($i=0; $i<sizeof($cards); $i++) {
// See if it is this card (ignoring the case of the string)
if (strtolower($cardname) == strtolower($cards[$i]['name'])) {
$cardType = $i;
$response = true;
break;
}
}
// If card type not found, report an error
if ($cardType == -1) {
$errornumber = 0;
$errortext = $ccErrors [$errornumber];
$response = false;
return false;
}
// Ensure that the user has provided a credit card number
if (strlen($cardnumber) == 0) {
$errornumber = 1;
$errortext = $ccErrors [$errornumber];
$response = false;
return false;
}
// Remove any spaces from the credit card number
$cardNo = str_replace (' ', '', $cardnumber);
// Check that the number is numeric and of the right sort of length.
if (!preg_match("/^[0-9]{13,19}$/",$cardNo)) {
$errornumber = 2;
$errortext = $ccErrors [$errornumber];
$response = false;
return false;
}
// Now check the modulus 10 check digit - if required
if ($cards[$cardType]['checkdigit']) {
$checksum = 0; // running checksum total
$mychar = ""; // next char to process
$j = 1; // takes value of 1 or 2
// Process each digit one by one starting at the right
for ($i = strlen($cardNo) - 1; $i >= 0; $i--) {
// Extract the next digit and multiply by 1 or 2 on alternative digits.
$calc = $cardNo{$i} * $j;
// If the result is in two digits add 1 to the checksum total
if ($calc > 9) {
$checksum = $checksum + 1;
$calc = $calc - 10;
}
// Add the units element to the checksum total
$checksum = $checksum + $calc;
// Switch the value of j
if ($j ==1) {$j = 2;} else {$j = 1;};
}
// All done - if checksum is divisible by 10, it is a valid modulus 10.
// If not, report an error.
if ($checksum % 10 != 0) {
$errornumber = 3;
$errortext = $ccErrors [$errornumber];
$response = false;
return false;
}
}
// The following are the card-specific checks we undertake.
// Load an array with the valid prefixes for this card
$prefix = explode(',',$cards[$cardType]['prefixes']);
// Now see if any of them match what we have in the card number
$PrefixValid = false;
for ($i=0; $i<sizeof($prefix); $i++) {
$exp = '/^' . $prefix[$i] . '/';
if (preg_match($exp,$cardNo)) {
$PrefixValid = true;
$response = true;
break;
}
}
// If it isn't a valid prefix there's no point at looking at the length
if (!$PrefixValid) {
$errornumber = 3;
$errortext = $ccErrors [$errornumber];
$response = false;
return false;
}
// See if the length is valid for this card
$LengthValid = false;
$lengths = explode(',',$cards[$cardType]['length']);
for ($j=0; $j<sizeof($lengths); $j++) {
if (strlen($cardNo) == $lengths[$j]) {
$LengthValid = true;
$response = true;
break;
}
}
// See if all is OK by seeing if the length was valid.
if (!$LengthValid) {
$errornumber = 4;
$errortext = $ccErrors [$errornumber];
$response = false;
return false;
};
// The credit card is in the required format.
return $response;
in the other page:
$cardnumber = $_POST['CardNumber'];
$cardname = $_POST['CardType'];
require('phpcreditcard.php');
if ($response == true) {
echo 'works';
}
elseif ($response == false) {
echo $errortext;
}