I'm new to programming and Web Development all together. So please take it easy on me.
Right. My question is I have a file that users will download from the website. What I want to do is create a function that keeps track of the amount of times it has been downloaded. I have no problem in display the current count.
How can I update the Mysql database when a new click has been made?
So this is my link:
Download
This is my counter (retrieves amount of times it has been downloaded):
<h6 class="downloaded-count text-center"> Downloaded: <?php echo file_counter() ?></h6>
File counter:
function file_counter(){
$db = DB::getInstance();
$query = $db->query("SELECT temp_downloads FROM templates");
if(#$query->count()){
foreach($query->results() as $query_run){
$valid_count = $query_run->temp_downloads;
}
} return $valid_count;
}
Is there a way I could use html form with post method? and then create a function file_counter_inc() which receives form name or button name ? Or maybe use Javascript onclick method? which receives php function? P.s Don't know if the javascript thing would work
Update
OK I figured out how to increment the Mysql field after user clicks the button. Another proble m arise.... This is what I did. Looking at bellow code. How can I force a download now? I can't place the file into the form since the method now is PHP_SELF. So I cant place another method there.
This is my html now.
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="Download" name="download_counter">
</form>
<p class="text-center"> Downloaded: <?php echo file_counter() ?> </p>
This is file_counter_inc() method:
function file_counter_inc($tempID){
$db = DB::getInstance();
$query = $db->query("UPDATE templates SET temp_downloads = temp_downloads + 1 WHERE temp_id = '{$tempID}'");
}
Php uses Post method to know whether button was clicked.
if( isset($_POST['download_counter']))
{
file_counter_inc($website->temp_id);
}
How can I force a download after the file_counter_inc() method has been executed?
You can create a PHP function to handle the download requests, and increment the counter inside the function, for example, create download.php and pass the requested file as a GET parameter:
file_counter_inc(); // <-- The increment happens here
$file_url = $_GET['file_url'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"MyFile\"");
readfile($file_url);
Then you output the download link like this:
Download
Related
I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>
I want to send a preselected file (/tmp/test.txt) to a website (upload site) and get the response (shows a link to the uploaded file).
I have googled so much and didnt get it to work.
the following easy html form is working.
<html>
<body>
<form action="http://upload-site/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="testfile" value="select file" >
<input type="submit" value="Submit">
</form>
</body>
</html>
so i all need to send is the enctype und the file with info "testfile=test.txt" i guess ??
the form ofc wants me to select a file...what i dont want.
it has to be preselected since i want to automate the upload procedure and work with the response that gives me the link to the file.
how do i do that in php/curl/js ?
You have to use different approach to send your file to another website. You're transferring file over the server(technically over two machine). You could do it by FTP. Fortunately, PHP provides you functionality for this.
<?php
$file = 'somefile.txt'; // Path of the file on your local server. should be ABSPATH
$remote_file = 'somefile.txt'; // Path of the server where you want to upload file should be ABSPATH.
// set up basic connection
$conn_id = ftp_connect($ftp_server); // $ftp_server can be name of website or host or ip of the website.
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
I've never tried from localhost to website (Server). Give it try and let me know your feedback for this.
Without seeing your upload.php its hard to help you, but if you want to copy the selected uploaded file to a destination on your server and then display it in the browser you need to do something like this in the file upload.php which is your forms action.
//Get the file name
$file_name = $_FILES["testfile"]["name"];
//Create destination path
$dest = "/path/to/where/you/want/the/file/" . $file_name;
//Move the file
move_uploaded_file($_FILES["testfile"]["tmp_name"], $dest)
//View the file
echo "<script> location.href='http://someip/$dest'; </script>";
I think you need to change this
<input type="file" name="testfile" value="select file">
To this
<input type="file" name="testfile" id="testfile" value="select file">
You will notice im using JavaScript to redirect the browser to the newly uploaded file, you can also just send a new HTTP header using native PHP.
header("Location: http://example.com/thefile.txt") or die("Failed!");
You can read about what you think is the best approach for the redirect here.
I hope this helps?
I was hoping someone could help me/guide me in the right direction with this issue.
I want to create a button called "Send File". When this button is clicked, a directory on my web server is opened where multiple PDF files are stored. I must then have the option of selecting multiple files. Once I click "Okay/Confirm", a new mail must be opened on Outlook with the files added as attachments.
So it's basically like adding an attachment on your local computer through Outlook, but the only difference is the "source" of the file is in a directory on my web server.
I hope this question isn't too broad or not specific enough. I have really no idea how to go about this, so any tips are appreciated. I will attempt to write some code but I don't have a clue on how I'd do this.
Here is a quick example:
print_r($_POST['fileName']);
$array = array(
'file1.pdf',
'file2.pdf',
'file3.pdf',
'file4.pdf',
'file5.pdf',
'file6.pdf',
'file7.pdf',
'file8.pdf',
);
echo '<form action="" method="post">';
foreach($array as $file){
echo $file . '<input name="fileName[]" type="checkbox" value="' . $file . '"><br>';
}
echo '<input name="submit" type="submit" value="Submit">';
echo '</form>';
This isn't possible.
There is no way for the browser to tell the user's email client (Outlook or otherwise) to start a new email with specific attachments (no matter what the source of the attachments).
Instead, you could send the email directly from the server.
I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?
I need to use the input from a user to create a filename.html on the server they are attached to. The program normally takes the input and writes it TO an existing html file. In this one case, I need to add the ability to create the file they are writing to before they begin writing to it.
While I am wishing :) I would like to start out by showing the user a directory of the html files are already there in case someone else has already created it.
The logic of the input would be to use the data input to create the file IF the file does not already exist. If it does exist, then they would open to the pre-existing file by that name.
This is an adaptation of "Microchat" php script which normally writes to msg.html.
It works fine as-is but this one project needs the added ability of creating multiple Name.html files and then letting the user continue as normal except they will be writing to the filename they chose or created rather than the using the generic msg.html. I have been working on the assumption that I will have to create a variable of their input to use for creating the file.
The entire script for Microchat is only 144 lines. But too long to post in its entirety
It can be viewed at www.phptoys.com. The area I need help with is this:
function createForm () {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table align="center">
<tr><td colspan="2">Please eneter a nickname to login!</td></tr>
<tr><td>Your name: </td>
<td><input class="text" type="text" name="name" /></td></tr>
<tr><td colspan="2" align="center">
<input class="text" type="submit" name="submitBtn" value="Login" />
</td></tr>
</table>
</form>
<?php
This is normally used to create the users login. I have tried a few variations on the input to achieve a variable for creating a file but sadly, I know my limits. I doubt I will find a way without help.
I am not sure what you are trying to make. Possibly you can use database for the purpose but purpose is not clear to me so I don't know. By the way you can use following approach. Then you can do customization as per your requirements.
<?php
$fileName = "newHTMLFileName";
$path= "../yourFolder/".$fileName.".html";
if (!file_exists ($path))
{
$code = "<!DOCTYPE html><html><body><h1>Information</h1></body></html>";
$handle = fopen ($path, "w");
$write = fwrite ($handle,$code);
fclose($handle);
echo "created";
}
else
{
echo "already created";
}
?>