storing XML value to a session variable - php

been trying to store a value from an XML file however it releases an error.
how can i solve this ?
<?php
session_start();
$success = 0;
session_unset();
$clients= simplexml_load_file('client.xml');
if(isset($_POST['submit'])){
foreach($clients -> client_info as $client){
if($_POST['username'] == $client->username && $_POST['pwd'] == $client->pwd ){
$success = $success + 1;
$_SESSION["id"] = $client['id'];
break;
}
}
}
if (isset($_SESSION["id"])) {
echo $_SESSION["id"];
}
else {
echo "no session";
}
thats the code.
however the problem is that when i go outside for example
<?php
session_start();
echo $_SESSION["id"];
?>
it says undefined id.
any solutions to this problem?

If you need to save a complete element of the simplexml_load_file() result use the asXML() method (formatting the element as XML string). To store the string value of any content element use the __toString() method:
Example:
$_SESSION["id"] = $client['id']->__toString(); //for attributes
If you want to save the text content of a xml tag:
$_SESSION["clientContent"] = $client->__toString(); //text content of client tag
To save an entire xml section as XML string:
$_SESSION["client"] = $client->asXML(); //for elements
and to restore the $client variable:
$client=simplexml_load_string($_SESSION["client"]); //$client as object again

Related

call a php function inside a div

I want to make a call of this php logic inside a html div but when passing it as a function the logic breaks since it does not send an error message in case of entering the pass wrong and its confirmation at the time of performing the password change.
<?php
require 'funcs/conexion.php';
require 'funcs/funcs.php';
$user_id = $mysqli->real_escape_string($_POST['user_id']);
$token = $mysqli->real_escape_string($_POST['token']);
$password = $mysqli->real_escape_string($_POST['password']);
$con_password = $mysqli->real_escape_string($_POST['con_password']);
if(validaPassword($password, $con_password))
{
$pass_hash = hashPassword($password);
if(cambiaPassword($pass_hash, $user_id, $token))
{
echo "Contraseña Modificada <br> <a href='index_alumnos.php' >Iniciar Sesion</a>";
} else {
echo "Error al modificar contraseña";
}
} else {
echo "Las contraseñas no coinciden <br> <a href='index_alumnos.php' >contacta a Academia</a>";
}
?>
If the echo happens before your actual div is drawn, the echo goes... right where it happens. Which isn't within your div.
One way of getting around this would be to put your error message into a variable and then deliver this variable into your div (whether it be through a return value, if it's a call, or some other means.)
Here's a simple example to illustrate this:
<?php
if(1 === 2) {
//great, 1 is 2
} else {
//oh no, an error
$someErrorLine = '1 is not 2';
} ?>
<h1>Hi</h1>
<div><?= $someErrorLine ?></div>
You could also check if the variable exists, something like if(isset($someErrorLine)) {} and echo the div with it, or put the div within your variable.

using $_GET['VALUE'] from a FORM using method POST

I am troubleshooting CAPTCHA problem in someone Else's code, where the form method is "POST"
But in the action.php file the code is like this:
$key=substr($_SESSION['key'],0,5);
$number = $_GET['img_code'];
if($_GET['img_code']){
if($number==$key)
{
echo "done";
exit();
}
else
{
echo false;
exit();
}
}
I have tried to var_dump($_GET['img_code']) and as expected I am getting null value.
but if I am doing it var_dump($_POST['img_code']) I am getting the correct value.
but once I am setting it to POST, I start getting error "captcha not entered correctly.
Any help will be greatly appreciated.
UPDATE:
FORM METHO
<form action="{$Site_Root}signup.php" method="post" class="frmRegister tutor-registration" name="frmRegister" id="frmRegister" enctype="multipart/form-data" >
Further Update:
If I am using $_REQUEST['img_code'] and then doing a var_dump I am getting the matching string for $key and $number like
string(5) "f065a" string(5) "f065a"
but problem is when I am applying this as a condition for example:
I am getting - "captcha not entered correctly."
if(isset($_POST['email'])){
if ($key==$number){ // condition line is added by me
if(!empty($_FILES['photo']['name']))
{
$_POST['photo'] = fileUpload($_FILES['photo'],TUTOR);
$thumb->image($physical_path['Tutor'].$_POST['photo']);
$thumb->size_width(120);
$thumb->jpeg_quality(100);
$filename = $thumb->get2(); //small_thumb_
}
else
{
$_POST['photo'] = "";
}
$tutor_id = $tut->Insert($_POST);
$to_email = $_POST['email'];
global $mail;
$mail = '';
$mail = new htmlMimeMail();
$mail->setFrom($config[WC_CONTACT_US]);
//Set Cc
// $mail->setCc(array($config[WC_CONTACT_US]));
$mail->setSubject('Welcome to TuitionJobsPortal.com!');
$tpl2 = new Smarty;
$tpl2->template_dir = $physical_path['EmailTemplate'];
$tpl2->compile_dir = $physical_path['Site_Root']. 'templates_c/';
$tpl2->debugging = DEBUG;
$tpl2->assign(array("membername" => $_POST['tutor_name'],
"vcode" => $_POST['verification_code'],
"tutor_id" => $tutor_id,
"Templates_Image" => $virtual_path['Site_Root'].'templates/images/',
"Site_Root" => $virtual_path['Site_Root'],
));
$content = $tpl2->fetch('registration'. $config['tplEx']);
$mail->setHtml($content);
$result = $mail->send(array($to_email));
header("location: signup.php?signup=true");
exit();
}
} //this is added.
I don't think you can access $_POST data from $_GET , so either change form method to GET or access posted data using $_POST['img_code'] .
You can use the $_REQUEST global variable, it can do the work of both GET and POST,

php - encode json to path

I have a JSON file and in it consists of site data. This site data is for a homepage (I decode the JSON into variables so I can echo them out within the HTML).
Here is my code:
<?php
//start json stuff
$path = "../assets/json/home.json";
$fileexists = file_exists($path);
if ($fileexists) {
$json_d = file_get_contents($path,TRUE);
$json = json_decode($json_d,TRUE);
} else {
die("Error retrieving site data - please refresh the page. If that doesn't work, please report a problem, here and come back later.");
}
if(isset($_POST['submit'])) {
$navtitle = $_POST['navtitle'];
$title = $_POST['title'];
$json_arr = array('navtitle' => $navtitle, 'title' => $title);
$json_enc = json_encode($json_arr);
$json_result = file_put_contents($path, $json_enc);
if($json_result) {
echo "<script>alert('WORKING!');</script>";
} else {
echo "<script>alert('NO WORKING!');</script>";
}
}
?>
So, I have created the array, encoded the array and placed it in the file (I think) but I do not see any changes.
NOTE: I have added the <meta http-equiv="expires" content="0"> meta tag to force the website/browser to grab the home.json file everytime the page is loaded in.
Thank you for any help.

How to manage HTML special characters stored in an array

I have the $user array that contains data with special characters. It seems like each element of $user that contains special characters can't render properly after they are stored in a session.
Here is my code:
<?php
session_start();
include_once('../application/classes/DataLayer.class.php');
$dl = new DataLayer();
$user = $dl->doLogin($_POST['email_sub'], $_POST['password_sub']);
if(isset($user)) {
foreach($user as $detail_array => $detail){
$fn = html_entity_decode($user['fn']);
$ln = html_entity_decode($user['ln']);
}
var_dump($fn, $ln); // $fn and $ln display well here
$_SESSION['user'] = $user;
$_SESSION['fn'] = $fn;
$_SESSION['ln'] = $ln;
var_dump($_SESSION['fn'], $_SESSION['ln']); // $_SESSION['fn'], $_SESSION['ln'] display well here too
}
else {
//do something here
}
?>
Any help would be appreciated. Sorry for my bad english.
Use the function from this link https://stackoverflow.com/a/8454838/997178 to encode the data for output
Use encode_output_vars function , param $vars is your session data ... return value will be a single element encoded for output or an array with all elements encoded , depending what your parameter is .
Or just use php function htmlentities for your session data before you output it . Here is link http://php.net/manual/en/function.htmlentities.php

Having trouble getting the right idea

well i'm writing a php code to edit tags and data inside those tags but i'm having big trouble getting my head around the thing.
basically i have an xml file similar to this but bigger
<users>
<user1>
<password></password>
</user1>
</users>
and the php code i'm using to try and change the user1 tag is this
function mod_user() {
// Get global Variables
global $access_level;
// Pull the data from the form
$entered_new_username = $_POST['mod_user_new_username'];
$entered_pass = $_POST['mod_user_new_password'];
$entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
$entered_new_roll = $_POST['mod_user_new_roll'];
$entered_new_access_level = $_POST['mod_user_new_access_level'];
// Grab the old username from the last page as well so we know who we are looking for
$current_username = $_POST['mod_user_old_username'];
// !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!
// Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
$xml = simplexml_load_file('../users/users.xml');
// read the xml file find the user to be modified
foreach ($xml->children() as $xml_user_get)
{
$xml_user = ($xml_user_get->getName());
if ($xml_user == $entered_new_username){
// Set array to send data back
//$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);
// Add to session to be sent back to other page
// $_SESSION['add_error'] = $a;
die("Username Already exist - Pass");
// header('location: ../admin.php?page=usermanage&task=adduser');
}
}
// Check the passwords and make sure they match
if ($entered_pass == $entered_confirm_pass) {
// Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
$new_password = hash('sha512', $entered_pass);
unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
}
else {
die("passwords did not match - Pass");
}
if ($entered_new_access_level != "") {
if ($entered_new_access_level < $access_level){
die("Access level is not sufficiant to grant access - Pass");
}
}
// Now to load up the xml file and commit changes.
$doc = new DOMDocument;
$doc->formatOutput = true;
$doc->perserveWhiteSpace = false;
$doc->load('../users/users.xml');
$old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
}
when run with just the username entered for change i get this error
Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201
could someone explain to me how to do this or show me how they'd do it.. it might make a little sense to me to see how it's done :s
thanks
$entered_new_username is a string so you'll need to wrap it with a DOM object, via something like$doc->createElement()
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);
This may not be quite right, but hopefully it points you in the correct direction.
alright got it writing and replacing the node that i want but i have ran into other issues i have to work out (IE: it's replacing the whole tree rather then just changing the node name)
anyway the code i used is
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
try {
$new_node_name = $doc->createElement($entered_new_username);
$old_user->parentNode->replaceChild($new_node_name, $old_user);
}
catch (DOMException $e) {
echo $e;
}
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
$doc->save('../users/users.xml');

Categories