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">
Related
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 );
I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.
I have a form and I have been developing this website with my localhost and it is working perfect. But when I moved the files to my dedicated server it no longer gets any of the values when I submit the form. I have narrowed it down to two things. A either my server has restricted configurations on the form being submitted but I do not use global variables to get the values so that shouldnt be the problem or the php on the server is older and not allowing me to submit the values the server version i found out is <5.6. Here is my form code:
<form id="company-form" action="scripts/create-library.php" method="post" enctype="multipart/form-data">
<button id="hide-form"><img src="images/minus.png"/></button>
<h3>Add Library Item Form</h3>
<input class="c-name" type="text" name="file-display-name" placeholder="File Display Name"/>
<select class="companies-dd" name="companies">
<?php
require_once("../../scripts/connection.php");
// Select all companies and related data
$sql = "SELECT company_id, company FROM companies ORDER BY company_id";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($c_id, $c);
while($stmt->fetch()){
echo "<option value='".$c_id."'>".$c."</option>";
}
?>
</select>
<select class="companies-dd" name="library-cats">
<?php
// Select all companies and related data
$sql = "SELECT library_category_id, library_category FROM library_categories ORDER BY library_category_id";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($l_id, $l);
while($stmt->fetch()){
echo "<option value='".$l_id."'>".$l."</option>";
}
$conn->close();
?>
</select>
<input id="uploadFile" class="image-name" type="text" name="library-file-name" placeholder="No Logo File Chosen" disabled="disabled"/>
<input id="uploadBtn" type="file" name="library-file"/>
<input type="submit" value="Create Item"/>
</form>
This is added the page via ajax call on a button click.
Then the script that I run after the form is submitted is
<?php
session_start();
ini_set('display_errors',1);
error_reporting(-1);
$display = trim($_POST["file-display-name"]);
$company = trim($_POST["companies"]);
$lib_cat = trim($_POST["library-cats"]);
if(empty($display) || empty($company) || empty($lib_cat)){
$_SESSION["errormsg"] = "Required information is missing please fill out all required fields.";
header("Location: ../library.php");
}
else{
$file_name = $_FILES['library-file']['name'];
$tmp_name = $_FILES['library-file']['tmp_name'];
$file_size = $_FILES['library-file']['size'];
$file_type = $_FILES['library-file']['type'];
$fp = fopen($tmp_name, 'r');
$content = fread($fp, filesize($tmp_name));
$content = base64_encode($content);
fclose($fp);
if(!get_magic_quotes_gpc()){
$file_name = addslashes($file_name);
}
if(empty($content)){
$_SESSION["errormsg"] = "Required information is missing please fill out all required fields (File).";
header("Location: ../library.php");
}
else{
require_once("connection.php");
// Insert the logo into the companies photo table
$sql = "INSERT INTO library_items(filename, mime_type, file_size, file_item, display_name, company_id, library_category_id) VALUES(?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssssss', $file_name, $file_type, $file_size, $content, $display, $company, $lib_cat);
if(!$stmt->execute()){
$_SESSION["errormsg"] = "Failed to add library item: ".mysqli_error();
header("Location: ../library.php");
}
}
unset($_SESSION["errormsg"]);
$_SESSION["successmsg"] = "Library Item successfully added into the database.";
header("Location: ../library.php");
}
?>
It gives me the errors with the variables saying that they are undefined index's for the form names.
I have read other posts but none of them has helped me. Is there something I am not seeing or I have to change on my server for me to use this?
Well it looks like the two files I had for testing the upload and display ended up corrupt when I downloaded them. This was causing the server to throw and error saying that the text was outside the US-ASCII range. Since this was not able to be display it didnt transfer any of the forms values. That was the weirdest bug I ever had I guess I will have to start testing my pdfs for errors also.
I am trying to make a php file in which I will send data from database and through them i will show 0 or 1. In my example I have a table with two user_ids and a parameter in which takes the value 0 or 1. From test.php I fill a form by giving the user_id and I submit it. When I submit it for this user the parameter in becomes 0 if it was 1 and vise versa. In next.php I use <iframe src="show.php"> and in show.php I show the user_id and in. What I want is when I submit a user_id, immediately to see the changes in show.php. What I did is to refresh the page all the time but it was too disturbing. Can you suggest something else? Here is some code.
test.php
<?php
require_once 'include_php/db.php';
global $dbcnx;
?>
<form action="" method="get">
<input type="text" name="id"/>
<input type="submit" name="submit"/>
</form>
<?php
if(isset($_GET['submit']))
{
$id = $_GET['id'];
$res = mysqli_query($dbcnx, "select * from people where uid = ".$id.";");
$row = mysqli_fetch_array($res);
if($row['in'] == 0) $up = mysqli_query($dbcnx, "UPDATE `people` SET `in`=1 WHERE uid=".$id.";");
else $up = mysqli_query($dbcnx, "UPDATE `people` SET `in`=0 WHERE uid=".$id.";");
}
show.php
<?php
require_once 'include_php/db.php';
global $dbcnx;
$res = mysqli_query($dbcnx, "select * from people");
while($row = mysqli_fetch_array($res))
{
echo $row['uid']." ".$row['in']."<br/>";
}
print "<script>window.location.replace('show.php');</script>"; //here is the disturbing refresh
next.php
<iframe src="show.php">
What you want is live updates without hard refreshing your page. You can achieve this by using AJAX requests, or by using websockets.
With an ajax request, you could easily set a timeout function to refresh your iframe every x-seconds/minutes.
This question gives a good description on how to give it a go.
I'm trying to have the mail.php script identify the page that called the script, and return the user to that page and if the form didn't validate, was empty, etc. When I click on submit, it just 404's.
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "email#email.com";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email'];
$comments = $_REQUEST['comment'];
$fname = $_REQUEST['first-name'];
$lname = $_REQUEST['last-name'];
$filename = debug_backtrace();
$page = $filename[0]['file'];
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments) || empty($fname)) {
echo "<script type=\"text/javascript\">window.alert('Please fill in the required fields.');
window.location.href = $page;</script>";
exit;
}
// If email injection is detected, redirect to the error page.
elseif (isInjected($email_address)){
echo "<script type=\"text/javascript\">window.alert('Please, Try Again.');
window.location.href = $page;</script>";
exit;
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail("$webmaster_email", "Feedback Form Results", $comments, "From: $email_address");
echo "<script type=\"text/javascript\">window.alert('Thank You for contacting us!');
window.location.href = $page;</script>";
exit;
}
?>
No need for debug_backtrace(). To get the referring page, you could replace this:
$filename = debug_backtrace();
$page = $filename[0]['file'];
With this:
$page = $_SERVER['HTTP_REFERER'];
However, $_SERVER['HTTP_REFERER'] is unreliable according to the PHP docs:
This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So another solution is to add an additional field in the referring form and retrieve it in the PHP script e.g.
<input name="referrer" type="hidden" value="<?php echo $_SERVER['PHP_SELF'];?>"/>
Then:
$page = $_REQUEST['referrer'];