Transfer Data from form to XML file using PHP - php

I am working on a project for school, so needless to say I am a beginner at all of this. I am having trouble passing my form data to my XML file. I am receiving a
Fatal error: Call to a member function writeXML() on a non-object from save-xml.php line 53
which points to my define-classes.php. I have defined the ticket class in the define-classes file. I am writing just a help ticket site where users can input and view tickets. below is the code.
<?php
// load required files
require "define-classes.php";
require "load-xml.php";
require "save-xml.php";
// save form to xml file
save_xml( $_POST, "tickets.xml", "append" );
?>
<link rel="stylesheet" href="site.css">
</head>
<body>
<?php include 'header.php'; ?>
<?php include 'nav.php'; ?>
<main>
<div class="row">
<div class="sidel">
</div>
<div class="main">
<h2>Create a New Ticket</h2>
<form name="newTicket" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<fieldset id="custInfo">
<legend><h3>Customer Information</h3></legend>
<label>First Name:<br>
<input type="text" name="fname" id="fname" size="40" required></label>
<br>
<label>Last Name: <br>
<input type="text" name="lname" id="lname" size="40" required></label>
<br>
<label>Phone: <br>
<input type="text" name="phone" id="phone" size="40" required></label>
<br>
<label>School / Building: <br>
<input type="text" name="loc" id="loc" size="40" required></label>
<br>
<label>Room Number: <br>
<input type="text" name="room" id="room" size="40" required></label>
</fieldset>
<fieldset id="devInfo">
<legend><h3>Device Information</h3></legend>
Device Type: <br>
<select size="1" name="device" id="device" required>
<option size="30" value="">Select Device </option>
<option value="Laptop">Laptop</option>
<option value="Desktop">Desktop</option>
<option value="Touch TV">Touch TV</option>
<option value="Projector">Projector</option>
<option value="Phone">Phone</option>
<option value="iPad">iPad</option>
<option value="Chromebook">Chromebook</option>
</select>
<br>
<label>Manufacturer: <br>
<input type="text" name="manu" id="manu" size="40"></label>
<br>
<label>Model:<br>
<input type="text" name="model" id="model" size="40"></label>
<br>
<label>Serial Number: <br>
<input type="text" name="serial" id="serial" size="40"></label>
<br><br><br>
</fieldset>
<fieldset id="description">
<legend>Description</legend>
Let Us Know What You Are Experiencing:<br>
<textarea name="comments" id="comments" cols="60" rows="10" required>Enter the Description of your Ticket here!</textarea>
<input type="hidden" name="status" value="open">
<input type="submit" value="Create New Ticket">
<input type="reset" value="Clear Form">
</fieldset>
</form>
</div>
<div class="sider">
</div>
</div>
</main>
<?php include 'footer.php' ?>
</body>
</html>
The define file
// Define the tickets class
class ticket
{
// required id property
var $id;
// define sub properties
var $fname;
var $lname;
var $phone;
var $loc;
var $room;
var $device;
var $manu;
var $model;
var $serial;
var $status;
var $comments = array();
// constructor
function ticket ($newID)
{
$this->id = $newID;
}
// convert object to XML string
function writeXML()
{
// Define some special characters to help format output
$tab = "\t";
$newline = "\n";
// opening tag
$xml_string = $newline . $tab . '<ticket id="' . $this->id . '">' . $newline;
// sub tags
$xml_string .= $tab . $tab . '<fname>' . $this->fname . '</fname>' . $newline;
$xml_string .= $tab . $tab . '<lname>' . $this->lname . '</lname>' . $newline;
$xml_string .= $tab . $tab . '<phone>' . $this->phone . '</phone>' . $newline;
$xml_string .= $tab . $tab . '<loc>' . $this->loc . '</loc>' . $newline;
$xml_string .= $tab . $tab . '<room>' . $this->room . '</room>' . $newline;
$xml_string .= $tab . $tab . '<device>' . $this->device . '</device>' . $newline;
$xml_string .= $tab . $tab . '<manu>' . $this->manu . '</manu>' . $newline;
$xml_string .= $tab . $tab . '<model>' . $this->model . '</model>' . $newline;
$xml_string .= $tab . $tab . '<serial>' . $this->serial . '</serial>' . $newline;
$xml_string .= $tab . $tab . '<status>' . $this->status . '</status>' . $newline;
// loop for comments array
foreach ($this->comments as $comments)
{
$xml_string .= $tab . $tab . '<comments>' . $comments . '</comments>' . $newline;
}
// closing tag
$xml_string .= $tab . '</ticket>' . $newline;
// return xml string
return $xml_string;
}
// function to add data to properties
function addData ($prop, $new_value)
{
// convert property to lower case
$prop = strtolower($prop);
// check if the property has been defined as an array
if ( is_array($this->$prop) )
{
// if array add a new element to the end of the array
$temp_array = array( $new_value );
$this->$prop = array_merge ( $this->$prop, $temp_array );
}
else
$this->$prop = $new_value;
}
}
?>
The save file
<?php
// You can call the function save_xml() to output an array of objects into
// a file in XML format. The function requires three arguments.
// The first argument should be the name of the PHP array to save.
// The second argument is the name of the XML file to save the content in.
// The third argument should be either "overwrite" or "append", depending on
// whether you wish to replace the existing file with just the contents
// of the current array, or if you want to add the contents of the current
// array to the end of the existing file.
function save_xml ($object_array, $filename, $type_of_save)
{
// if you are appending data, open the existing file and remove the
// closing root tag so that more data objects can be appended.
if ($type_of_save == "append")
{
// read in the old contents as a single string
$old_file_contents = file_get_contents($filename);
if (!$old_file_contents)
{
die("Error opening file $filename!");
}
// find the position of the closing root tag, and if found,
// make a substring starting at the beginning and ending
// before the closing root tag, then output it back to the file.
$end_tag_position = strpos( $old_file_contents, "</$filename>");
if (!$end_tag_position === false)
{
$new_file_contents = substr( $old_file_contents, 0, $end_tag_position );
file_put_contents($filename, $new_file_contents);
}
// re-open the file to append new content.
$fp = fopen($filename, "a+b");
if (!$fp) { die("Error opening file $filename."); }
}
else
{
// if the type_of_save is not append, open the file and overwrite it.
$fp = fopen($filename, "w+b");
if (!$fp) { die("Error opening file $filename."); }
// output the XML declaration and the opening root element tag.
write_line($fp, "<?xml version=\"1.0\"?>\n\n");
write_line($fp, "<$filename>\n");
}
// output the array objects to the file, using the writeXML method of the class.
foreach ($object_array as $current_object)
{
write_line($fp, $current_object->writeXML());
}
// output the closing root tag
write_line($fp, "\n</$filename>");
fclose($fp);
}
// This function writes the content to the specified file, and provides
// an error message if the operation fails.
function write_line ($fp, $line)
{
if (!fwrite($fp, $line))
die ("Error writing to file!");
}
// The function file_put_contents from the PHP web site does not exist
// in our server's version of PHP. This creates it.
if (!function_exists('file_put_contents'))
{
define('FILE_APPEND', 1);
function file_put_contents($filename, $content, $flags = 0)
{
if (!($file = fopen($filename, ($flags & FILE_APPEND) ? 'a' : 'w')))
return false;
$n = fwrite($file, $content);
fclose($file);
return $n ? $n : false;
}
}
?>
And the XML File
<tickets.xml>
</tickets.xml>

Talk about re-inventing the wheel, I tried using the above code as most of it was provided by my instructor for us to incorporate, however, I found that all this was for not as three simple php commands allowed to me to append into my XML no problem. I ended up using a mixture of CreateElement(), appendChild(), and createAttribute(). Thank you for the looking at this with me though guys.

Related

How do i create .txt file with PHP code in VScode

I have just started to learn PHP, and started it with VS Code
But unfortunately when trying to create a new simple 'data.txt' file, but without any luck. here is the code
<?php
mb_internal_encoding('UTF-8');
echo '<pre>' . print_r($_POST, true) . '</pre>';
$pageTitle = 'Форма';
include 'header.php';
$groups = [1 => 'Приятели', 2 => 'Бивши', 3 => 'Бъдещи', 4 => 'Колеги'];
$error = true;
if ($_POST) {
$username = trim($_POST['username']);
$phone = trim($_POST['phone']);
$selectedGroup = (int) $_POST['group'];
if (mb_strlen($username) < 4) {
echo '<p>Името е прекалено късо</p>';
$error = true;
}
if (mb_strlen($phone) < 6 || mb_strlen($phone) > 12) {
echo '<p>Невалиден Телефон</p>';
$error = true;
}
if (!array_key_exists($selectedGroup, $groups)) {
echo '<p>Невалидна Група</p>';
$error = true;
}
if (!$error) {
$result = $username . '!' . $phone . '!' . $selectedGroup;
file_put_contents('data.txt', $result);
}
}
?>
Списък
<form method="POST">
<div> Име: <input type="text" name="username" /> </div>
<div>Телефон <input type="text" name="phone" /> </div>
<div>
<select name="group">
<?php foreach ($groups as $key => $values) {
echo '<option value="' . $key . '">' . $values . '</options>';
} ?>
</select>
</div>
<div><input type="submit" name="Добави" /> </div>
</form>
<?php include 'footer.php';
?>
Every time i reload the server it does not create any new '.txt' file, even when i try with different values i am not able to create.enter code herenter code heree
I looked up to find different information, i have tried to change the permissions to -- 755 -- 'Path' ==>> /var/www/html.
The same goes to debugging, i have tried but no errors are displaying, assuming it is some small thing i tried to look into the code 100 times but with no result.
Thanks in Advance.
There's no condition where $error could be false (you initialize it to true and only set it to true), so you can never enter the if(!$error){ block.
You'll probably want to change that initial
$error = true;
to
$error = false;

PHP fopen not working

I just can't figure this out, I keep getting Unable To Create Group.
What I'm attempting to do is you submit a forum, and it creates a file with some info in it. If the group name already exist(the file) then tell them that. Though I keep getting as I stated "Unable To Create Group" as my die message.
This is the PHP part:
<?php
if($_POST['ownername'] && $_POST['groupname']){
$ownername = htmlspecialchars($_POST["ownername"]);
$groupname = htmlspecialchars($_POST["groupname"]);
echo 'Owner is ' . $ownername . ' and the group is ' . $groupname;
$groupfile = '/groups/' . $groupname . '.txt';
if(file_exists($groupfile) == false){
$newgroup = fopen($groupfile, 'w') or die("Unable to create group");
$txt = "Users:" . $ownername;
fwrite($newgroup, $txt);
fclose($myfile);
echo "<font style='color:green'>The group has been created! You may access it <a href='chat.php?group=" . $groupname . "'>here</a></font>";
} else {
echo "<font style='color:red'>The group name is taken, please use another name or wait for it to be released</font>";
}
}
?>
Then this is my HTML part:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
<input type="text" name="ownername" placeholder="Username"/>
<input type="text" name="groupname" placeholder="Group Name"/>
<input type="submit" value="Create"/>
</form>
Any and all help is appreciated, thank you very much!
If the filename doesn't exist yet, use 'x' instead of 'w' to create a file and allow writing into.
$newgroup = fopen($groupfile, 'x');

How to write to file with same name as HTML form field

I have made an attempt to write a PHP code that takes the contents of an HTML form then write them into a file. I have that down just fine, but I have another problem. I want to take an input of a field in the form and make it the file name that I am writing to.
Here is my PHP code:
<?php
if(isset($_POST['forwhom']) && isset($_POST['importance']) && isset($_POST['message'])) {
$file = "students.html";
$data = nl2br('-' . $_POST['forwhom'] . ':' . ' ' . $_POST['message'] . ' ' . $_POST['importance'] . "\n");
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "Success! Student added to database.";
}
}
else {
die('no post data to process');
}
?>
Currently, I am writing to the file "students.html" However, I want to write to the file "Dad.html", which happens to be the input in the field by the name of forwhom.
Basically, I am asking this: What do I use to replace "students.html" (line 3) so that the file name will be the same as the input of the field forwhom?
I apologize if that didn't make any sense. Thank you very much!
First check if data has been posted on your form using $_SERVER['REQUEST_METHOD'] == "POST".
For simplicity sake save all your "POST" requests in a variable eg.
$file = $_POST['forwhom'];
$importance = $_POST['importance'];
$message = $_POST['message'];
I sometimes find it much easier using empty() instead of isset().
Create a variable, lets say $status which would store all your messages, then any where in your HTML section you just use the $status to display the appropriate message to the user. Check below how i make use of $status in the form.
By doing so is much cleaner and makes your code more dynamic in a sense.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$file = $_POST['forwhom'];
$importance = $_POST['importance'];
$message = $_POST['message'];
if (!empty($file) && !empty($importance) && !empty($message)) {
$data = nl2br('-' . $file . ':' . ' ' . $message . ' ' . $importance . "\n");
$file .= ".html";
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if ($ret == true) {
$status = "Success! Student added to database.";
} else {
$status = "Error writing to file!";
}
} else {
$status = "Please enter name, email and message";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<ul>
<li>
<label for="name">Name: </label>
<input type="text" name="forwhom" id="forwhom">
</li>
<li>
<label for="email">Email: </label>
<input type="text" name="importance" id="importance">
</li>
<li>
<label for="message">Your Message: </label><br>
<textarea name="message" id="message"></textarea>
</li>
<li>
<input type="submit" value="Go!">
</li>
</ul>
<?php if(isset($status)): ?>
<p><?= $status; ?></p>
<?php endif; ?>
</form>
</body>
</html>
I added a form just for explanation sake, hope it helps.

How can I create a Searchstring for a Google AJAX Search API?

i have this code to get the search resutls from the api:
querygoogle.php:
<?php
session_start();
// Here's the Google AJAX Search API url for curl. It uses Google Search's site:www.yourdomain.com syntax to search in a specific site. I used $_SERVER['HTTP_HOST'] to find my domain automatically. Change $_POST['searchquery'] to your posted search query
$url = 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&start=20&q=' . urlencode('' . $_POST['searchquery']);
// use fopen and fread to pull Google's search results
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
}
fclose($handle);
// now $body is the JSON encoded results. We need to decode them.
$json = json_decode($body);
// now $json is an object of Google's search results and we need to iterate through it.
foreach($json->responseData->results as $searchresult)
{
if($searchresult->GsearchResultClass == 'GwebSearch')
{
$formattedresults .= '
<div class="searchresult">
<h3>' . $searchresult->titleNoFormatting . '</h3>
<p class="resultdesc">' . $searchresult->content . '</p>
<p class="resulturl">' . $searchresult->visibleUrl . '</p>
</div>';
}
}
$_SESSION['googleresults'] = $formattedresults;
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
?>
search.php
<?php
session_start();
?>
<form method="post" action="querygoogle.php">
<label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" />
</form>
<?php
if(!empty($_SESSION['googleresults']))
{
echo $_SESSION['googleresults'];
unset($_SESSION['googleresults']);
}
?>
but with this code, I cant add a searchstring..
how can i add a search string like search.php?search=keyword ?
thanks
ok, have it! changed into this code:
querygoogle.php
$_SESSION['googleresults'] = $formattedresults;
header("Location: search.php?searchquery=" . $_GET['searchquery']);
exit;
... &start=20&q=' . urlencode('' . $_GET['searchquery']);
search.php
<form method="get" action="querygoogle.php">

PHP: Remove Simple Session with Get-Method

I want to Remove the Sessions from this php code, actually if someone searches i get this url search.php?searchquery=test but if I reload the page, the results are cleaned. how can I remove the Sessions to get the Results still, if someone reloads the page? this are the codes:
search.php
<?php
session_start();
?>
<form method="get" action="querygoogle.php">
<label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" />
</form>
<?php
if(!empty($_SESSION['googleresults']))
{
echo $_SESSION['googleresults'];
unset($_SESSION['googleresults']);
}
?>
querygoogle.php
<?php
session_start();
$url = 'http://www.example.com';
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
}
fclose($handle);
$json = json_decode($body);
foreach($json->responseData->results as $searchresult)
{
if($searchresult->GsearchResultClass == 'GwebSearch')
{
$formattedresults .= '
<div class="searchresult">
<h3>' . $searchresult->titleNoFormatting . '</h3>
<p class="resultdesc">' . $searchresult->content . '</p>
<p class="resulturl">' . $searchresult->visibleUrl . '</p>
</div>';
}
}
$_SESSION['googleresults'] = $formattedresults;
header("Location: search.php?searchquery=" . $_GET['searchquery']);
exit;
?>
thank you for your help!!
This is against google's terms of use. Use google API

Categories