Login / directory creator [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
all.
I've got a big ask, and I have no idea how to go around it.
I want to make a login / signup form, which creates a directory on the server for each new user. This directory, somewhat obviously, must not be publicly accessible by other users, and must automatically copy / make it's index.php file and subdirectories.
I'm afraid that I won't have much luck, as I've never made any form of encrypted login before, let alone a fancy automated one like this.
No code as of yet. Any help appreciated!

Well you need two things:
1st of all a system that you can create the directory and the files:
1 php (if you don't mind) file to create files:
Example code:
<form action="function-create-new-file.php" method="post">
WHAT IS THE NAME OF YOUR PAGE
<input name="file_name" type="text" />
<br />
KIND OF FILE YOU WISH TO CREATE
<select name="file_ext">
<option value=".php" selected>php</option>
<option value=".html">php</option>
</select>
<br /><br /><br />
<input type="submit" class="btn" name="submit" value="Add Page" />
</form>
This file will create your files and you should include this one to process it:
<?php
if(isset($_POST['submit'])) //has the form been submitted?
{
$file_directory = "./test/"; //the directory you want to store the new file in
$file_name = strip_tags($_POST['file_name']);//the file's name, stripped of any dangerous tags
$file_ext = strip_tags($_POST['file_ext']); //the file's extension, stripped of any dangerous tags
$file = $file_directory.$file_name.$file_ext; //this is the entire filename
$create_file = fopen($file, "w+"); //create the new file
if(!$create_file)
{
die("ERROR, NOT POSSIBLE TO COMPLETE YOUR DESIRED INSTRUCTION");
}
$chmod = chmod($file, 0755); //set the appropriate permissions.
//attempt to set the permissions
if(!$chmod)
{
//error changing the file's permissions
echo("ERROR IN THE PERMISSIONS FOR THIS ACTION, PLEASE CHMOD 0755 THIS FILE AND FOLDERS");
echo "<br /><br /><br /><br /><br /><br /><br />";
include ("footer.php");
}
//defenition of the new page contante self created
if (fwrite
($create_file, "this is the content of your new page!") === FALSE)
{
echo "ERROR IN FILE: ($file)\n";
}
fclose($create_file);
//tell the user that the file has been created successfully
echo "The file was created! Take a look ate your file here - <a href='$file' target='_blank'>$file</a>";
exit; //exit the script
}
else{ //the form hasn't been submitted!
header("Location: function-create-new-file.php"); //redirect the user back to the add file page
exit; //exit the script
}
?>
Now second, you need to create a directory:
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create folders...');
}
// ...
?>
Please check also this link: How to Create a Directory
Now you need to create the login system for the users. You can do that once again in PHP.
<?php
session_start();
function encode_5t_base64($str)
{
for($i=0; $i<5;$i++)
{
$str=strrev(base64_encode($str));
}
return $str;
}
function jh_password_protection($pass_string)
{
$pass_string = encode_5t_base64($pass_string);
$pass_string = md5($pass_string);
$pass_string = sha1($pass_string);
return $pass_string;
}
function registerUser($user,$pass1,$pass2)
{
$errorText = '';
if ($pass1 != $pass2) $errorText = "Password must be the same";
elseif (strlen($pass1) < 6) $errorText = "Password too short";
$pfile = fopen("some/path/to/store/member/password.php","a+");
rewind($pfile);
while (!feof($pfile))
{
$line = fgets($pfile);
$tmp = explode(':', $line);
if ($tmp[0] == $user)
{
$errorText = "That user already exists"; // check it you made duplicated members
break;
}
}
if ($errorText == '')
{
$userpass = jh_password_protection($pass1);
fwrite($pfile, "\r\n$user:$userpass");
}
fclose($pfile);
return $errorText;
}
function loginUser($user,$pass)
{
$errorText = '';
$validUser = false;
$pfile = fopen("path/to/your/user/page.php","r");
rewind($pfile);
while (!feof($pfile)) {
$line = fgets($pfile);
$tmp = explode(':', $line);
if ($tmp[0] == $user)
{
if (trim($tmp[1]) == trim(jh_password_protection($pass)))
{
$validUser= true;
$_SESSION['userName'] = $user;
}
break;
}
}
fclose($pfile);
if ($validUser != true)
$errorText = "That went wrong"; // failed login message
if ($validUser == true) $_SESSION['validUser'] = true;
else $_SESSION['validUser'] = false;
return $errorText;
}
function logoutUser()
{
unset($_SESSION['validUser']);
unset($_SESSION['userName']);
}
function checkUser()
{
if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true))
{
header('Location: path/to/your/user/page.php'); // Your user location
exit();
}
}
?>
Now lets make the login system, first step, create a login page as you desire and place this code under content type tag:
<meta http-equiv="Pragma" content="no-cache">
Sample login system form:
<?php
if ($error == '') {
echo "Welcome";
echo "<a href='./path/to/your/member/area/'>Proceed</a>";
}
else echo " $error ";
?>
<?php if ($error != '') {?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<br/><br/>
<label>USERNAME</label>
<br/><br/>
<input name="username" type="text">
<br/><br/>
<label>PASSWORD</label>
<br/><br/>
<input name="password" type="password">
<br/><br/>
<input value="LOGIN" name="submitBtn" type="submit">
</form>
<?php }
if (isset($_POST['submitBtn'])){
?>
at the top of your page just include this:
<?php
require_once('file/that/operates/the/login.php');
$error = 'wow that was wrong';
if (isset($_POST['submitBtn'])){
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$error = loginUser($username,$password);}
?>
I think i didnt forgot nothing here, but let me know if that helps.

IMO storing the data in a database instead of files would be cleaner and easier.
However if you really need to go with separate folders here's a solution:
Create a simple login/signup form.
On signup, create the user folder in a parent folder you will name for example uploads.
Then you just have to configure your server (you can achieve this with .htaccess) so that every request to the uploads folder gets redirected to a controller (for example index.php)
In index.php, check that the user is logged in and that the folder he's trying to access belongs to him. If it does, render the requested file, if not, render an error message.

in your php file that handles the register function
after a success registration you should add
mkdir("yourtargetpath/" . $username, 0700);

Related

Creating N number of individual delete forms

I am trying to write a forum-like application where users can add comments (saved in database) and attach up to 3 files to each comment.
// SQL query to SELECT comments from database
// Echo out all comments
foreach ($resultCom as $row) {
echo $commentContent;
// Echo out up to 3 files for each comment
if (isset($commentFile1) {
echo "<a class='file-download' href='upload/$commentFile1'>$commentFileName1</a>";
}
if (isset($commentFile2) {
echo "<a class='file-download' href='upload/$commentFile2'>$commentFileName2</a>";
}
if (isset($commentFile3) {
echo "<a class='file-download' href='upload/$commentFile3'> $commentFileName3</a>";
}
}
Now I want to give the user the possibility to delete each of the files in their comment which means I need to write a delete form for each file in each comment:
<form action="delete_file.php" method="post">
<input name="id">
<input name="filename">
...
<button type="submit" name="delete-submit">Delete</button>
</form>
This same <form> would exist many times, using the same name attributes for inputs/submit buttons. If I use JavaScript to loop through every file and give each input field an unique name, I would still end up having one button that submits the information to my action="delete_file.php" which is then caught and processed in delete_file.php with something like:
if(isset($_POST['delete-file-submit'])) { delete files/update database}
I've tried a couple of approaches and each of them failed. A hint how I would set up a delete form for each of the files using their unique attributes (filename, file id, etc.) would be much appreciated.
The best way to do it. Is to use an AJAX, but if this must be in PHP here you go:
<?php
if (isset($_POST['filename'])) {
$name = $_POST['filename'];
$id= $_POST['id'];
//Direction where you store your files
$target_dir = "/";
// If u store it by name then do this:
$target_file = $target_dir . $name;
// If you store it by id then do this:
// $target_file = $target_dir . $id;
if (file_exists($target_file)) {
if(unlink($target_file)){
echo "File". $name ." was removed.";
}else{
echo "Error!". $name . "was not removed";
}
}else{
echo "Could not find file". $name;
}
}
?>
Of course it depends how do you store your data, but if it is in this same directory this is the way.
AJAX function would like like this, but you have to do some changes to fit it in your code:
const deleteFiles = (id, filename) => {
//Ask if your user wants to delete file
let confirmDelete = confirm("Are you sure you want to delete " + filename + "?");
//If yes, its doing this
if(confirmDelete){
$.post("php/deleteFile.php",
{
id: id,
filename: filename
},
function(response){
alert(response);
}
);
}
};
My idea is to create strucutre of element like this:
<div data-name="name" data-id="id">
<a>IMAGE HERE</a>
<button class="delete-file">DELETE</button>
</div>
Then search for every element with class .delete-file and set on it listener for click like this:
document.find(".deleteFile").click(function(){
deleteFile(this.parent().dataset.id, this.parent().dataset.name);
});
If you will have any problems, or dont undestand sth, let me now.
Small edit: As it was said in comments, you will need additional sanitazer for your filename to stay safe, without injections. Here is the simple one (if you will need more advanced one, you should look for it in web) :
$name = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $name );

Creating a simple Password login without the password hardcoded [PHP,Javascript,MySQL]

I'm trying to create a simple login promt on my local website. I already tried with Javascript, but I don't want the password to be hardcoded. The Users get the password by mail so there is no registration form needed. I searched on the Internet and I think it should work with PHP and Javascript. This is what i've come up with:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password',' ');
while (testV < 3) {
if (!pass1)
window.open('Website.html',"_self");
if (pass1.toLowerCase() == "password") {
alert('Correct!');
window.open('./test/sitetwo.html',"_self");
break;
}
testV+=1;
var pass1 =
prompt('Wrong Password','Try again');
}
if (pass1.toLowerCase()!="password" & testV ==3)
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Does anyone of you know how to code this? Thank you for your help.
Login prompt is just one of possible approaches to hide information on your website. You have to decide first what are you trying to hide. For instance, if you if are providing some paid information to your clients - you can send the information itself by mail (instead of password). If you want to hide some part of site from other people - you can just give it weird url, like site.com/jkhgdsdkgf
Creating login backend with php and database obviously requires your php, mysql (or other database) and server administration skills and completely depends on details of your task, so it's hard to provide a useful advice here.
In my opinion, you should use a database to store all your credentials (like username, password, etc..)
If you don't know how to do it, you should know that if you want to run your php code, you need a php server and somewhere to put your db.
Here is how to set up a php server with Apache
https://www.ultraedit.com/support/tutorials-power-tips/uestudio/local-php-mysql-dev-environment.html
Here is how to set up a db with PhpMyAdmin
https://www.siteground.com/tutorials/phpmyadmin/create-populate-tables/
You need a login.php (where you log in), a test.php page (then you put in it whatever you want) and a check_User.php page (where to control if the credentials are correct).
Login.php
<html>
<head> <title>Login</title> </head>
<body>
<form action="check_User.php" method="post" id="login_form">
<label><b>Username</b></label>
<!-- USERNAME -->
<input type="text" placeholder="Enter Username" name="username" required>
<!-- PASSWORD -->
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- LOGIN -->
<button type="submit">Login</button>
</form>
<body>
</html>
check_User.php
<?php
session_start();
$_POST["username"] = htmlspecialchars($_POST["username"]);
$_POST["password"] = htmlspecialchars($_POST["password"]);
$link = mysqli_connect("your_host", "your_db_username", "your_db_password", "your_db_name");
$query = "SELECT username, password
FROM your_db_name
WHERE username = \"".$_POST["username"]."\" AND password = \"".$_POST["password"]."\"
";
mysqli_query($link, $query);
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
/* correct match */
if(mysqli_affected_rows($link) == 1)
{
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
}
if(isset($_SESSION["username"]) && isset( $_SESSION["password"]))
header("Location:test.php");
else {
alert("Wrong username or password");
}
?>
test.php
<?php
session_start();
// not logged in, not showing this page
if((!isset($_SESSION["username"]) || !isset( $_SESSION["password"]))
header("Location:login.php");
?>
<html>
....whatever you want this page to do
</html>

Populate a form field with page URL

I have a downloads section on a client wordpress site. Using Download Monitor plugin. They are protected with a form using the Ninja Forms addon for the DM plugin so users have to register details to access the download.
I'd like to add the ID from the download form URL to a field in the form so client can see which download that form registration is associated with.
The generated url of the unlock registration form for a particular download is similar to the following:
https://domain.com/no-access/download-id/572/
I have found how to do this with a query string ( https://ninjaforms.com/how-to-auto-populate-form-fields-using-query-string/ ) but not sure how to do it with the IDs in my url above.
Ideally I'd like to translate that ID to the actual download title too if that's possible.
Can anyone please advise?
Thanks!
If the id is always at the end of the url that way, you can use basename to grab it very simply:
<?php
// in your code you will do this:
//$url = $_SERVER['REQUEST_URI'];
// but for this example, i need your url:
$url = 'https://domain.com/no-access/download-id/572/';
// grab the basename:
$id = basename($url);
echo "($id)"; // (572)
ADDITION
Now that you can find that $id which is the download-id requested, put it in a variable that you can use within the code that is writing your ninja form. For instance:
$url = $_SERVER['REQUEST_URI'];
// this was just for debugging...now comment it out
// $url = 'https://domain.com/no-access/download-id/572/';
// echo "($id)"; (572)
$id = basename($url);
// instead put it in a variable you can use in your form
$GLOBALS['requested-download-id'] = (integer) $id;
Now wherever you have the code for your ninja form do something like this:
<form id="ninja-form" action="your-action" method="POST">
<?php
// sanity check...something may have gone wrong
if (empty($GLOBALS['requested-download-id'])) {
$download_id = 'NOT FOUND';
} else {
$download_id = $GLOBALS['requested-download-id'];
}
?>
<input value="<?php echo $download_id; ?>" type="hidden" name="download-id">
EVEN MORE SIMPLIFIED - DO IT ALL AT ONCE
<form id="ninja-form" action="your-action" method="POST">
<?php
$id = basename($_SERVER['REQUEST_URI']);
// be sure you ended up with a number
$id = (integer) $id;
if (empty($id)) {
$download_id = 'NOT FOUND';
} else {
$download_id = $id;
}
?>
<input value="<?php echo $download_id; ?>" type="hidden" name="download-id">

Many spaces before javascript result

I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.

Passing Variable From JavaScript to PHP without Page Refresh [duplicate]

This question already has answers here:
Passing javascript variable to php without refreshing the page
(2 answers)
Closed 8 years ago.
I'm writing some code that has a variable in JavaScript that must be passed into the PHP script in the same document. The user input will be used to be scraped from some external site.
The JavaScript variable is HtmlLink, and it needs to be passed to the PHP code where it says INSERT HTMLLINK VARIABLE HERE without reloading the page.
<!DOCTYPE HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT>
type = "text/javascript"
function testResults (form) {
var TestVar = form.inputbox.value + ".html";
var HtmlLink = "www.mp3skull.com/mp3/" + TestVar;
document.write(HtmlLink);
}
</SCRIPT>
<?php
$contents = file_get_contents('INSERT HTMLLINK VARIABLE HERE');
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($contents);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$element = $xpath->query('//div[#id="right_song"]/div[3]/div[1]/div[1]/a')->item(0)-
echo $element;
?>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET"> Song Name <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Search" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
If you want to do some searching, first of course build the proper URL first, then from there search/scrape the site, actually the base code is already working so its time to build on that. You can do something like this: Sample Demo
$main_url = 'http://www.mp3skull.com/mp3/';
$results = array();
if(isset($_POST['submit'])) {
// handle input (sample: hot mallets)
$input = preg_replace('/[\s]+/', '_', strtolower(trim($_POST['input'])));
$main_url .= $input . '.html'; // turns to hot_mallets.html
$contents = #file_get_contents($main_url);
if($contents !== false) { // simple error checking
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($contents);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$search_results = $xpath->query('//div[#id="song_html"]');
if($search_results->length > 0) {
foreach($search_results as $result) {
// each row result, put it inside the array
$results[] = $xpath->query('//div[#id="right_song"]/div[3]/div[1]/div[1]/a', $result)->item(0)->getAttribute('href');
}
} else {
echo 'Zero results';
}
} else {
echo 'Some error on getting results from external site.';
exit;
}
}
?>
<form method="POST">
<label for="inputbox">Song Name: <input type="text" id="inputbox" name="input"/ ></label>
<input type="submit" name="submit" />
</form>
<?php if(!empty($results)): ?>
<h3>Search Results:</h3>
<ul>
<?php foreach($results as $result): ?>
<li><?php echo $result; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Because of the way that pages are loaded on the web this doesn't really make sense in most setups. The PHP runs on the server, sends the javascript and HTML to the client and then the javascript executes on the client. At that point in the process it's too late for javascript to set a variable in php because php is already finished loading. You could use ajax to send the request from javascript. If you did that the page would load like this:
(Server gives initial HTML/javascript/CSS to client)->(Client runs javascript which makes request to server (after the user has entered the data))->(Result of external request returns and is now usable by javascript).
You don't really need to do that for what you're trying to do though - fetch a link off of another page. What you should really do is write your javascript stuff in php and then echo out the link. Then, set the form to submit back to the same page. Here's an example:
<!doctype html>
<head>
<title>Fetch Link</title>
</head>
<body>
<?php
ini_set('display_errors', 0);
if (isset ($_GET['search_term']))
{
$searchTerm = $_GET['search_term'];
$searchPage = "http://www.example.com/".$searchTerm.'.html';
$searchPageContents = file_get_contents($searchPage);
$feedBack = '';
$failedMessage = 'Sorry, we couldn\'t match your search =(';
if ($searchPageContents !== FALSE)
{
$searchPageDom = new DOMDocument();
if (!$searchPageDom->loadHTML($searchPageContents))
$feedBack = $failedMessage;
else
{
$searchPageXpathWrapper = new DOMXpath($searchPageDom);
$searchLinkNode = $searchPageXpathWrapper
->query('SOME QUERY HERE')
->item(0);
$searchLink = $searchPageDom->saveHTML ($searchLinkNode);
$feedBack = $searchLink;
}
}
else
$feedBack = $failedMessage;
}
else
$feedBack = 'Please enter a search term';
echo $feedBack.'<br>';
?>
<form name="myform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="GET">
<label for='search_name' for='search_term'>Search Term</label>
<input type="text" name="search_term">
<input type='submit' value='Search'>
</form>
</body>
</html>
Of course, unless you have a particularly good reason to be fetching the link from the page instead of just generating the link yourself - you can generate the link yourself with minimal javascript and save the round trip to the server and guard against the possibility of the page formatting changing on the other side.

Categories

Resources