php/mysql: credit card validation isn't working - php

I tried to make this program that takes a credit card number and checks if it it valid or not and let the user know about it but in my program, i dont get echo message at all on clicking submit
<?php
session_start();
if (isset($_POST['submit'])){
$number=$_POST['cc'];
$total=0;
$i=1;
$last4= substr($number,-4,4);
$number=$str_split($number);
$number=array_reverse($number);
foreach($number as $digit){
if(i%2==0){
$digit*=2;
if($digit>9){
$digit -=9;
}
}
$total += $digit;
$i++;
}
if($total%10==0){
echo "Your credit card number ending in ".$last4." is valid";
}
else
{
echo "Your credit card number ending in ".$last4." is invalid";
}
}
?>
<html>
<head>
<title>Credit Card Number</title>
</head>
<body>
<form action="cards.php">
<input type="text" name="cc">
<input type="submit" name="submit">
</form>
</body>
</html>

Let's go over this, one step at a time.
Firstly, the following condition never gets met/satisfied, since you're using a POST array against a form that does not (specifically) contain a "post" method in it <form action="cards.php">.
if (isset($_POST['submit'])){
// ...
}
Since forms default to a "GET" method when "POST" was not implied, it needs to be included.
<form action="cards.php" method="post">
Next, we have the following error (pulled from and stated in comments):
"Notice: Undefined variable: str_split"
str_split() should have been declared as a function, rather than a variable.
$number=$str_split($number);
^ $ is a variable character
It needs to be removed:
$number= str_split($number);
And then we have the following error (also pulled from and stated in comments):
Use of undefined constant i - assumed 'i'"
That was caused by the missing $ for the "i" in if(i%2==0) and is first declared in $i=1;.
It looked for a constant of that name, and since it did not find one, it threw you that error.
Therefore, it should read as:
if($i%2==0)

Related

How can I let customers enter custom text on a Product Page and then charge per letter?

I am currently putting together a WordPress website, with WooCommerce being the preferred platform for eCommerce functionality.
The individual would like to have a field, on the Product Page, where people can enter a custom word. This custom word would be applied to the Product on the page.
Furthermore, the first 16 letters, within this custom field, would be included in the product price. Therefore, the charge would only apply to any letters after the first 16 letters.
I am assuming this would require work within the functions.php file.
Any suggestions on the required coding or steps I would need to follow, in order to achieve this?
I have never used WOOCOMERCE, and the question is asking for a php solution , but since this has to do with client input first i thought it may be better to use jquery on the client side to validate then pass the values to your php function to enter to your DB
you could run ajax calls on change too put that seemed a little too intensive
and a PITA
$(document).ready(function() {
$("#basePrice").on('change', function(e){
$('#word').keyup();
})
$('#word').on('keyup', function(e) {
length = $(this).val().length;
$('#wordLength').html(length);
if(length>=16){
$('#wordLength').addClass('greater');
total = parseFloat($('#basePrice').val()) + parseFloat((length - 16) * $('#priceperletter').val()) ;
$('#total').val(total);
}
else {
$('#wordLength').removeClass('greater');
total = parseFloat($('#basePrice').val());
$('#total').val(total);
}
})
})
label{
display:block
}
.greater{
border:1px solid red;
}
.totalLabel,.totalLabel * {
font-weight:700;
font-size:18px;
}
.totalLabel input{
border:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Base Price<input id="basePrice" value="10"/></label>
<label>Price per Letter over 16<input id="priceperletter" value = ".25"/></label>
<label>Enter your string<input id="word" type="text" /> <span id="wordLength"></span></label>
<label class="totalLabel" >Total $<input id="total" readonly value="10"/></label>
To count the character in string PHP strlen () function is used .
For example:
<?php
echo strlen('YourString'); //outputs 10
?>
<?php
$string='YourString';
echo strlen($string); //outputs 10
?>
For more refer Crackpoint PHP strlen () tutorial
So if you want to compare you can use like
if (strlen($description) >= 16) ){
// more then 16 characters
// We need to charge the user
} else {
// N
Your solution
<?php
// If form is submitted
if (isset($_POST['description']) && !empty($_POST['description'])) {
// Form is submitted, check length
$description = trim($_POST['description']);
if (strlen($description) >= 16)) {
// more then 16 characters
// We need to charge the user
} else {
// Not more then 16 characters, continue.
}
}
?>
<html>
... Your other code here ...
<form method='POST' action="$_SERVER['PHP_SELF']">
<input type='text' name='description' />
<input type='submit' />
</form>
</html>
Since this is a very generic question, and I can't comment only post an answer I'll just try and help out here.
if strlen($description >= 16) {
// more then 16 characters
// We need to charge the user
} else {
// Not more then 16 characters, continue.
}
W3Schools: https://www.w3schools.com/php/func_string_strlen.asp
PHP Site: http://php.net/manual/en/function.strlen.php
As per the comment below. Here is a mockup just for demonstration. I'm not sure how all of your site is setup, so I can't exactly make it work copy&paste for you. I'm not sure entirely how WooCommerce is setup in terms of payment.
<?php
// If form is submitted
if (isset($_POST['description']) && !empty($_POST['description'])) {
// Form is submitted, check length
$description = trim($_POST['description']);
if strlen($description >= 16) {
// more then 16 characters
// We need to charge the user
} else {
// Not more then 16 characters, continue.
}
}
?>
<html>
... Your other code here ...
<form method='POST' action="$_SERVER['PHP_SELF']">
<input type='text' name='description' />
<input type='submit' />
</form>
</html>
Again, this isn't ready for copy & paste. I know people on this forum are very particular and judgemental so please beware it's a mockup. You will need to ensure the input is secure and safe etc. I'm not sure how to directly hook into woocommerce so I apologize if this is just a waste of your time.
It's my first legitimate answer, be nice.

Get input from HTML form in PHP

I'm learning MySQL and PHP and got a problem with the input of the form. So I wrote a small test code, but it still cannot work. My PHP version is 5.6.
The code:
<html>
<body>
<form action ="2.php" method ="post">
Name: <input type="text" name="username" />
<input type ="submit" value="ok" />
</form>
</body>
</html>
and
<html>
<?php
if(isset($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
The output of the project is always error, can't output the input before.
I tried single quote and double quote for username, both can't work.
I also tried to set always_populate_raw_post_data in php.ini to 0, -1, 1, all can't work.
I don't know where the problem is, though it might be very silly.
As what it look it is correct and should run without any problem. Make sure the above code is what you actually have. From my experience most of the form submission can be
you don't have correct name (username)
you might send incorrect http verb (post)
you submit to wrong endpoint (2.php)
From you code above everything look fine. if you still don't have the right result, you better debug it with var_dump, or print_r function with these built-in
$_POST, $_GET, $_REQUEST and check whether they contains you form variable name username
You are using isset as a variable, but it is a function that returns a boolean.
Change $user=isset($_POST['username']); to $user=$_POST['username'];
Another thing is that in both case you will end up in the IF condition even if there is no value added to the field so you can do something like this too:
<html>
<?php
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>

Php script find square root of a given number error

I simple php program that returns the square root of a number, although when I echo the results, I get the following error and I am tired, so Im probably missing something really small here.
Code:-
<!DOCTYPE html>
<html>
<head><title>Task 2</title></head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class square
{
public $num=null;
public $objRes=null;
function processRequest()
{
$this->square=$_REQUEST['num'];
}
function run()
{
if(isset($_REQUEST['submit']))
{
$this->processRequest();
$this->objRes=sqrt($this->square);
}
}
}
$objSquare=new square();
$objSquare->run();
?>
<form action="task2.php" method="POST">
Enter the number:<input type="text" name="num"/>
<input type="submit" value="Submit">
</form>
<?php
if($objSquare->res!=0) {
echo "Square root of a given number is ".$objSquare->objRes." ";
}
?>
</body>
</html>
Heres my error:-
Notice: Undefined property: square::$res in /Applications/MAMP/htdocs/test/task-2/task2.php on line 46
Change $objSquare->res to $objSquare->objRes because that's the name of your square class property.
I know it's not what you asked for. But sometimes people don't know they wanted something until they have it.
Example using sqrt()
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...

ISSET function undefined variables variables

Hello i have problem with isset id like someone to help me fixin this problem. Its this problem Notice: Undefined variable: v in C:\xampp\htdocs\something\something2.php on line 17 and my code is :
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php IF (isset($_POST['v'])) {
$_POST['v'];
}
?>
<label>r:</label><input type="text" name="r"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo 2*$v;?> cm</label>
</form>
EDIT:
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php If (is_numeric($_POST['v'])) {
$v = $_POST['v'];
}
?>
<label>v:</label><input type="text" name="v"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo 2*$v;?> cm</label>
</form>
and im getting these errors
Notice: Undefined index: v in C:\xampp\htdocs\something\something2.php on line 11 and Notice: Undefined variable: v in C:\xampp\htdocs\something\something2.php on line 17
What's actually happening with that error is that your variable $v isn't being initialized because the code has not enter the if condition.
if(is_numeric($_POST['v'])){
$v = $_POST['v'];
}
You're assuming that the condition is_numeric($_POST..) is true but it might not be, which means that the variable $v is never initialized. Therefore is pretty normal the error you are having.
You can continue with your condition but you must check for the variable after it.
if(is_numeric($_POST['v'])){
$v = $_POST['v'];
}
echo 2 * (isset($v) ? $v : 1);
The above code might be improved. A better code/logic would be you to set up the default value of the variable in case the is_numeric returns false.
$v = 1; // default value
if(is_numeric($_POST['v'])){
$v = $_POST['v'];
}
echo 2 * $v;
What is happening is that your value v is not the same as the implied value of $_POST['v'] . As stated by Tim, there is no $v = statement so in effect your echo output is outputting nothing multiplied by 2.
This throws a warning which you have picked up.
So a solution could be:
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php If (is_numeric($_POST['v'])) {
$v = $_POST['v'];
}
?>
<label>r:</label><input type="text" name="r"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo 2*$v;?> cm</label>
</form>
I have used is_numeric as you are using the echo to produce a value x 2 so makes more sense to check V is a number rather than a string.
UPDATE
Ok, first stop then is to see what is on line 11? is it $_POST['v'] ? If so then you can work back to the source of the cause - replace the line 11 (comment it out, don't delete it) with something like:
print_r($_POST);
This will output all values associated with the array $_POST.
If you do not see a value for 'v' (and I guess you probably won't) then that means this value wasn't set in the previous HTML page so go back and check that your form submits an input such as:
<input name='v' value="something">
Undefined index means the array ( $_POST ) does not contain any information stored under $_POST['v'].
Can you confirm your POST is as intended, and that you do want post which means you need to submit the form rather than GET or another method, such as index.php?v=10 ?
The Notice:
PHP does have notice statements but they're only notices, they are not errors or even warnings, it's just PHP telling you what's going on. This will not break your code, but it could be nice to add this line above your IF statement:
$v = 0;
This establishes the variable $v and gives it a value. Which if $_POST['v'] exists is then updated to reflect that.
Your code must be like this.
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php
$v = '';
If (is_numeric($_POST['v'])) {
$v = $_POST['v'];
}
?>
<label>v:</label><input type="text" name="v"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo (($v)? 2*$v : 'Its not numeric value');?> cm</label>
</form>

Can't retrieve data from session variable - PHP Number guessing game

I am building a number guessing game and need to create a session variable to hold the randomized target number until the user submits the correct guess. I also need to print the number of attempts after the user submits the correct answer.
I set my session variable and used a hidden field to hold the counter. I don't know if the hidden field works bc when I submit a guess, my code prints out the first if statement of the check() function..ALL THE TIME.
I think it has something to do with the session variable (and of course my code), but I can't figure it out. I've been working on this for two days now and feeling the frustrations. Any help would be amazing. Here's my full code below:
<?php session_start() ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Number Guessing Game</title>
</head>
<body>
<h1>Guess the number</h1>
<p>I'm thinking of a number between 1 and 5. Can you guess what it is?<br>
In less than 3 tries?</p>
<?php
extract($_REQUEST);
error_reporting(E_ALL & ~E_NOTICE);
// check to see if this is start of game
if (filter_has_var(INPUT_POST, "guess")) {
check();
} else {
setTarget();
} //end if
// set targetNum session variable
// increment counter by 1
function setTarget() {
$targetNum = rand(1, 5);
$_SESSION["targetNum"] = $targetNum;
$counter++;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
}
function check() {
global $counter;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess"
value= "$guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
if ($guess == $_SESSION['$targetNum']) {
print "<h3>Awesome. You guessed it in $counter attempt(s)</h3>";
unset($_SESSION["targetNum"]);
$count = 0;
print "<a href='numberGuessingGame.php'>TRY AGAIN</a>";
} else if ($guess > $_SESSION['$targetNum']) {
print "<h3>Too high. Guess again.</h3>";
} else if ($guess < $_SESSION['$targetNum']) {
print "<h3>Too low. Guess again.</h3>";
} else {
print "I don't know what that is...";
}
}
?>
</body>
</html>
You made two basic, but severe errors.
First: DO not set the error level to exclude notices when developing! That way you will never spot typos in variable or array index names. Remove error_reporting(E_ALL & ~E_NOTICE);, or replace it with error_reporting(E_ALL);.
Second: You use extract($_REQUEST); - using that function is asking for trouble. PHP has a long history of security vulnerabilities because of the "register_globals" feature, which introduces global variables just because some key=value pair in the request data was parsed. It took years to remove that feature. You are re-implementing it without any security precaution by using that function, and with no real benefit.
Remove that extract($_REQUEST); function, and use $_REQUEST['varname'] instead of $varname for all variables that come from the remote browser.
Your $guess variable is never set to the POST value (Correction: you're using extract but I'd advise against it). You are also changing the value of your session array key when you add a '$':
$guess = $_POST['guess'];
if ($guess == $_SESSION['targetNum']) {

Categories