Ir para conteúdo
Fórum Script Brasil

blx32

Membros
  • Total de itens

    15
  • Registro em

  • Última visita

Posts postados por blx32

  1. Olá a todos, a intenção do script é simplificar ainda mais o meu formulário,  podendo por em qualquer lugar.

    <pay.php>

    <?php
    $email_pay ='test@yandex.com';
    $email_pag ='test@live.com';
    
    $form_pag = $_POST['form_pag'];
    $item_nam = $_POST['item_nam'];
    $valor = $_POST['valor'];
    
    
    	if($form_pag == "pagseguro"){
           //########PAG*SEGURO############
        $content = http_build_query(array(
        'currency' => 'BRL',
        'receiverEmail' => $email_pag,
    ));
         $context = stream_context_create(array(
        'http' => array(
        'method'  => 'POST',
        'content' => $content,
        )
    ));
    $result = file_get_contents('https://pagseguro.uol.com.br/checkout/v2/donation.html', null, $context);
    
    	} elseif($form_pag == "paypal"){
    		//#######PAYPAL########
    	$content = http_build_query(array(
        'cmd' => '_xclick',
        'business' => $email_pay,
        'currency_code' => 'BRL',
        'item_nam' => $item_nam ,
        'amount' => $valor,
    ));
    	$context = stream_context_create(array(
        'http' => array(
            'method'  => 'POST',
            'content' => $content,
        )
    ));
    $result = file_get_contents('https://www.paypal.com/br/cgi-bin/webscr', null, $context);
    
    	}else echo "erro";
    
    ?>

    <pay.html> (algumas coisas foram copiadas por pura preguiça, já que meu foco é o php.

    <link rel="stylesheet" type="text/css" media="all" href="https://elementary.io/styles/home.css"><link rel="stylesheet" type="text/css" media="all" href="https://fonts.googleapis.com/css?family=Raleway:100,100italic|Open+Sans:300,400,600,300italic,400italic|Droid+Sans|Roboto+Mono&subset=latin,greek,vietnamese,greek-ext,latin-ext,cyrillic,cyrillic-ext"><link rel="stylesheet" type="text/css" media="all" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"><link rel="stylesheet" type="text/css" media="all" href="https://elementary.io/styles/main.css">
    
    <div class="row">
                    <div id="amounts">
                        <form action='pay.php' method='POST'>
                                            <select  class="small-button payment-button target-amount" name="form_pag" size="1" gtbfieldid="52">
      <option value="paypal">Pay Pal</option>
      <option value="pagseguro">Pag Seguro</option>
    </select>
    
                        <div class="column">
                            <span class="pre-amount">$</span>
                            <input type="number" step="0.01" min="0" max="999999.99" id="amount-custom" class="button small-button target-amount" placeholder="Personalizar" name='valor'>
                            <p class="small-label focus-reveal text-center">Digite qualquer valor em Reais.</p>
                        </div>
                        <div style="clear:both;"></div>
                                             
                    <button type="submit" id="download" class="suggested-action">pagar</button>
                </form>
                </div>

     

    Vi um tutorial de como reencaminhar o post, más acho que o fiz errado.

    AGREDEÇO MUITO, se alguém pudr me dar uma ajuda, dizer onde esta o erro.

    Ou algo pra ler, uma maneira diferente de fazer isso.

  2. Fui vendo na internet os tutoriais e tudo mais e resolvi juntar e mais pra frente incrementar meu sisteminha.

    Arquivo functions.php

    <?php
    /**
     * Created by PhpStorm.
     * User: blx32
     * Date: 7/10/16
     * Time: 1:58 PM
     */
    include_once ('global-config.php');
    /*
     * É importante não colocar apenas "session_start()"; no topo de todas as páginas nas quais você desejar utilizar sessões php, se você realmente estiver preocupado com a segurança, é desta forma que você deverá fazer. Você criará uma função chamada "sec_session_start", a qual irá iniciar uma sessão php de forma segura. Você deveria chamar esta função no topo de cada página a partir da qual você deseje acessar uma variável de sessão php.
    Função de Início de Sessão Segura:
     */
    function sec_session_start()
    {
        $session_name = 'sec_session_id';   // Set a custom session name
        $secure = true;
        // This stops JavaScript being able to access the session id.
        $httponly = true;
        // Forces sessions to only use cookies.
        if (ini_set('session.use_only_cookies', 1) === FALSE) {
            header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
            exit();
        }
        // Gets current cookies params.
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"],
            $cookieParams["path"],
            $cookieParams["domain"],
            $secure,
            $httponly);
        // Sets the session name to the one set above.
        session_name($session_name);
        session_start();            // Start the PHP session
        session_regenerate_id(true);    // regenerated the session, delete the old one.
    };
    
    /*
     * Crie uma função de login.
    Esta função irá checar o email e a senha na base de dados e retornará um valor "true" (verdadeiro) caso ambos estejam corretos e combinando.
    Função de Login Seguro:
     */
    function login($email, $password, $mysqli)
    {
        // Using prepared statements means that SQL injection is not possible.
        if ($stmt = $mysqli->prepare("SELECT id, username, password FROM members WHERE email = ? LIMIT 1")) {
            $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
            $stmt->execute();    // Execute the prepared query.
            $stmt->store_result();
    
            // get variables from result.
            $stmt->bind_result($user_id, $username, $db_password);
            $stmt->fetch();
    
            if ($stmt->num_rows == 1) {
                // If the user exists we check if the account is locked
                // from too many login attempts
    
                if (checkbrute($user_id, $mysqli) == true) {
                    // Account is locked
                    // Send an email to user saying their account is locked
                    return false;
                } else {
                    // Check if the password in the database matches
                    // the password the user submitted. We are using
                    // the password_verify function to avoid timing attacks.
                    if (password_verify($password, $db_password)) {
                        // Password is correct!
                        // Get the user-agent string of the user.
                        $user_browser = $_SERVER['HTTP_USER_AGENT'];
                        // XSS protection as we might print this value
                        $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                        $_SESSION['user_id'] = $user_id;
                        
                        // XSS protection as we might print this value
                        $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
                        $_SESSION['username'] = $username;
                        $_SESSION['login_string'] = hash('sha512', $db_password . $user_browser);
                        // Login successful.
                        return true;
                    } else {
                        // Password is not correct
                        // We record this attempt in the database
                        $now = time();
                        $mysqli->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
                        return false;
                    }
                }
            } else {
                // No user exists.
                return false;
            }
        }
    };
    
    
    /*
     * Função Brute Force.
    Ataques de brute force ou força bruta acontecem quando hackers tentam milhares de diferentes senhas em uma conta, seja de forma randômica através de senhas aleatórias ou através de um dicionário de palavras. Em nosso script, se um usuário falhar em sua tentativa de login por mais de 5 vezes, sua conta será bloqueada.
    Crie a função login_check:
     */
    
    function checkbrute($user_id, $mysqli)
    {
        // Get timestamp of current time
        $now = time();
    
        // All login attempts are counted from the past 2 hours.
        $valid_attempts = $now - (2 * 60 * 60);
    
        if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time >'$valid_attempts'")) {
            $stmt->bind_param('i', $user_id);
    
            // Execute the prepared query.
            $stmt->execute();
            $stmt->store_result();
    
            // If there have been more than 5 failed logins
            if ($stmt->num_rows > 5) {
                return true;
            } else {
                return false;
            }
        }
    }
    
    
    /*Cheque o status de login.
    Isto é feito checando-se as variáveis de sessão "user_id" e "login_string". A variável de sessão "login_string" possui as informações de endereço IP e navegador em forma de hash juntamente com a senha. Utilizamos o endereço IP e a informação do navegador pois é muito improvável que o usuário altere o endereço IP ou o navegador durante sua sessão. Fazendo isto, você impede um ataque de hijack na sessão (sequestro de sessão, literalmente).
    Crie a função login_check:
    */
    
    function login_check($mysqli) {
        // Check if all session variables are set 
        if (isset($_SESSION['user_id'],
            $_SESSION['username'],
            $_SESSION['login_string'])) {
    
            $user_id = $_SESSION['user_id'];
            $login_string = $_SESSION['login_string'];
            $username = $_SESSION['username'];
    
            // Get the user-agent string of the user.
            $user_browser = $_SERVER['HTTP_USER_AGENT'];
    
            if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) {
                // Bind "$user_id" to parameter. 
                $stmt->bind_param('i', $user_id);
                $stmt->execute();   // Execute the prepared query.
                $stmt->store_result();
    
                if ($stmt->num_rows == 1) {
                    // If the user exists get variables from result.
                    $stmt->bind_result($password);
                    $stmt->fetch();
                    $login_check = hash('sha512', $password . $user_browser);
    
                    if (hash_equals($login_check, $login_string) ){
                        // Logged In!!!! 
                        return true;
                    } else {
                        // Not logged in 
                        return false;
                    }
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    }
    
    function esc_url($url)
    {
    
        if ('' == $url) {
            return $url;
        }
    
        $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
    
        $strip = array('%0d', '%0a', '%0D', '%0A');
        $url = (string)$url;
    
        $count = 1;
        while ($count) {
            $url = str_replace($strip, '', $url, $count);
        }
    
        $url = str_replace(';//', '://', $url);
    
        $url = htmlentities($url);
    
        $url = str_replace('&', '&', $url);
        $url = str_replace("'", ''', $url);
    
        if ($url[0] !== '/') {
            // We're only interested in relative links from $_SERVER['PHP_SELF']
            return '';
        } else {
            return $url;
        }
    }
    ?>

    autentica_usuario.php

    <?php
    /**
     * Created by PhpStorm.
     * User: blx32
     * Date: 7/10/16
     * Time: 1:35 PM
     */
    
    include_once 'inc/db_connect.php';
    include_once 'inc/functions.php';
    
    sec_session_start(); // Our custom secure way of starting a PHP session.
    
    if (isset($_POST['email'], $_POST['p'])) {
        $email = $_POST['email'];
        $password = $_POST['p']; // The hashed password.
    
        if (login($email, $password, $mysqli) == true) {
            // Login success
            header('Location: protected_page.php');
        } else {
            // Login failed
            header('Location: index.php?error=1');
        }
    } else {
        // The correct POST variables were not sent to this page.
        echo 'Invalid Request';
    }

    db_connect.php

    <?php
    /**
     * Created by PhpStorm.
     * User: blx32
     * Date: 7/10/16
     * Time: 3:29 PM
     */
    include_once 'global-config.php';   // As functions.php is not included
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    ?>

    E global-config.php é onde estão o define do host,user,pdw e database.

    register.php

    <?php
    /**
     * Created by PhpStorm.
     * User: blx32
     * Date: 7/10/16
     * Time: 2:20 PM
     */
    /*
     * Certifique-se de que o valor de $_POST['p'] já esteja em hash a partir do javascript. Caso não esteja utilizando este método por desejar validar a senha no lado do servidor, certifique-se de utilizar hash.
     */
    
    
    include_once 'db_connect.php';
    include_once 'inc/global-config.php';
    
    $error_msg = "";
    
    if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
        // Sanitize and validate the data passed in
        $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
        $email = filter_var($email, FILTER_VALIDATE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Not a valid email
            $error_msg .= '<p class="error">The email address you entered is not valid</p>';
        }
    
        $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
        if (strlen($password) != 128) {
            // The hashed pwd should be 128 characters long.
            // If it's not, something really odd has happened
            $error_msg .= '<p class="error">Invalid password configuration.</p>';
        }
    
        // Username validity and password validity have been checked client side.
        // This should should be adequate as nobody gains any advantage from
        // breaking these rules.
        //
    
        $prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
        $stmt = $mysqli->prepare($prep_stmt);
    
        // check existing email
        if ($stmt) {
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $stmt->store_result();
    
            if ($stmt->num_rows == 1) {
                // A user with this email address already exists
                $error_msg .= '<p class="error">A user with this email address already exists.</p>';
                $stmt->close();
            }
        } else {
            $error_msg .= '<p class="error">Database error Line 39</p>';
            $stmt->close();
        }
    
        // check existing username
        $prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
        $stmt = $mysqli->prepare($prep_stmt);
    
        if ($stmt) {
            $stmt->bind_param('s', $username);
            $stmt->execute();
            $stmt->store_result();
    
            if ($stmt->num_rows == 1) {
                // A user with this username already exists
                $error_msg .= '<p class="error">A user with this username already exists</p>';
                $stmt->close();
            }
        } else {
            $error_msg .= '<p class="error">Database error line 55</p>';
            $stmt->close();
        }
    
        // TODO:
        // We'll also have to account for the situation where the user doesn't have
        // rights to do registration, by checking what type of user is attempting to
        // perform the operation.
    
        if (empty($error_msg)) {
    
            // Create hashed password using the password_hash function.
            // This function salts it with a random salt and can be verified with
            // the password_verify function.
            $password = password_hash($password, PASSWORD_BCRYPT);
    
            // Insert the new user into the database
            if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) {
                $insert_stmt->bind_param('sss', $username, $email, $password);
                // Execute the prepared query.
                if (! $insert_stmt->execute()) {
                    header('Location: ../error.php?err=Registration failure: INSERT');
                }
            }
            header('Location: ./register_success.php');
        }
    }
    ?>

    A pagina login.php

    <?php
    include_once 'inc/db_connect.php';
    include_once 'inc/functions.php';
    
    sec_session_start();
    
    if (login_check($mysqli) == true) {
        $logged = 'in';
    } else {
        $logged = 'out';
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Secure Login: Log In</title>
        <link rel="stylesheet" href="styles/main.css"/>
        <script type="text/JavaScript" src="sha512.js"></script>
        <script type="text/JavaScript" src="main.js"></script>
    </head>
    <body>
    <?php
    echo "Username: test_user
    Email: test@example.com
    Password: 6ZaxN2Vzm9NUJT2y";
    if (isset($_GET['error'])) {
        echo '<p class="error">Error Logging In!</p>';
    }
    ?>
    <form action="autentica_usuario.php" method="post" name="login_form">
        Email: <input type="text" name="email"/>
        Password: <input type="password"
                         name="password"
                         id="password"/>
        <input type="button"
               value="Login"
               onclick="formhash(this.form, this.form.password);"/>
    </form>
    
    <?php
    if (login_check($mysqli) == true) {
        echo '<p>Currently logged ' . $logged . ' as ' . htmlentities($_SESSION['username']) . '.</p>';
    
        echo '<p>Do you want to change user? <a href="inc/logoff.php">Log out</a>.</p>';
    } else {
        echo '<p>Currently logged ' . $logged . '.</p>';
        echo "<p>If you don't have a login, please <a href='register.php'>register</a></p>";
    }
    ?>
    </body>
    </html>

    logoff.php (está escrito errado mas não me preocupei em mudar).

    <?php
    /**
     * Created by PhpStorm.
     * User: blx32
     * Date: 7/10/16
     * Time: 2:14 PM
     */
    include_once ('functions.php');
    sec_session_start();
    
    // Unset all session values
    $_SESSION = array();
    
    // get session parameters
    $params = session_get_cookie_params();
    
    // Delete the actual cookie.
    setcookie(session_name(),
        '', time() - 42000,
        $params["path"],
        $params["domain"],
        $params["secure"],
        $params["httponly"]);
    
    // Destroy session
    session_destroy();
    header('Location: ../index.php');

    protegido.php (pagina que quero proteger).

    <?php
    /**
     * Created by PhpStorm.
     * User: blx32
     * Date: 7/10/16
     * Time: 2:32 PM
     */
    include_once 'inc/db_connect.php';
    include_once 'inc/functions.php';
    sec_session_start();
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Secure Login: Protected Page</title>
        <link rel="stylesheet" href="styles/main.css"/>
    </head>
    <body>
    <?php if (login_check($mysqli) == true) : ?>
        <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
        <p>
            This is an example protected page. To access this page, users
            must be logged in. At some stage, we'll also check the role of
            the user, so pages will be able to determine the type of user
            authorised to access the page.
        </p>
        <p>Return to <a href="index.php">login page</a></p>
    <?php else : ?>
        <p>
            <span class="error">You are not authorized to access this page.</span> Please <a href="login.php">login</a>.
        </p>
    <?php endif; ?>
    </body>
    </html>

    sha512.js

    var hexcase=0;var b64pad="";function hex_sha512(a){return rstr2hex(rstr_sha512(str2rstr_utf8(a)))}function b64_sha512(a){return rstr2b64(rstr_sha512(str2rstr_utf8(a)))}function any_sha512(a,b){return rstr2any(rstr_sha512(str2rstr_utf8(a)),b)}function hex_hmac_sha512(a,b){return rstr2hex(rstr_hmac_sha512(str2rstr_utf8(a),str2rstr_utf8(b)))}function b64_hmac_sha512(a,b){return rstr2b64(rstr_hmac_sha512(str2rstr_utf8(a),str2rstr_utf8(b)))}function any_hmac_sha512(a,c,b){return rstr2any(rstr_hmac_sha512(str2rstr_utf8(a),str2rstr_utf8(c)),b)}function sha512_vm_test(){return hex_sha512("abc").toLowerCase()=="ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"}function rstr_sha512(a){return binb2rstr(binb_sha512(rstr2binb(a),a.length*8))}function rstr_hmac_sha512(c,f){var e=rstr2binb(c);if(e.length>32){e=binb_sha512(e,c.length*8)}var a=Array(32),d=Array(32);for(var b=0;b<32;b++){a[b]=e[b]^909522486;d[b]=e[b]^1549556828}var g=binb_sha512(a.concat(rstr2binb(f)),1024+f.length*8);return binb2rstr(binb_sha512(d.concat(g),1024+512))}function rstr2hex(c){try{hexcase}catch(g){hexcase=0}var f=hexcase?"0123456789ABCDEF":"0123456789abcdef";var b="";var a;for(var d=0;d<c.length;d++){a=c.charCodeAt(d);b+=f.charAt((a>>>4)&15)+f.charAt(a&15)}return b}function rstr2b64(c){try{b64pad}catch(h){b64pad=""}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b="";var a=c.length;for(var f=0;f<a;f+=3){var k=(c.charCodeAt(f)<<16)|(f+1<a?c.charCodeAt(f+1)<<8:0)|(f+2<a?c.charCodeAt(f+2):0);for(var d=0;d<4;d++){if(f*8+d*6>c.length*8){b+=b64pad}else{b+=g.charAt((k>>>6*(3-d))&63)}}}return b}function rstr2any(m,c){var b=c.length;var l,f,a,n,e;var k=Array(Math.ceil(m.length/2));for(l=0;l<k.length;l++){k[l]=(m.charCodeAt(l*2)<<8)|m.charCodeAt(l*2+1)}var h=Math.ceil(m.length*8/(Math.log(c.length)/Math.log(2)));var g=Array(h);for(f=0;f<h;f++){e=Array();n=0;for(l=0;l<k.length;l++){n=(n<<16)+k[l];a=Math.floor(n/b);n-=a*b;if(e.length>0||a>0){e[e.length]=a}}g[f]=n;k=e}var d="";for(l=g.length-1;l>=0;l--){d+=c.charAt(g[l])}return d}function str2rstr_utf8(c){var b="";var d=-1;var a,e;while(++d<c.length){a=c.charCodeAt(d);e=d+1<c.length?c.charCodeAt(d+1):0;if(55296<=a&&a<=56319&&56320<=e&&e<=57343){a=65536+((a&1023)<<10)+(e&1023);d++}if(a<=127){b+=String.fromCharCode(a)}else{if(a<=2047){b+=String.fromCharCode(192|((a>>>6)&31),128|(a&63))}else{if(a<=65535){b+=String.fromCharCode(224|((a>>>12)&15),128|((a>>>6)&63),128|(a&63))}else{if(a<=2097151){b+=String.fromCharCode(240|((a>>>18)&7),128|((a>>>12)&63),128|((a>>>6)&63),128|(a&63))}}}}}return b}function str2rstr_utf16le(b){var a="";for(var c=0;c<b.length;c++){a+=String.fromCharCode(b.charCodeAt(c)&255,(b.charCodeAt(c)>>>8)&255)}return a}function str2rstr_utf16be(b){var a="";for(var c=0;c<b.length;c++){a+=String.fromCharCode((b.charCodeAt(c)>>>8)&255,b.charCodeAt(c)&255)}return a}function rstr2binb(b){var a=Array(b.length>>2);for(var c=0;c<a.length;c++){a[c]=0}for(var c=0;c<b.length*8;c+=8){a[c>>5]|=(b.charCodeAt(c/8)&255)<<(24-c%32)}return a}function binb2rstr(b){var a="";for(var c=0;c<b.length*32;c+=8){a+=String.fromCharCode((b[c>>5]>>>(24-c%32))&255)}return a}var sha512_k;function binb_sha512(p,A){if(sha512_k==undefined){sha512_k=new Array(new int64(1116352408,-685199838),new int64(1899447441,602891725),new int64(-1245643825,-330482897),new int64(-373957723,-2121671748),new int64(961987163,-213338824),new int64(1508970993,-1241133031),new int64(-1841331548,-1357295717),new int64(-1424204075,-630357736),new int64(-670586216,-1560083902),new int64(310598401,1164996542),new int64(607225278,1323610764),new int64(1426881987,-704662302),new int64(1925078388,-226784913),new int64(-2132889090,991336113),new int64(-1680079193,633803317),new int64(-1046744716,-815192428),new int64(-459576895,-1628353838),new int64(-272742522,944711139),new int64(264347078,-1953704523),new int64(604807628,2007800933),new int64(770255983,1495990901),new int64(1249150122,1856431235),new int64(1555081692,-1119749164),new int64(1996064986,-2096016459),new int64(-1740746414,-295247957),new int64(-1473132947,766784016),new int64(-1341970488,-1728372417),new int64(-1084653625,-1091629340),new int64(-958395405,1034457026),new int64(-710438585,-1828018395),new int64(113926993,-536640913),new int64(338241895,168717936),new int64(666307205,1188179964),new int64(773529912,1546045734),new int64(1294757372,1522805485),new int64(1396182291,-1651133473),new int64(1695183700,-1951439906),new int64(1986661051,1014477480),new int64(-2117940946,1206759142),new int64(-1838011259,344077627),new int64(-1564481375,1290863460),new int64(-1474664885,-1136513023),new int64(-1035236496,-789014639),new int64(-949202525,106217008),new int64(-778901479,-688958952),new int64(-694614492,1432725776),new int64(-200395387,1467031594),new int64(275423344,851169720),new int64(430227734,-1194143544),new int64(506948616,1363258195),new int64(659060556,-544281703),new int64(883997877,-509917016),new int64(958139571,-976659869),new int64(1322822218,-482243893),new int64(1537002063,2003034995),new int64(1747873779,-692930397),new int64(1955562222,1575990012),new int64(2024104815,1125592928),new int64(-2067236844,-1578062990),new int64(-1933114872,442776044),new int64(-1866530822,593698344),new int64(-1538233109,-561857047),new int64(-1090935817,-1295615723),new int64(-965641998,-479046869),new int64(-903397682,-366583396),new int64(-779700025,566280711),new int64(-354779690,-840897762),new int64(-176337025,-294727304),new int64(116418474,1914138554),new int64(174292421,-1563912026),new int64(289380356,-1090974290),new int64(460393269,320620315),new int64(685471733,587496836),new int64(852142971,1086792851),new int64(1017036298,365543100),new int64(1126000580,-1676669620),new int64(1288033470,-885112138),new int64(1501505948,-60457430),new int64(1607167915,987167468),new int64(1816402316,1246189591))}var q=new Array(new int64(1779033703,-205731576),new int64(-1150833019,-2067093701),new int64(1013904242,-23791573),new int64(-1521486534,1595750129),new int64(1359893119,-1377402159),new int64(-1694144372,725511199),new int64(528734635,-79577749),new int64(1541459225,327033209));var s=new int64(0,0),r=new int64(0,0),J=new int64(0,0),I=new int64(0,0),G=new int64(0,0),F=new int64(0,0),E=new int64(0,0),D=new int64(0,0),C=new int64(0,0),B=new int64(0,0),m=new int64(0,0),l=new int64(0,0),t=new int64(0,0),o=new int64(0,0),z=new int64(0,0),w=new int64(0,0),u=new int64(0,0);var v,y;var n=new Array(80);for(y=0;y<80;y++){n[y]=new int64(0,0)}p[A>>5]|=128<<(24-(A&31));p[((A+128>>10)<<5)+31]=A;for(y=0;y<p.length;y+=32){int64copy(J,q[0]);int64copy(I,q[1]);int64copy(G,q[2]);int64copy(F,q[3]);int64copy(E,q[4]);int64copy(D,q[5]);int64copy(C,q[6]);int64copy(B,q[7]);for(v=0;v<16;v++){n[v].h=p[y+2*v];n[v].l=p[y+2*v+1]}for(v=16;v<80;v++){int64rrot(z,n[v-2],19);int64revrrot(w,n[v-2],29);int64shr(u,n[v-2],6);l.l=z.l^w.l^u.l;l.h=z.h^w.h^u.h;int64rrot(z,n[v-15],1);int64rrot(w,n[v-15],8);int64shr(u,n[v-15],7);m.l=z.l^w.l^u.l;m.h=z.h^w.h^u.h;int64add4(n[v],l,n[v-7],m,n[v-16])}for(v=0;v<80;v++){t.l=(E.l&D.l)^(~E.l&C.l);t.h=(E.h&D.h)^(~E.h&C.h);int64rrot(z,E,14);int64rrot(w,E,18);int64revrrot(u,E,9);l.l=z.l^w.l^u.l;l.h=z.h^w.h^u.h;int64rrot(z,J,28);int64revrrot(w,J,2);int64revrrot(u,J,7);m.l=z.l^w.l^u.l;m.h=z.h^w.h^u.h;o.l=(J.l&I.l)^(J.l&G.l)^(I.l&G.l);o.h=(J.h&I.h)^(J.h&G.h)^(I.h&G.h);int64add5(s,B,l,t,sha512_k[v],n[v]);int64add(r,m,o);int64copy(B,C);int64copy(C,D);int64copy(D,E);int64add(E,F,s);int64copy(F,G);int64copy(G,I);int64copy(I,J);int64add(J,s,r)}int64add(q[0],q[0],J);int64add(q[1],q[1],I);int64add(q[2],q[2],G);int64add(q[3],q[3],F);int64add(q[4],q[4],E);int64add(q[5],q[5],D);int64add(q[6],q[6],C);int64add(q[7],q[7],B)}var k=new Array(16);for(y=0;y<8;y++){k[2*y]=q[y].h;k[2*y+1]=q[y].l}return k}function int64(b,a){this.h=b;this.l=a}function int64copy(b,a){b.h=a.h;b.l=a.l}function int64rrot(c,a,b){c.l=(a.l>>>b)|(a.h<<(32-b));c.h=(a.h>>>b)|(a.l<<(32-b))}function int64revrrot(c,a,b){c.l=(a.h>>>b)|(a.l<<(32-b));c.h=(a.l>>>b)|(a.h<<(32-b))}function int64shr(c,a,b){c.l=(a.l>>>b)|(a.h<<(32-b));c.h=(a.h>>>b)}function int64add(g,b,f){var d=(b.l&65535)+(f.l&65535);var c=(b.l>>>16)+(f.l>>>16)+(d>>>16);var a=(b.h&65535)+(f.h&65535)+(c>>>16);var e=(b.h>>>16)+(f.h>>>16)+(a>>>16);g.l=(d&65535)|(c<<16);g.h=(a&65535)|(e<<16)}function int64add4(j,m,l,k,i){var h=(m.l&65535)+(l.l&65535)+(k.l&65535)+(i.l&65535);var g=(m.l>>>16)+(l.l>>>16)+(k.l>>>16)+(i.l>>>16)+(h>>>16);var f=(m.h&65535)+(l.h&65535)+(k.h&65535)+(i.h&65535)+(g>>>16);var e=(m.h>>>16)+(l.h>>>16)+(k.h>>>16)+(i.h>>>16)+(f>>>16);j.l=(h&65535)|(g<<16);j.h=(f&65535)|(e<<16)}function int64add5(l,o,n,m,k,j){var i=(o.l&65535)+(n.l&65535)+(m.l&65535)+(k.l&65535)+(j.l&65535);var h=(o.l>>>16)+(n.l>>>16)+(m.l>>>16)+(k.l>>>16)+(j.l>>>16)+(i>>>16);var g=(o.h&65535)+(n.h&65535)+(m.h&65535)+(k.h&65535)+(j.h&65535)+(h>>>16);var f=(o.h>>>16)+(n.h>>>16)+(m.h>>>16)+(k.h>>>16)+(j.h>>>16)+(g>>>16);l.l=(i&65535)|(h<<16);l.h=(g&65535)|(f<<16)};

    main.js

    /**
     * Created by blx32 on 7/10/16.
     */
    function formhash(b,a){var c=document.createElement("input");b.appendChild(c);c.name="p";c.type="hidden";c.value=hex_sha512(a.value);a.value="";b.submit()}function regformhash(f,d,c,b,a){if(d.value==""||c.value==""||b.value==""||a.value==""){alert("You must provide all the requested details. Please try again");return false}e=/^\w+$/;if(!e.test(f.username.value)){alert("Username must contain only letters, numbers and underscores. Please try again");f.username.focus();return false}if(b.value.length<6){alert("Passwords must be at least 6 characters long.  Please try again");f.password.focus();return false}var e=/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;if(!e.test(b.value)){alert("Passwords must contain at least one number, one lowercase and one uppercase letter.  Please try again");return false}if(b.value!=a.value){alert("Your password and confirmation do not match. Please try again");f.password.focus();return false}var g=document.createElement("input");f.appendChild(g);g.name="p";g.type="hidden";g.value=hex_sha512(b.value);b.value="";a.value="";f.submit();return true};

    o BD

    CREATE DATABASE `secure_login`;
    CREATE USER 'sec_user'@'localhost' IDENTIFIED BY 'eKcGZr59zAa2BEWU';
    GRANT SELECT, INSERT, UPDATE ON `secure_login`.* TO 'sec_user'@'localhost';
    CREATE TABLE `secure_login`.`members` (
        `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `username` VARCHAR(30) NOT NULL,
        `email` VARCHAR(50) NOT NULL,
        `password` CHAR(128) NOT NULL
    ) ENGINE = InnoDB;
    
    CREATE TABLE `secure_login`.`login_attempts` (
        `user_id` INT(11) NOT NULL,
        `time` VARCHAR(30) NOT NULL
    ) ENGINE=InnoDB
    
    
    /*
    Username: test_user
    Email: test@example.com
    Password: 6ZaxN2Vzm9NUJT2y
     */
    
    
    INSERT INTO `secure_login`.`members` VALUES(1, 'test_user', 'test@example.com',
    '$2y$10$IrzYJi10j3Jy/K6jzSLQtOLif1wEZqTRQoK3DcS3jdnFEhL4fWM4G');

    A minha duvida é, o que posso fazer para que ele funcione completamente?

    Ele loga, e redireciona más na pagina que quero proteger o check_login não funciona muito bem.

    Ou como posso adicionar mais a informação "classe" na sessão?

    Desde já agradeço a todos.

  3. Olá irmãos de programação, eu tenho o seguinte problema que não sei como resolver.

    Tenho uma pagina de login semelhante ao do google, com email, senha e uma foto que fica por padrão até que alguém digite um usuário válido.

    O problema é esse, não sei como posso alterar a imagem conforme um usuário digitado.

    Não tem problema se for uma lista de possíveis, e ao digitar apareça a careta do cadastrado.

    Utilizo bootstrap com php.

  4. <?php

    function getBrowser()
    {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';
        $version = "";

        //First get the platform?
        if (preg_match('/linux/i', $u_agent)) {
            $platform = 'Linux';
        } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
            $platform = 'Mac';
        } elseif (preg_match('/windows|win32/i', $u_agent)) {
            $platform = 'Windows';
        }

        // Next get the name of the useragent yes seperately and for good reason
        if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {
            $bname = 'Internet Explorer';
            $ub = "MSIE";
        } elseif (preg_match('/Firefox/i', $u_agent)) {
            $bname = 'Mozilla Firefox';
            $ub = "Firefox";
        } elseif (preg_match('/Chrome/i', $u_agent)) {
            $bname = 'Google Chrome';
            $ub = "Chrome";
        } elseif (preg_match('/Safari/i', $u_agent)) {
            $bname = 'Apple Safari';
            $ub = "Safari";
        } elseif (preg_match('/Opera/i', $u_agent)) {
            $bname = 'Opera';
            $ub = "Opera";
        } elseif (preg_match('/Netscape/i', $u_agent)) {
            $bname = 'Netscape';
            $ub = "Netscape";
        }

        // finally get the correct version number
        $known = array('Version', $ub, 'other');
        $pattern = '#(?<browser>' . join('|', $known) .
            ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
        if (!preg_match_all($pattern, $u_agent, $matches)) {
            // we have no matching number just continue
        }

        // see how many we have
        $i = count($matches['browser']);
        if ($i != 1) {
            //we will have two since we are not using 'other' argument yet
            //see if version is before or after the name
            if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {
                $version = $matches['version'][0];
            } else {
                $version = $matches['version'][1];
            }
        } else {
            $version = $matches['version'][0];
        }

        // check if we have a number
        if ($version == null || $version == "") {
            $version = "?";
        }

        return array(
            'userAgent' => $u_agent,
            'name' => $bname,
            'version' => $version,
            'platform' => $platform,
            'pattern' => $pattern
        );
    }

    // now try it
    $ua = getBrowser();
    $yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " . $ua['platform'] . " reports: <br >" . $ua['userAgent'];

    ?>

    E para imprimir o resultado:

     <?php echo $ua['platform'] ?>

    ou imprimir tudo: 

     <?php echo $yourbrowser ?>

    Ele só não detecta se é mobile, coisa que poderíamos fazer perguntando a resolução.

  5. Olá, eu estava usando algo assim:

    ------------------------------------------------config.php-------------------
    $host_name = "localhost";
    $database = "usuarios"; // Change your database nae
    $username = "root";          // Your database user id 
    $password = "test";          // Your password

    //////// Do not Edit below /////////
    try {
    $dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
    } catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
    }

    --------------------------------------------------inc.login.php-------------------

    session_start();
    include ("config.php");

    $usuario = $_POST['usuario'];
    $senha = $_POST['senha'];

    if (!empty($usuario) AND !empty($senha)) {

        echo "Por favor, todos campos devem ser preenchidos! <br /><br />";
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"5; URL= ..\">";

    }

     else {


        $senha = md5($senha);

        /** @noinspection PhpDeprecationInspection */
        $sql = mysql_query("SELECT * FROM usuarios WHERE usuario='{$usuario}' AND senha='{$senha}' AND ativado='1'");
        $login_check = mysql_num_rows($sql);

        if ($login_check > 0) {

            /** @noinspection PhpDeprecationInspection */
            while ($row = mysql_fetch_array($sql)) {

                foreach ($row AS $key => $val) {

                    $$key = stripslashes($val);

                }

                $_SESSION['usuario_id'] = $usuario_id;
                $_SESSION['nome'] = $nome;
                $_SESSION['sobrenome'] = $sobrenome;
                $_SESSION['email'] = $email;
                $_SESSION['nivel_usuario'] = $nivel_usuario;
                $_SESSION['img_profile'] = $img;
                $_SESSION['user'] = $usuario;

                /** @noinspection PhpDeprecationInspection */
                mysql_query("UPDATE usuarios SET data_ultimo_login = now() WHERE usuario_id ='{$usuario_id}'");


                header("Location:../pagina/home.php");
                //echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL= ../dash.php">";


            }

        } else {
            header("Location:../");
        }
    }

    Encontrei alguns poucos exemplos na internet, e preciso verificar se o usuário esta ativado.

    INSERT INTO `usuarios` VALUES ('1', 'Nome', 'Sobrenome', 'email@email.com', 'user', '8e4441f86ad(senha)09db96e5459', 'Auto Autenticado', '(classe)', '2015-09-19 (data-cadastro)17:33:38', '2016-03-02(data-ultimologin)12:30:30', '(ativado=1)', 'assets/logos/iimg.png');

    No caso as sessões já estou mais safo, mas esse PDO está me matando.

    Como ficaria? Desde já muito obrigado

  6. Olá amigos, sou iniciante e quero produzir um script a qual use uma sessão para saber se o usuário esta online,

    Não importa em quantas maquinas esteja logado, eu só preciso saber qual o IP, o navegador, o sistema operacional e gravar seu ultimo acesso no banco de dados e por uma bolinha verde se online.

    Pra por no meu painel de controle pessoal.

    Por favor, me ajudem.

    Grato.

  7. Meus amigos, estou com uma dúvida cruel. Achei um pedaço aqui outro ali e montei esse script, mas não sei o que há de errado. E também quero compartilhar com a comunidade. Pode ajudar aos outros também.

     

    Script:

    <?php
    /*
    @autor: Gabriel Rodrigues de Moura
    @email: blx32@srmoura.com.br
    */

    // Função que valida o CPF
    function validaCPF($cpf)
    {    // Verifiva se o número digitado contém todos os digitos
        $cpf = str_pad(ereg_replace('[^0-9]', '', $cpf), 11, '0', STR_PAD_LEFT);
        
        // Verifica se nenhuma das sequências abaixo foi digitada, caso seja, retorna falso
        if (strlen($cpf) != 11 || $cpf == '00000000000' || $cpf == '11111111111' || $cpf == '22222222222' || $cpf == '33333333333' || $cpf == '44444444444' || $cpf == '55555555555' || $cpf == '66666666666' || $cpf == '77777777777' || $cpf == '88888888888' || $cpf == '99999999999')
        {
        return false;
        }
        else
        {   // Calcula os números para verificar se o CPF é verdadeiro
            for ($t = 9; $t < 11; $t++) {
                for ($d = 0, $c = 0; $c < $t; $c++) {
                    $d += $cpf{$c} * (($t + 1) - $c);
                }

                $d = ((10 * $d) % 11) % 10;

                if ($cpf{$c} != $d) {
                    return false;
                }
            }

            return true;
        }
    }
    // Verifica se o botão de validação foi acionado
    if(isset($_POST['btvalidar']))
        {// Adiciona o numero enviado na variavel $cpf_enviado, poderia ser outro nome, e executa a função acima
        $cpf_enviado = validaCPF($_POST['cpf']);
        // Verifica a resposta da função e exibe na tela
        if($cpf_enviado == true)
            
    // Script para enviar ao BD se CPF True.

    $host= 'localhost';
     $bd= 'pedidos';
     $senhabd= 'hackme';
       $userbd = 'root' ;
        // RECEBENDO OS DADOS PREENCHIDOS DO FORMULÁRIO !
     $nome    = $_POST ["nome"];    //atribuição do campo "nome" vindo do formulário para variavel     
    $email    = $_POST ["email"];    //atribuição do campo "email" vindo do formulário para variavel 
    $cpf= $_POST ["cpf"];    //atribuição do campo "cpf" vindo do formulário para variavel 
    $pedido    = $_POST ["pedido"];

    $tel= $_POST ["tel"]
        //atribuição do campo "telefone" vindo do formulário para variavel 
    $cep    = $_POST ["cep"];    


    //Gravando no banco de dados !   
    //conectando com o localhost - mysql 
    $conexao = mysql_connect($host,$bd, $senhabd); if (!$conexao)     die ("Erro de conexão com localhost, o seguinte erro ocorreu -> ".mysql_error());
     //conectando com a tabela do banco de dados $banco = mysql_select_db($bd,$conexao); if (!$banco)     die ("Erro de conexão com banco de dados, o seguinte erro ocorreu -> ".mysql_error());
      
    $query = "INSERT INTO `pedidos` ( `nome` , `email` , `cpf` , `pedido` , `telefone` , `cep` , `id` ) VALUES ('$nome', '$email', '$cpf', '$pedido', '$tel', '$cep', '')";   mysql_query($query,$conexao);  
     echo "Seu pedido foi realizado com sucesso!<br> Entraremos em contato.";

        elseif($cpf_enviado == false)
            echo "Por favor, insira um CPF valido.";
        }
    ?>

     

    E uma outra página em HTML enviando os dados para essa:

     

    <html>
    <head>
    </head>
    <body>
    <form action="valida_cpf.php" method="post" name="cpf" id="cpf">
      CPF: 
      <label>
      <input name="cpf" type="text" id="cpf" size="11" maxlength="11">
      </label><br>
    Nome:
     <label>
      <input name="nome" type="text" id="nome" size="" maxlength="">
      </label><br>
    Email:
    <label>
      <input name="email" type="text" id="email" size="" maxlength="">
      </label><br>
    Pedido:
    <label>
      <input name="pedido" type="text" id="pedido" size="" maxlength="">
      </label>
    <br>
    Cep:
    <label>
      <input name="cep" type="text" id="cep" size="11" maxlength="11">
      </label>

      <label>
      <input name="btvalidar" type="submit" id="btvalidar" value="  Enviar  ">
      </label>
    </form>
    </body>
    </html>

     

    Como posso fazer funcionar???

×
×
  • Criar Novo...