I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
Related
I have a problem trying to display some session variables in a different page in php. Most of the threads I've seen here are related to the lack of "session_start()". But I already have it at the top of my files.
I'm trying to create a "recover your password module".
I have a form element which has an action set to another page.
I have a database with two tables. The form just allows the user to input his e-mail. When I click the submit button, a mysqli connection is supposed to look in both tables for the user with the e-mail stored in the form and then store the rest of the elements (name, password, recovery question and its answer) of the table in some php variables.
In an if conditional statement I check which table the e-mail is stored in and then create some session variables that store the whole information of said user.
In the other page I'm just trying to echo some text along with the session variable of the name of the user if that variable session is set. If not it will echo a "failed session" text.
Here is the form (the file where this thing is has the session_start() already in top):
<form action="cambio.php" method="post">
<h1>RECUPERACIÓN DE CONTRASEÑA</h1><br>
<p>Escriba su dirección de correo para modificar su contraseña:</p><br>
<div class="form group">
<label for="email">Correo electrónico:</label>
<input type="email" class="form-control ancho" id="email" name="email" class="ancho"><br>
</div>
<button type="submit" class="btn btn-primary" name="recuperar">Recuperar contraseña</button>
</form>
After connecting to the database, this is where I'm setting the session variables (in the same .php as the previous form code):
if(isset($_POST['recuperar'])) {
$c = $_POST["email"];
$buscarAlumno="select nombre, correo, password, num_pregunta, respuesta from alumno where correo='$c';"; //first table
$buscarProfesor="select nombre, correo, password num_pregunta, respuesta from profesor where correo='$c';"; //second table
$resA = $conn->query($buscarAlumno);
$resP = $conn->query($buscarProfesor);
$rowA = $resA->fetch_array();
$rowP = $resP->fetch_array();
//Save the e-mail-matching fields (first table)
$rnA = $rowA["nombre"];
$rcA = $rowA["correo"];
$rpA = $rowA["password"];
$rnpA = $rowA["pregunta"];
$rrA = $rowA["respuesta"];
//Save the e-mail-matching fields (second table)
$rnP = $rowP["nombre"];
$rcP = $rowP["correo"];
$rpP = $rowP["password"];
$rnpP = $rowP["num_pregunta"];
$rrP = $rowP["respuesta"];
//In this statement, some of the variables above are going
//to be stored in session variables depending on the
//table in which the e-mail was found
if (isset($c)) {
if ($c == $rcP) {
$_SESSION['nomCorrecto'] = $rnP;
$_SESSION['corCorrecto'] = $rcP;
$_SESSION['pasCorrecto'] = $rpP;
$_SESSION['preCorrecto'] = $rnpP;
$_SESSION['resCorrecto'] = $rrP;
}
elseif ($c == $rcA) {
$_SESSION['nomCorrecto'] = $rnA;
$_SESSION['corCorrecto'] = $rcA;
$_SESSION['pasCorrecto'] = $rpA;
$_SESSION['preCorrecto'] = $rnpA;
$_SESSION['resCorrecto'] = $rrA;
}
else {
echo "Usuario no registrado.";
}
}
}
This code is in another page, where I want the results to be show (again, it already has the session_start() on top of the file).
<?php
//This part should show the name of the user, but is not working
if(isset($_SESSION['nomCorrecto'])) {
echo "Hola " .$_SESSION['nomCorrecto']. ".";
}
else {
echo "Sesión fallida.";
}
?>
I don't know what I'm doing wrong, I don't know if the error is about the form statement or how I'm saving and echoing the session variables.
I just get the "Sesión fallida" error text.
Any help is welcome.
Thanks in advance.
Ensure that you've initialize session_start(); before any sessions are being called.
For example, you can add something like this to the beginning of each page where session is used: if (session_status() == PHP_SESSION_NONE) session_start(); This will check whether the session is started or not, and if not it will start it.
You can also use var_dump($_SESSION); at every places where you use sessions in order to track / examine the session data.
Note: The common reason why your code is not working is if you failed to initialize session_start(); in places necessary. Failure to carry out some necessary checks on your code can also cause this. You can find more detail about session loss in the answer of this question.
Finally figured it out. I need to declare the session variables that I'm going to use right after the session_star() function.
Thanks for the help.
I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .
On my website, I allow users to view a users information by simply clicking their name. Once they click the persons name, they can schedule the person to come to an event. When the user clicks "schedule me" I take the them full name from the "user_id" and send it as a "$_SESSION['speaker']" to the next file that pretty much checks if the user came from the last file and takes the name and uses it as the input value for the calendar. The problem I am having is that when the user didn't "click schedule" from the other file and goes to the calendar website alone, the name from the previous person they clicked stays there and I want it to be blank in case they want to put a different name. So pretty much i would access the calendar website just by typing the URL and the name would still be in the session. I want to clear the session without logging the user out so they don't see the name of the previous person they clicked. Here is some of my code
First file
$_GET['speaker'] = $_SESSION['speaker_id'];
$speaker_id = $_GET['speaker'];
$stmtSpeaker = $handler->prepare("SELECT * FROM formdata WHERE user_id= :speaker_id");
$stmtSpeaker->bindParam(':speaker_id', $speaker_id, PDO::PARAM_INT);
$stmtSpeaker->execute();
$formData = $stmtSpeaker->fetch();
if(isset($_POST['schedule_me'])){
$_SESSION['admin'] = $adminBoolean;
$_SESSION['speaker'] = $formData['fullname'];
$_SESSION['speaker_came'] = true;
header("Location: admincalendar.php");
exit;
}
Second file
$adminBoolean = $resultChecker['admin'];
if($_SESSION['speaker_came'] = true){
$speaker = $_SESSION['speaker'];
}else{
$speaker = "";
}
Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
You can unset session variable
$adminBoolean = $resultChecker['admin'];
if($_SESSION['speaker_came'] = true){
$speaker = $_SESSION['speaker'];
}else{
unset($_SESSION['speaker']);
unset($_SESSION['speaker_came']);
$speaker = '';
}
You need to first get the tempkey of the element and then unset it. Try this:
if(($tempkey = array_search($speaker_id, $_SESSION['speaker'])) !== FALSE)
unset($_SESSION['speaker'][$tempkey]);
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 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.