I am passing the following variables from a query through a link:
<a href="middle.php?name=<?php echo $name; ?>&id=<?php echo $id1; ?>&rowid=<?php echo $rowid; ?>&record=<?php echo $record; ?>">
The variables are being passed to this page:
session_start();
//$id = ($_GET['id']);
if (isset($_GET["record"])) {
$_SESSION["record"] = $_GET["record"];
}
if (isset($_GET["id"])) {
$_SESSION["id"] = $_GET["id"];
}
if (isset($_GET["rowid"])) {
$_SESSION["rowid"] = $_GET["rowid"];
}
if (isset($_GET["name"])) {
$_SESSION["name"] = $_GET["name"];
}
if (isset($_GET["store"])) {
$_SESSION["store"] = $_GET["store"];
}
and then users are redirected to this page where Im trying to use the assign the session variables to variables in the page like this:
session_start();
$id = $_SESSION[id];
$rowid = $_SESSION[rowid];
$name = $_SESSION[name];
$record = $_SESSION[record];
The variables arent accessible as I need them to be on this page. Am I missing quotes? What is the best way to use the session variables again?
FYI they're mainly being used in other queries like this:
"SELECT * FROM mgap_orders WHERE mgap_ska_id = '" . $_SESSION['id'] . "' AND mgap_status = 0 GROUP BY mgap_ska_report_category LIMIT 5";
Am I missing quotes?
Yes. You say you're accessing them like this:
$id = $_SESSION[id];
That should be this:
$id = $_SESSION['id'];
But even more to the point, why do you need to use session here at all? The way you describe the situation is:
User makes a request with query string values in the link.
In the response you forward the user to another page (presumably using the location header?).
On the last page the values need to be present.
If they're query string values, keep them as query string values in the redirect. So where you may have something like this:
header('Location: somePage.php');
you can include the values:
header('Location: somePage.php?name=' . $name');
and so on for the remainder of the values, just like you do when building the original link for the page which performs the redirect.
Also, while you don't show your data access, you do show your query which appears to be vulnerable to SQL Injection attacks. Ultimately the values you're using are coming from user input (query string) so you shouldn't directly concatenate them into SQL queries.
Related
I have this code which permits me to pass a variable to another page, but the problem is i cannot seem to get that variable using the link. We have tried before, this same method and has worked.. could you please check it?
Thanks..
The link:
$sql="SELECT * FROM pianificazione";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['job'] ?>
<?php echo '</br><br />'; }
?>
The page after the link:
include('menu.php');
$id=$_GET['job_id'];
$sql="SELECT * FROM attivita WHERE job_id='$id'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['attivita_da_promuovere'] ?>-<?php echo $row['attivita_tip_merc'] ?>-<?php echo $row['attivita_da_svolgere'] ?>-<?php echo $row['attivita_tip_personale'] ?>
You should be using:
$id = $_GET['id'];
You're also open to SQL injections... Either parse it as an INT:
$id = (int) $_GET['id'];
... or use prepared statements with PDO (instead of the default mysql functions that you're using, which are no longer recommended).
You're passing it as:
lista_attivita.php?&id=<?php echo $row['job_id'] ; ?>
And then looking for it as:
$id=$_GET['job_id'];
You should use:
$id=$_GET['id'];
In the URL that you're passing to the "page after link" you're setting "?id=xxx" as the parameter however in your script, your looking for "job_id".
Change the parameter to ?job_id= in your first script.
Two things.
1) FUNCTIONALITY
$id=$_GET['job_id'];
should be
$id=$_GET['id'];
since your link passes the variable id, not job_id:
lista_attivita.php?&**id**=<?php echo $row['job_id']
2) SECURITY
Never, NEVER insert user-input data directly into a SQL query. You are asking for headaches or worse. The $id on your receiving page should be validated and escaped prior to doing any lookup. If you expect a number, do something like this on the receiving page:
if (!is_numeric($_GET['id']))
{
// throw error
}
It's not a bad idea to query your DB for valid codes, put those in an array, then check that array to see if the passed value is found. This prevents user entered data from reaching your DB.
Something like this:
$q = "SELECT DISTINCT(id) FROM my_table WHERE display=1 ORDER BY id ASC";
$res = mysqli_query($dbx,$q);
while (list($_id) = mysqli_fetch_array)
{
$arr_valid_id[] = $_id;
}
Then,
if (in_array($_GET[id],$arr_valid_id[])
{
// do stuff
} else {
// throw error
}
I have the following login script, where i do use sessions.
<?php
session_start();
if(isset($_SESSION['logged_in'])){
$id = $_SESSION['id'];
header("Location: start.php?id=$id");
exit();
}
if(isset($_POST['submit'])){
$x1 = $_POST['x1'];
$x2 = $_POST['x2'];
...
$query = $db->query("SELECT * FROM table WHERE x1='".$x1."' AND x2='".$x2."'");
if($query->num_rows === 1){
$row = $query->fetch_object();
$id = $row->id;
$_SESSION['logged_in'] = true;
$_SESSION['id'] = $id;
header("Location: start.php?id=$id");
3more queries
exit();
start.php will be just:
<?php
echo $_GET['id'];
?>
I thought $_GET['id'] would be stored on the server so that $_GET should be displayed. The fetch_object is working. I know that, because it will be displayed the right way at "id=$id" at the browser. So would someone be that friendly and could help me out. Thanks!
The $_GET superglobal is defined as part of the URL string:
http://example.org/index.php?foo=bar&baz=1
In index.php:
echo $_GET['foo']; // bar
echo $_GET['baz']; // 1
So $_GET is not stored on the server, but is passed with each HTTP request, as is $_POST, but that is passed in the HTTP headers rather than simply appened to the end of the URL.
$_GET variables are those passed via the URL, i.e. index.php?foo=bar&baz=qux (foo equals bar, baz equals qux).
These variables are not stored on the server as a part of the session, but rather only exist with that request. If you want to store information on the server as a part of the session, you should use $_SESSION instead, which will exist within the current session, regardless of the request.
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.
I have the following code in view.php, I would like to take the information to edit.php without compromising on security or show what is contained in the variables. edit.php has a form to edit the information from the database.
while ($row = mysql_fetch_assoc($result))
{
echo "" . $row['first_name'] ." " . $row['surname'] . "";
echo "<br />";
}
You are already compromising in security - see SQL injection and escaping strings.
Also, it is common practice to include other modules of the application by requiring (see require_once() and require() functions) files. It itself is not a security vulnerability, but indeed encloses all the global variables, functions and classes to that script.
If you really need that, you can unset (see unset()) all the variables you have set, but leave only data you want to be passed.
Learn how to write clean and secure code and it will be secure. Including one PHP file into another is not an insecure practice.
EDIT:
Some start may be creating classes with private or protected properties and public methods, then using them to store sensitive information and execute some actions. By using encapsulation you may achieve what you need.
You should allow only logged in users to see or edit that information, also you might get an SQL injection with:
$first_name = $_POST['first_name'];
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
You should have instead:
$first_name = mysql_real_escape_string( $_POST['first_name']);
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
The best way to do this would be(assuming you cant do anything else other than to use a standard anchor link to pass the variable) have an md5 of id of each of your record in the table. So that you can do
while($row = mysql_fetch_assoc($res))
{
echo "" . $row['first_name'] ." $row['surname'] . "";
}
now in edit.php retrieve this and compare it with the hash.
An even more secured way would be to concatenate the id of the record with another unique data such as join date or dob and hash the entire string. It would be highly secure that way.
Option 1: Just past the id from the database via your link. If user knows the id, but doesn't know any other information, than it's useless to it. Using something else will just bring few more code lines.
Option 2: Set user's id in SESSION
$first_name = mysql_real_escape_string( $_POST['first_name']);
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['first_name'] = $first_name;
Then to set other values from the database as session variables, e.g. the user's surname:
$_SESSION['surname'] = $row['surname'];
Then from any other page you can do
if ($_SESSION['loggedin'] == true) {
echo "Welcome $_SESSION['first_name'] $_SESSION['surname']!";
}
i want to keep some variable alive so that it is available to all the pages of the site ;
i tried global but that don't work with these kind of problem ;
i use the following code :
while($result1 = mysql_fetch_array( $result))
{
$adm_no = $result1['adm_no'];
$adm_dt = $result1['adm_dt'];
$name = $result1['name'];
$dob = $result1['dob'];
$f_name = $result1['f_name'];
$f_office = $result1['f_office'];
$f_o_no = $result1['f_o_no'];
$m_name = $result1['m_name'];
$m_office = $result1['m_office'];
$addr = $result1['addr'];
$pho_no = $result['pho_no'];
these same variable in another page called tc.php . how can i do that ????
If you want to access all that data again in another page I would recommend storing the information needed to retrieve data from your mysql table in a session rather than the result of the query. This means you don't have a load of trivial data in your session space. For example.
Imagine I have a person table and want to get bits of information for that person on different pages I just store the person_id in a session like so:
//home.php
$_SESSION['personID'] = $personID;
Then on any page I want to retrieve person information on I just get the person id from the session and run the query to get the specific information I need.
//profile.php
$personID = $_SESSION['personID'];
//Get specific information here
If you really cant change the way that you are doing this which I really hope you can as it'll make your life a hell of a lot easier then just changing your code to this:
//make sure that you have started a session at the top of your page before you do anything else
session_start();
while($result1 = mysql_fetch_array($result)) {
$_SESSION['adm_no'] = $result1['adm_no'];
$_SESSION['adm_dt'] = $result1['adm_dt'];
$_SESSION['name'] = $result1['name'];
$_SESSION['dob'] = $result1['dob'];
//etc
}
Use
$_SESSION['myvar']= "your value";
echo $_SESSION['myvar'];
will can access any page
Fetch data again in tc.php - it is the best way in this case I think.
You can also set that data to the session, and in tc.php get it from there.