PHP/HTML - isset function - php

I'm fairly new to PHP and am creating a website for my company. I am using some existing code that I have obtained but can't seem to make it work properly - any help would be much appreciated!
I have a variable, $id, which identifies the product category type to display on the page. I first need to check that the id variable has been set and if not, default the variable to category 0.
The code I have is as follows:
setdefault($id, 0);
function setdefault(&$var, $default="")
{
if (!isset($var))
{
$var = $default;
}
}
So with the address www.website.com/browse.php, I would expect it to default to $id=0; with the address www.website.com/browse.php?id=3, I would expect it to set $id to 3 and display the relevant products. However, despite setting $id, it still defaults to 0. Is there something obviously incorrect with my code?

You are probably expecting PHP to use the $_POST and $_GET as global variables. PHP used to be setup this way, back in the day, but newer versions require you to explicitly reference these variables.
You could try this:
setdefault($_GET['id'], 0);
function setdefault(&$var, $default="")
{
if (!isset($var))
{
$var = $default;
}
}
or even more simply (using the ternary operator):
$id = array_key_exists('id', $_GET) ? $_GET['id'] : 0;

First off, if this is PHP 5.X I highly recommend you do not pass variables by reference using the &. That being said. the isset function call will always be true withing the function. But you will receive an undefined variable warning on the setdefault($id, 0);
Try this instead.
$id = isset($id) ? $id : 0;

If $id is not set, the call to setdefault($id,0) will generate a warning. A function like setdefault does not work in PHP. Use this instead.
if (!isset($id)) $id = 0;
If you are doing this for array variables, like $_GET and $_POST, you can do this:
function getuservar($A, $index, $default = '') {
if (!isset($A[$index])) return $default;
if (get_magic_quote_gpc()) return stripslashes($A[$index]);
return $A[$index];
}
$clean_id = getuservar($_GET, 'id', 0);
This return form is better because you stop using the $_GET array immediately and only use the variables that are cleaned in the rest of the code. You clean your external variables once and never touch the external variables again in your code. $A can be $_GET, $_POST, $_REQUEST or $_COOKIE.
It also handles the annoying magic_quote stuff for you so you know the data in the variable is the text sent by the user. Just remember to clean it again when sending it back to the user or to the database.

How is $id being set? If register_globals is off (and it's off by default in PHP 4.2 and newer), you need to look at $_GET['id'] or $_POST['id'] instead (or $_REQUEST['id'], but there are reasons to avoid that).

The code to set $id to sometime from the query string (browse.php?id=3) would also need to be included. You might be thinking of the register_globals settings that PHP has that will automatically create variables when included in the query string. DO NOT re-enable that feature, for several years now that has been shown to be a really bad idea.
Any variable you are pulling from the query string needs to be checked for type/safety before using it. So for example you might pull the variable from the $_GET super global, check to see if it's numeric, if it is not then set the default:
if (!is_numeric($_GET['id']) {
setdefault($_GET['id'], 0);
}

Related

Cant set session variable to stable value on reloading the page

I'm making a php app. I used sessions for splitting users
for example:
<?php
session_start();
?>
<?php
$_SESSION["color"] = random_int(1, 2);
?>
I want to became a not changeable and unique value but on refresh it would change its value.
For example:
1,2,1,1,2,1,2,2,1
please help.
PHP session variables are not immutable. You will need to check for the value being set already before setting it to something else. Notice that isset will only work for variables that are not null, array_key_exists maybe more suitable depending on what data is being stored.
if (!isset($_SESSION["color"])) {
$_SESSION["color"] = random_int(1, 2);
}

Checking unsanitized POST values

I am just starting PHP and have a form where users can submit data. Before I display or send the data, it is sanitized and validated (trim, stripslashes, and htmlspecialchars) and saved as new variables which are then used instead of the directly submitted values.
My question is, is it safe to do anything at all with the unsanitized values? Do the security implications only become apparent when the values are displayed?
Specifically, would there be any problems with doing code such as
if(empty($_POST["theirname"]){code;}
if they tried some kind of attack or placed code into that box while submitting?
Currently I sanitize all input before checking if they are empty, but I want to avoid errors/warnings in this case if a user submits a blank box for example (as the sanitizing function could be called on POST values that don't exist)
PHP's filter_* functions. They're functions that do sanitizing for every variable you have, be it server variables (like $_SERVER, $_GET, $_POST, $_REQUEST) or your own variables.
Since you want to sanitize $_POST, here's what you should use:
$theirname = filter_input(INPUT_POST, "theirname");
if (!$theirname) {
echo "theirname is invalid!";
} else {
// your code
}
filter_input can check if the variable exists, if it's empty, and if it has anything that can make your code/website vulnerable (HTML tag injection, JS code injection, PHP code injection by evaluation, etc.). It's way better than checking it by yourself.
Of course, you can always just check it by yourself if you decide not to trust the filter_* functions, in that case you need to:
Check if the variable exists by using is_null and/or checking against NULL;
Check if the variable is empty;
Check if the variable has special characters (and escape them properly);
Check if the variable has HTML or XML tags (and escape/delete them);
Check if the variable has JS code or script tags (and escape/delete them);
Check if the variable has PHP code and if it's trying to execute it via eval;
As you can see, it's an extensive list, and if you don't want to rely on PHP's built-in functions, that's what you need to do.
Sources:
PHP: Filter Functions - Official PHP docs
PHP 5 Filter functions - W3Schools
always check for undefined variables first.
if(!is_null($_POST["theirname"])){
if(empty($_POST["theirname"]){code;}
}
It is absolutely required to check for existence for any variable.
$bingo = isset($variable);
Normally you want to first check if a variable is defined at all. You can do this by if(!is_null($_POST["theirname"]))
If it is defined, then you maybe want to check if it is empty, and if not, do some stuff. (for example sanitizing and / or validating)
if(!is_null($_POST["theirname"])){
if(!empty($_POST["theirname"])
{
//Do some stuff here
}
else
{
//send notification that the user didn't input any data
}
}
The error in your example is you have missing ) in your if judgment.
//Your code
if ( empty($_POST["theirname"]) { code; }
^^
//Code updated
if (empty($_POST["theirname"])) { code; }
Before checking if your inputs are empty, you could check if your form is defined and is not NULL.
Example:
//Reset.
$msg = $theirname = NULL;
//Check if the form is defined.
if (isset($_POST)) {
//Check input empty.
if(empty($_POST['theirname'])) {
$msg = 'Inputs are required';
} else {
$theirname = data_filter($_POST['theirname']);
}
//check $theirname.
if ($theirname) {
//Do something with $theirname...
}
}
//Filter function.
function data_filter($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Message.
echo $msg;
Checkout filter_var and filter_input.

Create a variable in one function and pass it to another in PHP

Let me first say I've spent a day reading three google pages of articles on this subject, as well as studied this page here.
Ok, here's my dilemma. I have two functions. Both called upon via AJAX. This first one assigns a value to the variable and the second one uses that variable. Both functions are triggered by two separate buttons and need to stay that way. The AJAX and the firing off of the functions work fine, but the variable isn't passed. Here is my code:
if( $_REQUEST["subjectLine"] ) //initiate first function
{
$CID = wpCreateChimpCampaign();
echo $CID; //this works
}
if( $_REQUEST["testEmails"] ) //initiate second function
{
echo $CID; //does not return anything but should contain "apple"
wpSendChimpTest($CID);
}
function wpCreateChimpCampaign () //first function
{
$CID = "apple";
return $CID;
}
function wpSendChimpTest ($CID) //second function
{
echo $CID; //does not return anything but should contain "apple"
}
I'm open to using a class but I haven't had much luck there either. I was hoping to solve this issue without using classes. Thanks for the help in advance!
If you are making 2 separate calls to this file, it may be helpful for you to visualise this as being 2 functions in 2 totally separate files. Although they exist in the same PHP file, because they used called in different calls, they don't retain the value of the variable $CID. Once the file has run, the variable is destroyed and when you call the file again, the value is null again.
So you need to store that variable between calls. You can either store it in a database or store it in a session variable.
So call session_start(); at the beginning of the file, then rather than use $CID, just use $_SESSION['CID'];
I'm not sure where the hold up is. The code you have will work:
$CID = wpCreateChimpCampaign(); // returns 'apple'
wpSendChimpTest($CID); // echos 'apple'
The code looks fine, but are you certain that all requirements are being met so both functions execute?
In other words are you supplying values for both $_REQUEST["subjectLine"] and $_REQUEST["testEmails"]?

PHP undefined index error when clicking a url and invoking a php script

I have a call to a PHP script from my home page which I do like this:
echo 'Delete';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}

PHP $_SESSION variables not storing values

I'm trying to use PHP session variables to carry data over multiple pages. I am using session variables on many parts of my site, but this is the first place where they don't work.
I'm setting it like this:
$_SESSION["savedRetailerName"] = $foo;
And calling it like this:
echo $_SESSION["savedRetailerName"];
The session id remains the same between these two pages, and I'm sure that I'm setting the variables right and that they are being called right. I start the session correctly, and even on that particular page, other session variables are being shown properly.
How can I begin to debug this odd behavior?
Edit:
There are two different pages I'm currently dealing with. Page 2 sets the session variables, and there is a button that will return the user to Page 1. The idea is to still have the fields in Page 1 filled in if the user wishes to return to Page 1.
It is not a cache problem, and I can return other session variables in the exact same spot in my code as where I am failing to return these variables.
The only other code that may be pertinent is the back button handler (jQuery):
$('#backButton').live('click',function() {
window.location.replace("page 1");
});
Edit 2:
I believe this isn't working because of something with variables here:
<?php
$retailerName = $_REQUEST["retailerName"];
$description = $_REQUEST["description"];
$savingsDetails = $_REQUEST["savingsDetails"];
$terms = $_REQUEST["terms"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$zone = $_REQUEST["zone"];
$dateExp = $_REQUEST["dateExp"];
$tag = $_REQUEST["tag"];
$_SESSION["rn"] = $retailerName;
$_SESSION["de"] = $description;
$_SESSION["sd"] = $savingsDetails;
$_SESSION["tm"] = $terms;
$_SESSION["ph"] = $phone;
$_SESSION["ad"] = $address;
$_SESSION["zo"] = $zone;
$_SESSION["ex"] = $dateExp;
$_SESSION["tg"] = $tag;
?>
I am able to set any session variable to a string, but it won't set to a variable.
You want to use session_start before you set or use any session variables. You only need to call it once.
If it's working in other places, odds are that this particular block of code is being executed before session_start is called.
remove all non printable characters before <?php
you may not see them..
You have spaces before your <php tag
You don't have session_start() anywhere
You are using the $_REQUEST variable which is sketchy (use $_GET or $_POST instead)
You would also need to register the session using
session_register # php.net

Categories