I am trying to get dynamic $_SESSION[$id] on the second page shown below, but its not working (as per the printout):
First page url
https://example.com/test.php?id=1548393
First page code
<?php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
?>
Second page url
https://example.com/test2.php?id=1548393
Second page code
<?php
session_start();
$id = $_GET['id'];
if(isset($_SESSION[$id])){
echo "working";
}else{
echo "not working";
}
?>
i found problem we can not use numeric index for $_SESSION
but we can use number in $_SESSION by convert number to roman numerals
first page url
https://example.com/test.php?id=1548393
first page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
$_SESSION[$roman_id] = "mysecretstringline";
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
second page url
https://example.com/test2.php?id=1548393
second page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
if(isset($_SESSION[$roman_id])){
echo "working";
}else{
echo "not working";
}
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
output
working
thanks #gre_gor and #Katie
Could be that in your normal code (this just looks like a quick mockup), you have a space after ?> somewhere. That could cause issues.
<?php
// start.php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
and
<?php
// next.php
session_start();
$id = $_GET['id'];
if (isset($_SESSION[$id])) {
echo "working";
} else {
echo "not working";
}
works for me. Notice no ?> characters.
UPDATE:
The following might be of interest regarding session name constraints (can a php $_SESSION variable have numeric id thus : $_SESSION['1234’])
You have that issue in your example you could just add an id_ and then do the same check when validating/getting the session.
Related
i have a simple skript that is sending the User to another Page if the input is over 10, from the other skript i want to echo the input. But it giving me the warning that: Warning: Undefined variable $QT
and anyhow it is also copying the whole page that i am including so the pages looking the same.
I tried with require and include and also to paste the whole location of the skript
Skript1:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && $_POST["QT"] > 10) {
$QT = $_POST["QT"];
header("location: ../main/Skript2.php");
die();
}
else{
}
?>
Skript 2:
<?php
include "Skript1.php";
echo $QT;
?>
Both skripts are in the same Folder main.
thanks for helping
You can use header location with a parameter.
Skript 1:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && $_POST["QT"] > 10) {
$QT = $_POST["QT"];
header("location: ../main/Skript2.php/?number=$QT");
die();
}
else{
}
?>
Skript 2:
<?php
$QT = $_GET['number'];
echo $QT;
?>
More than one variables can be joined to a string with a delimiter and then exploded.
Skript 1:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && $_POST["QT"] > 10) {
$xy = "test";
$QT = $_POST["QT"];
$all = $QT.",". $xy;
header("location: ../main/Skript2.php/?number=$all");
die();
}
else{
}
?>
Skript 2:
<?php
$all = $_GET['number'];
$parts = explode(",", $all);
echo $parts[0]."<br>";
echo $parts[1]."<br>";
?>
Whenever I leave my input field empty, $error['commment'] should be set and echoed, but it won't echo, but if I just say echo "some text";, it echo's it.
The comments function is in my functions.php file and $error[] = array() is given in my text.php file above my comments() function, so I don't understand why it's not working, please help guys.
The last bit of PHP code is in a while loop that has to display all the results of my SQL query.
Code above my HTML in text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
comments();
?>
Code in my functions.php:
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
$filledIn = true;
if (empty($text)) {
$error['comment'] = "No text filled in";
$filledIn = false;
}
}
}
This is the code in my text.php:
<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Because $error is not in the scope of the comments() function. So $error['comment'] never gets set.
Ideally you would want to do something like this:
text.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error['comment'] = comments();
functions.php
function comments(){
if (isset($_POST['submit'])) {
$text = $_POST['text'];
if (empty($text)) {
return "No text filled in";
}
}
return null;
}
text.php
<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>
Rather than setting the array key "comments" directly I would use a return value from the comments() function to set it. This allows you to avoid having to use global variables.
Edit: I removed the $filledIn variable from comments() because it wasn't being used in the provided code.
#pu4cu
imo, since you dont come across as very advanced, so that you dont have to make many code changes to what you have now which might get you the minimal edits, and easiest for you to understand;
if in your comment function, you just return a response from this function, like a good little function does, then your response will be available when you call the function, when you set that function to a variable.
//functions.php (note this sets error to true to be failsafe, but this depends on how your using it. set the $response to an empty array in the first line instgad, i.e. array(); if you don't want it failsafe.
<?php
function comments()
{
$response = array(
'error' => TRUE,
'filledIn' => FALSE
);
if (isset($_POST['submit']))
{
$text = $_POST['text'];
$response['filledIn'] = TRUE;
if (empty($text))
{
$response['error']['comment'] = "No text filled in";
}
else{
$response['error'] = NULL;
}
}
return $response;
}
//index.php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$response = comments();
//text.php
<?php
if($response['error']['comment'])) echo "<p class='error'>".$response['error']['comment']."</p>";
I find your code overly complicated, 3 files, 2 includes, and 1 function, when all you really needed is this:
$error = array();
$error['comment'] = empty($_POST['text']) ? "No text filled in" : $_POST['text'];
echo "<p class='error'>".$error['comment']."</p>";
Your scopes are all mixed up. Your comments() function checks for $_POST, which should be checked before the function is called, and then tries to set a variable within its scope, but you try to access the same variable from outside.
The correct way would be:
text.php:
<?php
session_start();
include("connect.php");
include("functions.php");
$userId = "";
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
$userId = $_SESSION['id'];
}
$error[] = array();
if (isset($_POST['submit']) {
comments($_POST);
}
?>
functions.php
function comments($data){
if (isset($data['text'])) {
$text = $data['text'];
if (empty($text)) {
return array('comment' => 'No text filled in');
}
return true;
}
return null;
}
Then you can use the values returned by your function on to act on the result.
I'm calling a specific function, either getTaskList0, getTaskList1, or getTaskList2, each the same as below, with the number after task referring to the getTaskList number (in TaskManagerDAO):
function getTaskList0(){
$lst=array();
$con=$this->getDBConnection();
$result = $con->query("SELECT name, score FROM task0 ORDER BY score DESC");
$i = 0;
$counter=0;
while (($row =$result->fetch_row()) && ($counter<5)) {
$rec = new Task($row[0],$row[1]);
$lst[$i++]=$rec;
$counter++;
}
return $lst;
}
Task:
<?php
class Task{
public $name;
public $score;
function __construct($name,$score) {
$this->name = $name;
$this->score = $score;
}
}
The function is called in here:
<?php
session_start();
if(!class_exists('Action')){
include_once 'Action.php';
}
if(!class_exists('TaskManagerDAO')){
include_once 'TaskManagerDAO.php';
}
class Action_DisplayList implements Action{
public function execute($request){
if(!isset($_SESSION['functCount']))
$_SESSION['functCount']=0;
$functCount=$_SESSION['functCount'];
$functionName="getTaskList{$functCount}";
echo $functionName;
$dao = new TaskManagerDAO();
$names = $dao->$functionName();
$_SESSION['names'] = $names;
$last = sizeof($names);
$start = 0;
$_SESSION['start'] = $start;
$_SESSION['last'] =$last;
header("Location: tasklist.php");
}
}
?>
I'm trying to call the function by putting a variable at the end of the function name as a string and then calling the function. This works as I don't get any errors, but the list does not show up in the table, which is what this code is supposed to do:
<?php
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
include 'Action_Add.php';
Action_Add::execute();
}
$functCount=0;
$_SESSION['functCount']=0;
$names = $_SESSION['names'];
$start=$_SESSION['start'];
$last = $_SESSION['last'];
for($count = $start; $count < $last; $count++){
$name=$names[$count];
echo "<tr>";
echo "<td>".($count+1)."</td>";
echo "<td>".$name->name."</td>";
echo "<td>".$name->score."</td>";
echo "</tr>";
}
?>
EDIT:
I restarted my computer and everything and for the first run load of the page it worked perfectly. After that though, it stopped working though.
Use session_start(); before start using $_SESSION. So in your case, try something like
<?php
session_start();
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
//.... remaining code here
Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
Still trying to get how PHP works :)
Kindly help me with one solution & idea, here is when i'm using:
<?php
$content = array(
'id01'=>'sub_id01.php',
'id02'=>'sub_id02.php'
);
if(in_array($_GET['show'], array_keys($content))) {
include($content[$_GET['show']]);
} else {
include('sub_id00.php');
}
?>
and:
<?php
$content = array(
'id00'=>'N/A',
'id01'=>'ID01',
'id02'=>'ID02',
);
if(!empty($_GET['show']) && isset($content[$_GET['show']])) {
echo $content[$_GET['show']];
} else {
echo $content['id00'];
}
?>
Where first example includes pages and second includes simple code inside ''
Problem is that if there is no ID set (index.php) ut shows default page/code. And if wrong ID set, it'll also show default page/code.
How to update it so without any ID set it would show default page and if some wrong ID set, it would show some error page/code?
Cheers!
UPDATE!
After a while reqding i've updated it with:
<?php
$content = array(
'id01'=>'sub_id01.php',
'id02'=>'sub_id02.php'
);
if (in_array($_GET['show'], array_keys($content)))
{
include($content[$_GET['show']]);
}
elseif (isset($_GET['show']))
{
include('sub_error.php');
}
else {
include('sub_id00.php');
}
?>
And:
<?php
$content = array(
'error'=>'error msg',
'id00'=>'N/A',
'id01'=>'ID01',
'id02'=>'ID02',
);
if(!empty($_GET['show']) && isset($content[$_GET['show']]))
{
echo $content[$_GET['show']];
}
elseif (isset($_GET['show']))
{
echo $content['error'];
}
else
{
echo $content['id00'];
}
?>
:)
$content = array(
'id01'=>'sub_id01.php',
'id02'=>'sub_id02.php'
);
if (isset($_GET['show']))
{
if (array_key_exists($_GET['show'], $content))
{
//$_GET id is set and it exists in content
include($content[$_GET['show']]);
}
else
{
//$_GET id is set but does not exist in content
//include whatever page you have for a wrong id here
}
}
else
{
//else no $_GET was set
//include default page
}
In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.