how to add a parameter to the url in php? - php

I'm trying to add the parameter cs with a value of 1 to the url using a form and hidden type input. When I execute this, I have a simple if statement that checks to see if $_GET['cs'] is = to 1, but I get a Notice: Undefined index. I'm a php beginner, any help, explanations, or alternatives is very much appreciated.
echo '<form>';
echo '<input type="hidden" name="cs" value="1">';
echo '</form>';
if($_GET['cs'] == 1) {
echo'working';
}
else {
echo 'not working';
}

Only after form is submitted you will see 'cs' in $_GET array.
The $_GET array contains all parameters on the URL line.
For example if a URL is: https://example.com?param1=1&param2=2
You will get a $_GET array with two entries ('param1' and 'param2') with values 1 and 2.

You should add a check using the isset function (https://www.php.net/manual/en/function.isset.php). Otherwise it will try to access the parameter if it isn't sent. In your case the parameter was probably not sent.

Url in html:
test the get method
The url test
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
Full code:
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get varaible</title>
</head>
<body>
test the get method
</body>
</html>

Related

How to add GET and remove

I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query

Why using operator in front of function?

I started learning PHP 1 week ago, i'm making some form tests to get more apprehension on the language, i get stuck in problem small problem for you guys....
I used in_array function from the PHP manuale to check an array off names at login
The function did not work to check the array tell i add !in_array !!!
Normal in_array did not work to check for names ...
So I used blaindly the operator "!" in front of the function, so why did it work with that operator and not without it ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forum</title>
<meta name="Nic" content="" />
<link rel="stylesheet" type="text/css" href="style.css"> </head>
<body>
<?php
if(isset($_POST['submit'])){
$names = array("Nicolaus", "Solo", "Yiu", "Yang", "Darius");
$minimum = 5;
$maximum = 10;
$username = $_POST['username'];
echo '<br>';
$password = $_POST['passwoard'];
if(strlen($username) < $minimum){
echo 'Username needs to be longer then 5 carcaters !';
}
if(strlen($username) > $maximum){
echo "Username can't be longer then 10 carcaters";
}
if(!in_array($username, $names)){
echo "You are not alowed , not in database !";
} else {
echo 'Welcome';
}
echo '<br>';
echo 'Your Username is : ' . "<b>" . $username . '</b>';
echo ' Your Password is : ' . "<b>" . $password . '</b>';
}
?>
<form action="my_from.php" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="passwoard" placeholder="password">
<input type="submit" name="submit"> </form>
</body>
Ty
! means NOT, its an operator to make comparisons when you want to check if something is false.
$raining = false;
if (!$raining){
echo "its not raining";
}
Now that you posted your code:
if(!in_array($username, $names)){
echo "You are not allowed , not in database !";
} else {
echo 'Welcome';
}
in_array is a function that checks if some value is inside an array. You are testing if $username is inside $names array.
Your conditional checks if $username is NOT in array, if so, it means that $username is not allowed because it doesn't make part of the permitted $names.
Your ELSE clause identify that it is in the array, and then the user is able to login.
you can invert your logic:
if(in_array($username, $names)){
echo 'Welcome';
} else {
echo "You are not allowed , not in database !";
}
And it will work as well.
! symbol is used for negating the logic of the function.
What you actually want to do is, you want to reject an user with $username, if his/her name is NOT in the $names array. You have got a function to check whether an element is present in an array. So adding ! operator to it negates the logic.
if (!in_array($username, $names))
That means if the $username is NOT present in array $names.
Using ! is similar to checking with condition == FALSE. But we can't directly use that logic on that function so we opted for ! operator.
Another alternative for your example without ! is,
if (in_array($username, $names)) {
echo "Welcome";
} else {
echo "You are not alowed , not in database !";
}
Hope this helps! :)

How to validate php if form is filled

//So i have a php validation external and a html file. I'm trying to validate if //the input boxes are filled out correctly... so far i have one but I can't get it //to run and i tried testing it out doesn't work... do i need to download //something or is my code completely wrong. I just trying to check if its empty and if it has at least 3 characters
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cal5t</title>
</head>
<body>
<?php
$title= $_REQUEST["title"];
if ($title == "" or >3 ) {
echo "<p>5please!</p>";
?>
</body>
</html>
You are probably looking for something like:
if (($title == "") or (strlen($title) < 5))
{
echo "<p>5please!</p>";
}
if(!empty($title= $_POST['title']) && strlen($title) > 5){
echo "valid: $title";
} else {
echo "incorrect title: '$title'";
}
Also, its beter to use $_POST or $_GET over $_REQUEST.
I think you're looking for:
if(strlen($title) < 5){
echo '<p>The title you entered is not long enough.</p>";
}
You can make sure there is a value with the isset() function.
requird validation
$title = trim($_POST['title']); // it will remove stat and end spaces
if(strlen($title) <= 0)
{
echo "Title Field is required";
}

PHP code for calculator. validated but not working

So I have a calculator coded in PHP and I have validated it but there is a problem with this, its not working. I have used server side validation. Validation works well. But it doesn't do any work,for example, when I give an input like 2+8, it gives an output of 8888. This is very confusing. Please help me out with this. Thanks.
HTML page is here:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form method = "post" action = "calc.php">
<input type = "text" name = "val_1"/>
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "text" name = "val_2"/>
<input type = "submit" value = "calculate" name = "checker"/>
</form>
</body>
</html>
And here is the PHP code.
<?php
if(isset($_POST['checker'])) {
#Clean all values
function cleanStr($str){
$str = trim($str);
$str = addslashes($str);
$str = htmlspecialchars($str);
return $str;
}
$val_1=cleanStr($_POST['val_1']);
$val_2=cleanStr($_POST['val_2']);
$operator=$_POST['operator'];
function emptyFileds($ar){
if(!is_array($ar)){
echo "It must be an array";
return false;
}
#loop through each field to check for empty values
foreach($ar as $key => $value){
$value = CleanStr($value);
if(empty($value)){
echo $key . " must not be empty";
return false;
}
}
return true;
}
if(!emptyFileds($_POST)){
exit();
}
if($operator==="+"){
echo "Sum is " . $val_1+$val_2;
}
}
?>
Please change the original line
echo "Sum is " . $val_1+$val_2;
to
echo "Sum is " . ($val_1+$val_2);
It's a operator precedence issue as . is executed first. Therefore you append 2 to "Sum is " and then increment the string by 8 which results in this odd behavior.
Also, some nitpicking on your code, I will just name 3 issues:
requesting a parameter with cleanStr() is not a good idea, it's better to use
$val_1 = (int)trim($_POST['val_1']);
as $val_1 will be an integer after that line. This might be important for later development e.g. to compare numbers.
indent correctly, reading your code is hurting my eyes
the whole emptyFileds()thing is unnecessary, simply check whether the 3 parameters are filled or not, it's simple and it's readable.

PHP - Having a placeholder 'echo' so to speak

<?
//LUHN ALGORITHM PHP CONVERSION
// CREDIT CARD NUMBER CHECKER BY JACK BELLAMY - JACKBELLAMY.CO.UK
//----------- RETREIVE THE STRING FROM THE FORM POST -------------//
$var = $_POST['cardnumber'];
//----------- SPLIT THE 16 CHARACTOR STRING INTO INDIVIDUAL CHARACTERS AND ASSIGN TO INDIVIDUAL VARIABLES ---------------//
$n0 = $var[0];
$n1 = $var[1];
$n2 = $var[2];
$n3 = $var[3];
$n4 = $var[4];
$n5 = $var[5];
$n6 = $var[6];
$n7 = $var[7];
$n8 = $var[8];
$n9 = $var[9];
$n10 = $var[10];
$n11 = $var[11];
$n12 = $var[12];
$n13 = $var[13];
$n14 = $var[14];
$n15 = $var[15];
// ---------------------CHECKING THE CARDNUMBER FORM POST SUBMITS ALL VALUES PROPERLY
/*
echo $n0;
echo $n1;
echo $n2;
echo $n3;
echo $n4;
echo $n5;
echo $n6;
echo $n7;
echo $n8;
echo $n9;
echo $n10;
echo $n11;
echo $n12;
echo $n13;
echo $n14;
echo $n15;
*/
//-------ASSIGNING THE NEW VARIABLE VALUES ------------//
$n14_new = ($n14*2);
$n12_new = ($n12*2);
$n10_new = ($n10*2);
$n8_new = ($n8*2);
$n6_new = ($n6*2);
$n4_new = ($n4*2);
$n2_new = ($n2*2);
$n0_new = ($n0*2);
//!-----!------!//
//------------------------TESTING WITH THE NEW VARAIBLE *2
/*
echo $n0_new;
echo $n1;
echo $n2_new;
echo $n3;
echo $n4_new;
echo $n5;
echo $n6_new;
echo $n7;
echo $n8_new;
echo $n9;
echo $n10_new;
echo $n11;
echo $n12_new;
echo $n13;
echo $n14_new;
echo $n15;
*/
//--------- THE MATHS FOR THE COMPLETE SUM ------------ //
$isitlegit = ($n0_new+$n1+$n2_new+$n3+$n4_new+$n5+$n6_new+$n7+$n8_new+$n9+$n10_new+$n11+$n12_new+$n13+$n14_new+$n15);
//!----MATHS-----!//
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="veri-styles.css"
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div id ="verification-wrapper">
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<div id="input-holder">
<input name="cardnumber" type="text" class="input-style" placeholder=""> </input>
<button class="button-style">Verify my card</button>
</div>
</form>
<div class="result-class">
<?php
if(isset($isitlegit) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($isitlegit) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} elseif(!isset($isitlegit)) { // make sure this is not set
$new = "<img src='card-number-required.jpg' />";
}
echo $new;
?>
</div>
</div>
</div>
</body>
</html>
You have three states you need to account for, 'open', 'correct', and 'incorrect' To do that you start with an 'open' state.
$new = "<img src='please_enter your card number.jpg' />";
echo $new;
You would use that in the first condition of your test -
if(isset($var) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($var) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} else { // the default view
$new = "<img src='please_enter your card number.jpg' />";
}
echo $new;
Once submitted you can only have one of two states, never to return to the default.
In addition you have left your stylesheet declaration un-closed. Please change it to this -
<link rel="stylesheet" type="text/css" href="veri-styles.css" />
if(false===$submitted){
echo "Please type your card details here";
} else {
if($isitlegit % 5 == 0) {
$new = "<img src='correct.jpg' />";
echo $new;
}
else {
$new = "<img src='incorrect.jpg' />";
echo $new;
}
}
The best way I can think of to achieve this is with AJAX. Create a div on your page where your initial message is displayed, and then use an AJAX call to submit the form data to a script you'll use to validate it, and within that script, echo either a "Success! Your card has been verified" or a "Unable to validate your card" message. Then have your AJAX function change the .innerHTML of the div to the responseText element. You can see this answer for a good starting point, as well as a note about using the jQuery library to simplify your AJAX implementation.
Edit: In response to another user's downvote, here's some code.
First, let's give your HTML form a call to an AJAX object we'll create. So change your HTML form code to this:
<form onSubmit="return process()">
process() is a javaScript function we're going to set up later with the AJAX call. You already have a div established where you want this data to appear, but we need to give it an id, so change:
<div class="result-class">
please enter your card number<img src='correct.jpg' />
</div>
to this:
<div class="result-class" id="result">
Please enter your card number.
</div>
And also assign an id to your text input:
<input name="cardnumber" type="text" class="input-style" placeholder="" id="cardnumber"> </input>
Now we'll create the javaScript function. (This is easier with jQuery, but I wrote it in plain javaScript so you won't need the dependancy if you're not familiar with how to use jQuery.
function process(){
var xmlhttp = new XMLHttpRequest();
var cardnumber = document.getElementById("cardnumber").value;
var result = document.getElementById("result");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
result.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","validate.php?cardnumber=" + cardnumber,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
return false;
}
Now, use whatever php script you were going to use to validate the cc# and save it as a separate script called validate.php Use $_GET['cardnumber'] variable to fetch the cardnumber data sent from the form, run it through whatever validation process you are using. Use an if statement to create the responseText element for our AJAX function. You might have your script set some variable to boolean true or false to check this. I'll use $validated here.
if($validated){
echo 'Your card has been verified!';
} else {
echo 'Unable to validate your card.';
}
The AJAX function will change the text inside the "result" div to whatever text is echoed by your validate.php script.
This should get you on the right track, barring any syntax errors, I just wrote this all off the cuff.

Categories