dom cant use variables to store data in xml - php

I got an error when trying to post user input data from html to php and saved into xml file. It gives me this error Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, null given. Here is the code
register.htm
<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
</head>
<body>
<form id="regform" method="post" action="register.php">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="fname">First Name:</label><input type="text" name="fname"/></p>
<p><label for="lname">Last Name:</label><input type="text" name="lname"/></p>
<p><label for="password">Password:</label><input type="password" name="password"/></p>
<p><label for="cpassword">Confirm Password:</label><input type="password" name="cpassword"/></p>
<p><label for="email">Email:</label><input type="email" id="email" name="email"/></p>
<p><label for="phone">Phone:</label><input type="text" name="phone"/></p>
<input type="submit" value="Register"/>
</fieldset>
</form>
</body>
</html>
relevant parts of register.php (whole code is too long)
$fname = #trim($_POST["fname"]);
$lname = #trim($_POST["lname"]);
$password = #trim($_POST["password"]);
$cpassword = #trim($_POST["cpassword"]);
$phone = #trim($_POST["phone"]);
$email = #trim($_POST["email"]);
if(file_exists('../../customer.xml'))
{
$xml2 = file_get_contents('../../data/customer.xml');
}
if(!file_exists('../../customer.xml'))
{
$dir = "../../data";
$f = fopen("$dir/customer.xml", "w");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('customer');
$doc->appendChild($root);
$user = $doc->createElement('user');
$root->appendChild($user);
$fname = $doc->createElement('fname');
#override - if I change this to 'brian' then it works, doesnt work with $variable
$fnameValue = $doc->createTextNode($fname);
$fname->appendChild($fnameValue);
$user->appendChild($fname);
$lname = $doc->createElement('lname');
$lnameValue = $doc->createTextNode($lname);
$lname->appendChild($lnameValue);
$user->appendChild($lname);
echo $doc->save('../../data/customer.xml');
//$doc->load('customer.xml');
echo ' Registration Successful!';
}

Just like the error suggests, appendChild needs a DOMNode. Just create that element, then use the second paramter from the user input. Example:
$fname = #trim($_POST["fname"]);
$lname = #trim($_POST["lname"]);
$password = #trim($_POST["password"]);
$cpassword = #trim($_POST["cpassword"]);
$phone = #trim($_POST["phone"]);
$email = #trim($_POST["email"]);
if(file_exists('../../customer.xml')) {
$xml2 = file_get_contents('../../data/customer.xml');
}
if(!file_exists('../../customer.xml')) {
$dir = "../../data";
$f = fopen("$dir/customer.xml", "w");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('customer');
$doc->appendChild($root);
$user = $doc->createElement('user');
$root->appendChild($user);
$fname_node = $doc->createElement('fname', $fname);
$user->appendChild($fname_node);
$lname_node = $doc->createElement('lname', $lname);
$user->appendChild($lname_node);
echo $doc->save('../../data/customer.xml');
//$doc->load('customer.xml');
echo ' Registration Successful!';
}

You are re-using the $fname variable. That's why you get the error. It's a simple, typographical mistake. One thing you can do is to prefix the input variables with input, e.g. $input_fname so it's clear that you obtain them from there. Or even create a stdclass like $input = new stdClass; and then assign the $_POST variables to it: $input->fname = #trim($_POST["fname"]); - that way it's clear what it stands for and you can pass the input around more easily, too.
Example:
$input = new stdClass;
$input->fname = #trim($_POST["fname"]);
$input->lname = #trim($_POST["lname"]);
$input->password = #trim($_POST["password"]);
$input->cpassword = #trim($_POST["cpassword"]);
$input->phone = #trim($_POST["phone"]);
$input->email = #trim($_POST["email"]);
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('customer');
$root = $doc->appendChild($root);
foreach ($input as $key => $value) {
$element = $doc->createElement($key, $value);
$root->appendChild($element);
}
$doc->save('php://output');
Exemplary output:
<?xml version="1.0"?>
<customer>
<fname>Waltraud</fname>
<lname>Van Hömpenstetten</lname>
<password></password>
<cpassword></cpassword>
<phone></phone>
<email></email>
</customer>
Online Demo: https://eval.in/private/29c08d9fafec22

Related

How can I remove query string from URL?

Here is my code. It is a simple html form with two inputs. All data is saved into xml file using DOMDocument a then all data from XML file is inserted into the table below the form. I added two buttons edit and delete (x). Now I can edit and delete any user/player from the table. And here is my problem. I need to remove query string from URL after deleting or editing. I want to add a new user/player into the table after deleting. When I delete manually query string from URL everything works fine again. But I want to delete query string automatically after deleting some user. Sorry for my English hoping you understand me. Thanks in advance!
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$xml = new DOMDocument("1.0", "utf-8");
if (is_file('database.xml')) {
$xml->load("database.xml");
$db = $xml->getElementsByTagName('db')->item(0);
} else {
$db = $xml->createElement("db");
$xml->appendChild($db);
$db = $xml->getElementsByTagName('db')->item(0);
}
$newPlayer = $xml->createElement("player");
foreach ($_POST as $key => $value) {
$playerStuff = $xml->createElement($key, $value);
$newPlayer->appendChild($playerStuff);
}
$db->appendChild($newPlayer);
$xml->save("database.xml");
}
$name = $number = "";
if (isset($_GET['action']) && $_GET['action'] == 'edit') {
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
$player = $xml->getElementsByTagName('player')->item($_GET['id']);;
$name = $player->getElementsByTagName('name')->item(0)->nodeValue;
$number = $player->getElementsByTagName('number')->item(0)->nodeValue;
}
if (isset($_GET['action'])) {
switch ($_GET['action']){
case 'edit':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$nameEl = $player->getElementsByTagName('name')->item(0);
$numberEl = $player->getElementsByTagName('number')->item(0);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$newName = $xml->createElement("name", $_POST["name"]);
$nameEl->parentNode->replaceChild($newName, $nameEl);
$newNumber = $xml->createElement("number", $_POST["number"]);
$numberEl->parentNode->replaceChild($newNumber, $numberEl);
$db = $xml->getElementsByTagName('db')->item(0);
$lastElement = $db->lastChild;
$lastElement->parentNode->removeChild($lastElement);
}
$xml->save("database.xml");
break;
case 'delete':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
//$xml = $dokument->getElementsByTagName('xml')->item(0);
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$player->parentNode->removeChild($player);
$xml->save("database.xml");
break;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PLAYERS</title>
<link rel="stylesheet" href="stylesss.css">
</head>
<body>
<form action="" method="POST">
<input type="text" name="name" value="<?php echo $name ?>">
<input type="text" name="number" value="<?php echo $number ?>">
<input type="submit" value="INSERT">
</form>
<?php
$xml = new DOMDocument("1.0", "utf-8");
if (is_file('database.xml')) {
$xml->load('database.xml');
$players = $xml->getElementsByTagName("player");
echo "<table>";
echo "<tr><th>" . "Player Name" . "</th><th>" . "Number". "</th></tr>";
foreach($players as $key => $player){
echo "<tr>";
foreach($player->childNodes as $data) {
echo "<td>". $data->nodeValue ."</td>";
}
echo "<td>
<a href='?id={$key}&action=edit' class='buttons edit'>EDIT</a>
<a href='?id={$key}&action=delete' class='buttons delete'>&#10006</a>
</td>";
echo "</tr>";
}
}
echo "</table>";
?>
</body>
</html>
I would say to redirect header("Location: your-page.php"); The page you redirect to can be the same page but without the query string. It means that if someone refreshes you will not repeat the same action. So, something like this. You have to use the header function before anything is written to the page, it will not work if it is used after HTML or after something is print or echo to the page.
if (isset($_GET['action'])) {
switch ($_GET['action']){
case 'edit':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$nameEl = $player->getElementsByTagName('name')->item(0);
$numberEl = $player->getElementsByTagName('number')->item(0);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$newName = $xml->createElement("name", $_POST["name"]);
$nameEl->parentNode->replaceChild($newName, $nameEl);
$newNumber = $xml->createElement("number", $_POST["number"]);
$numberEl->parentNode->replaceChild($newNumber, $numberEl);
$db = $xml->getElementsByTagName('db')->item(0);
$lastElement = $db->lastChild;
$lastElement->parentNode->removeChild($lastElement);
}
$xml->save("database.xml");
break;
case 'delete':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
//$xml = $dokument->getElementsByTagName('xml')->item(0);
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$player->parentNode->removeChild($player);
$xml->save("database.xml");
break;
}
header("Location: your-page.php");
}

function php to Plugin Wordpress

i have php code it's for reading excel file (.xlsx) and i want to make plugin for Wordpress ( just a simple plugin ). tested on localhost Wordpress it's work perfectly, but when i uploaded to my site it's not work. when i click submit button just appear blank page.
<form method="post" action="">
Number : <input type="text" name"number" /> </br>
<input type"submit">
</form>
function find(){
if (isset($_POST['number']) {
$number = $_POST["number"];
require_once ( plugin_dir_path(__FILE__). 'includes\classes\PHPExcel.php');
$tmpfname = ( plugin_dir_path(__FILE__). 'number.xlsx');
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
$excel_arr = $worksheet->toArray(null,true,true,true);
for ($row=1;$row <=$lastRow;$row++){
if ($excel_arr[$row]["A"] == $number ) {
echo $excel_arr[$row]["A"];
break;
}
}
}
}
add_shortcode('show_number', 'find');
Insert HTML form code inside "find()" function. So form show with shortcode "show_number" and and get result.
function find(){
if (isset($_POST['number']) {
$number = $_POST["number"];
require_once ( plugin_dir_path(__FILE__). 'includes\classes\PHPExcel.php');
$tmpfname = ( plugin_dir_path(__FILE__). 'number.xlsx');
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
$excel_arr = $worksheet->toArray(null,true,true,true);
for ($row=1;$row <=$lastRow;$row++){
if ($excel_arr[$row]["A"] == $number ) {
echo $excel_arr[$row]["A"];
break;
}
}
}
?>
<form method="post" action="">
Number : <input type="text" name"number" /> </br>
<input type"submit">
</form>
<?php
}
add_shortcode('show_number', 'find');
?>

how to fetch all the data contained in a div tag from a website using php crawlers

i'm having a code for simple php crawler that fetches all the html pages from websites upto depth 5 but if ,I run that for getting all the data contained in a div tag with its id like [container, main ,wrapper.etc] then it show unexpected result...heres the php code ::
<?php
$a=$_POST['t1'];
function crawl_page($url, $depth = 5)
{
static $seen = array();
if (isset($seen[$url]) || $depth === 0) {
return;
}
$seen[$url] = true;
$dom = new DOMDocument('1.0');
#$dom->loadHTMLFile($url);
$anchors = $dom->getElementsByTagName('div');
foreach ($anchors as $element) {
$href = $element->getAttribute('id');
//$href = $element->find('div[id=main]', 0)->plaintext;
if (0 !== strpos($href, 'main')) {
$host = "http://".parse_url($url,PHP_URL_USER);
$href = $host. '/' . ltrim($href, '/');
}
crawl_page($href, $depth - 1);
}
echo "New Page:<br /> ";
echo "URL:",$url,PHP_EOL,"<br />","CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL," <br /> <br />";
}
crawl_page($a, 5);
?>
this code is working good for anchor tags but i want this working for div tag only that fetches all the data contained in it nothing else. i want this for my project if anybody has done that then helpme out.......the html code is written down
<HTML>
<head>
<title></title>
</head>
<body>
<form method="POST" action="crawler1edit[2].php">
Enter Url:-<input type="text" name="t1">
<input type="submit" value="send" name="s1">
</form>
</body>
</HTML>
in action attribute crawler1edit[2].php is the php file containing php code written at the top
Is there a reason why you aren't just targeting the divs by ID ?
$dom->getElementById ("main");

whats wrong with my php script

hello to all at stackoverflow. (my first post) : )
i wrote this script
$file = glob("*.php"); // list all .php files
$findfile = array_search("index.php", $file); // search array for index.php
unset($file[$findfile]); // remove index.php from array
sort($file, SORT_NUMERIC); // sort array
foreach($file as $file){ include_once($file);} // include files in page
the files are 1.php,2.php,3.php etc
everytime i run it the files get included at the top of the page.
i need the files in the middle,
what am i doing wrong.
Thats the whole page as it looks for now
<?php
if(isset($_POST['ta'])){
$ta = $_POST['ta'];
if($ta != "" && strlen($ta) > 1 ){
$ta = preg_replace('#[^a-z0-9 !?.,]#i', '', $ta);
$usertextinput = '<p class="important">'.$ta.'</p>';
$pho = count(glob('*.php'));
$username_file = ($pho + 1) . ".php";
$createuser = fopen($username_file, 'w');
fwrite($createuser, $usertextinput);
header("location: index.php#bottom");}}
$userpage = '<p class="important"><span>Posts\'s:</span><br />
[username] Has 1 post's To Date.</p>';?>
$file = glob("*.php");
$findfile = array_search("index.php", $file);
unset($file[$findfile]);
sort($file, SORT_NUMERIC);
foreach($file as $file){ include_once($file);}
$userpage .= '<form name="text" method="post" action="">
<textarea name="ta" placeholder=" Enter Your Comment\'s Here ">
</textarea><br />
<a name="bottom"></a>
<p class="sub"><input type="submit" value="Post To Page" /></p>';
?>
im building a post wall (no database)
Give this a go. It will have the form's input on top,
then the Posts's: [username] Has 1 post's To Date. followed by the included files.
It's basically a placement issue.
<?php
if(isset($_POST['ta'])){
$ta = $_POST['ta'];
if($ta != "" && strlen($ta) > 1 ){
$ta = preg_replace('#[^a-z0-9 !?.,]#i', '', $ta);
$usertextinput = '<p class="important">'.$ta.'</p>';
$pho = count(glob('*.php'));
$username_file = ($pho + 1) . ".php";
$createuser = fopen($username_file, 'w');
fwrite($createuser, $usertextinput);
header("location: index.php#bottom");
}
}
$userpage = '<form name="text" method="post" action="">
<textarea name="ta" placeholder=" Enter Your Comment\'s Here ">
</textarea><br />
<a name="bottom"></a>
<p class="sub"><input type="submit" value="Post To Page" /></p>';
$userpage .= '<p class="important"><span>Posts\'s:</span><br />[username] Has 1 post\'s To Date.</p>';
echo $userpage;
$file = glob("*.php");
$findfile = array_search("index.php", $file);
unset($file[$findfile]);
sort($file, SORT_NUMERIC);
foreach($file as $file){
include_once($file);
}
?>
The reason why it isn't working, is because you are terminating the php code here:
[username] Has 1 post's To Date.</p>';?>
Remove the ?> and escape the single quote near post's; so the code block will look like this:
$userpage = '<p class="important"><span>Posts\'s:</span><br />
[username] Has 1 post\'s To Date.</p>';
$file = glob("*.php");
$findfile = array_search("index.php", $file);
unset($file[$findfile]);
sort($file, SORT_NUMERIC);
foreach($file as $file){ include_once($file);}

php with mysql, the code is not inserting into my table

Big edit:
New script:
<?php
error_reporting(E_ALL|E_NOTICE);
$nazwabazydanych = "projekt";
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['imie']);
$nazwisko = mysql_real_escape_string($_POST['nazwisko']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$adres = mysql_real_escape_string($_POST['adres']);
$nr_konta = mysql_real_escape_string($_POST['nr_konta']);
$zarobek = mysql_real_escape_string($_POST['zarobek']);
if (!$pesel || !$imie || !$nazwisko || !$telefon || !$adres || !$nr_konta || !$zarobek)
{
print "Nie zostały wypełnione wszystkie pola";
exit;
}
$db = mysql_pconnect("localhost", "root", "");
if (!$db)
{
print "Nie można nawiązać połączenia z bazą danych";
exit;
}
mysql_select_db("$nazwabazydanych");
$query = mysql_query("CALL dodaj_osobe ('$pesel','$imie','$nazwisko','$telefon','$adres','$nr_konta','$zarobek')");
?>
Action:
<form action="lool.php" method="post">
PESEL: <input type="text" name="pesel" maxlength=11 size=12><br><br>
Imię: <input type="text" name="imie" maxlength=45 size=46><br><br>
Nazwisko: <input type="text" name="nazwisko" maxlength=45 size=46><br><br>
Telefon: <input type="text" name="telefon" maxlength=9 size=10><br><br>
Adres: <input type="text" name="adres" maxlength=45 size=46><br><br>
Numer konta: <input type="text" name="nr_konta" maxlength=20 size=21><br><br>
Zarobek: <input type="text" name="zarobek" maxlength=8 size=9><br><br>
<input type="submit" value="Dodaj klienta">
</form>
And the updated error:
NONE!
Thanks guys, but I got a question:
How can I send an error if for example "nr_konta" or "pesel" or "telefon" are too low digits?
Use print_r($_POST) you should see if you get values. In your code the problem seems to be that you are not using the correct indexes. Note Pesel doesn't have a notice but imie does.
Your code for the two:
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['$imie']);
Note you have '$imie' as the index. I'm guessing copy and paste error here. From the html it seems the element is named imie.
Try this:
$imie = mysql_real_escape_string($_POST['imie']);
You need to get POST variables using the $_POST array, unless you have register_globals on.
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['imie']);
$nazwisko = mysql_real_escape_string($_POST['nazwisko']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$adres = mysql_real_escape_string($_POST['adres']);
$nr_konta = mysql_real_escape_string($_POST['nr_konta']);
$zarobek = mysql_real_escape_string($_POST['zarobek']);
// Put this after so you don't have to restate the $_POST vars
if (!$pesel || !$imie || !$nazwisko || !$telefon || !$adres || !$nr_konta || !$zarobek)
{
print "Nie zostały wypełnione wszystkie pola";
exit;
}
You're not actually getting the $_POST values.
Should be
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['imie']);
$nazwisko = mysql_real_escape_string($_POST['nazwisko']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$adres = mysql_real_escape_string($_POST['adres']);
$nr_konta = mysql_real_escape_string($_POST['nr_konta']);
$zarobek = mysql_real_escape_string($_POST['zarobek']);
And those should go before your
if (!$pesel || !$imie || !$nazwisko || !$telefon || !$adres || !$nr_konta || !$zarobek)
Also, you need to remove the $ from your $_POST values.
$_POST['$imie']
Should be:
$_POST['imie']

Categories