Skip to content

Instantly share code, notes, and snippets.

@klebergraciasoares
Created July 12, 2013 11:41
Show Gist options
  • Save klebergraciasoares/5983830 to your computer and use it in GitHub Desktop.
Save klebergraciasoares/5983830 to your computer and use it in GitHub Desktop.
<?php
/**
* Validar se um CNPJ é válido
* @param string
* @return bool
*/
public function valid_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', $cpf);
if(strlen($cpnj) <> 14){
return false;
}
$calcular = 0;
$calcularDois = 0;
for ($i = 0, $x = 5; $i <= 11; $i++, $x--) {
$x = ($x < 2) ? 9 : $x;
$number = substr($cnpj, $i, 1);
$calcular += $number * $x;
}
for ($i = 0, $x = 6; $i <= 12; $i++, $x--) {
$x = ($x < 2) ? 9 : $x;
$numberDois = substr($cnpj, $i, 1);
$calcularDois += $numberDois * $x;
}
$digitoUm = (($calcular % 11) < 2) ? 0 : 11 - ($calcular % 11);
$digitoDois = (($calcularDois % 11) < 2) ? 0 : 11 - ($calcularDois % 11);
if ($digitoUm <> substr($cnpj, 12, 1) || $digitoDois <> substr($cnpj, 13, 1)) {
return false;
}
return true;
}
<?php
/**
* Verifica se o CPF informado é valido
* @param string
* @return bool
*/
function valid_cpf($cpf)
{
$cpf = preg_replace('/\D/', '', $cpf);
if (strlen($cpf) != 11)
return false;
$sum = 0;
for ($i = 0; $i < 9; $i++) {
$sum += $cpf[$i] * (10-$i);
}
$mod = $sum % 11;
$digit = ($mod > 1) ? (11 - $mod) : 0;
if ($cpf[9] != $digit)
return false;
$sum = 0;
for ($i = 0; $i < 10; $i++) {
$sum += $cpf[$i] * (11-$i);
}
$mod = $sum % 11;
$digit = ($mod > 1) ? (11 - $mod) : 0;
if ($cpf[10] != $digit)
return false;
if (str_repeat($cpf[0],11) == $cpf) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment