PHP: Remove Simple Session with Get-Method - php

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

Related

I can't seem to get my post form working correctly in PHP, despite hours of troubleshooting as well as it being a relatively simple program

I'm new to PHP and am having trouble with what seems like a relatively simple program. I can't get my $_POST['Username'] to equal my $temp and therefore never echo'success!'; even if i echo every check and i can physically see that they equal, success never prints. Any help is greatly appreciated <3.
<?php
if(isset($_POST['submit']))
{
if (file_exists('logins.txt'))
{
echo 'The file was found' . '<br>';
$file = fopen('logins.txt', 'r');
while (feof($file) == false)
{
$temp = fgets($file, 20);
if ($temp === $_POST['Username'])
{
echo'success!';
}else
{
echo 'failed' . '<br>';
echo $temp . '<br>';
echo $_POST['Username'] . '<br>';
}
};
fclose($file);
}
}
?>
<HTML>
<body>
<form action="" method="post">
Username
<input type="text" name="Username" size="30" value="">
Password
<input type="text" name="Password" size="30" value="">
<input type="submit" name="submit" value="Login">
</form>
</body>
</HTML>
Picture of the output using a textfile with the letters a - e
replace
if ($temp === $_POST['Username'])
with
if (trim($temp) == trim($_POST['Username']))
you probably have some space or something in your file
to better understand what is going on you can try to replace
echo $temp . '<br>';
echo $_POST['Username'] . '<br>';
with
var_dump($temp,$_POST['Username'])

Transfer Data from form to XML file using 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.

I can not pass a PHP SESSION and write it to text

I'm trying to pass $_POST info as $_SESSION but when it doesn't work, I don't know what is wrong in my code.
<?php
session_start();
$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];
?>
<html>
<form action="accion.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>
Second file
<?php
session_start();
if(isset($_SESSION['nombre']) && isset($_SESSION['edad'])) {
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
The following code will solve your problem:
File1.php
<html>
<form action="File2.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>
<?php
echo $_GET['msg'];
?>
File2.php
<?php
session_start();
if(isset($_POST['nombre']) && isset($_POST['edad'])) {
$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
header("Location:File1.php?msg=There was an error writing this file");
}
else {
header("Location:File1.php?msg=$ret bytes written to file";
}
}
else {
header("Location:File1.php?msg=no post data to process");
}
?>
When the form is submitted, it is submitted to File2.php
So, your first session being set and taking values as POST from it in File1.php won't work.
The best option is to set the session in the second file and then give back a message to the File1.php as shown above.
Check the code bellow. It is better to start session once at the begining of the file and check if post variable contains value to set in the session.
<?php
session_start();
if(isset($_POST['nombre']) && isset($_POST['edad'])) {
$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];
}
?>
<html>
<form action="accion.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>
<?php
if(isset($_SESSION['nombre']) && isset($_SESSION['edad'])) {
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
If you want to send the form in the same page instead using action="action.php" use action=""

I have multiple submit buttons and a validation issue with the second form

So I have two forms that are hidden when submitted. The validation for the second form isn't working. Any clue as to why?
if(isset($_POST['submit'])){
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
}
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
elseif(isset($_POST['submit2'])){
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
$isValid2 = true;
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
}
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
else{
?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?PHP
}
?>
These are all place holders BTW. The project I'm working on is much much larger, I just want to understand the whole 'hiding forms' thing before I try to implement it on a larger scale.
Thank You guys!
$isSubmitted = false;
$isValid = true;
$isValid2 = true;
$feetError = '';
$feetError2 = '';
if(isset($_POST['submit'])){
$isSubmitted = true;
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
} else {
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
}
elseif(isset($_POST['submit2'])){
$isSubmitted = true;
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
} else {
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
}
?>
<?php if(!$isSubmitted || !$isValid || !$isValid2) { ?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?php } ?>
When you submit a form, the PHP reloads the page. When the page is reloaded, it is reloaded WITH the previous posted values of your form. Therefore it will always trigger your first condition assuming the user is submitting the first form first.
You have 2 solutions. Do separate script, or use another if, instead the if - else. I'd recommend separate script though.
I recommend separate script for each form, with a header redirecting to your website after, it's easier to remember and to order your work afterwards.

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">

Categories