Checking time of submitting file in form - javascript

I want to have a HTML form to send a file to my server by user. I need to know the exact time he started sending this file - not the time that the file was received (I can check received time e.g. by checking file modification time at server). This code should do this - when clicking "Submit" the current server time should be written to logsForSendingForm.txt and when the file receives time should be written to logsForReceivedForm.txt.
Unfortunately, when sending the file, only the time when the file is received is written to logsForReceivedForm.txt - nothing is written to logsForReceivedForm.txt.
What is interesting, if I don't select any file and click Submit, current time is written to both files.
If you don't know how to debug this, but you can suggest any other solution (maybe without AJAX), it's also OK, I don't need to do it like in this code.
<?php
if (isset($_POST['tickStart']))
{
file_put_contents('logsForSendingForm.txt', time() . "\n", FILE_APPEND);
}
elseif (!empty($_FILES))
{
file_put_contents('logsForReceivedForm.txt', time() . "\n", FILE_APPEND);
$f = $_FILES['file'];
$patch = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']);
copy($f['tmp_name'], $patch.$f['name']);
}
?><!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.0.min.js'></script>
<script type='text/javascript'>
function sending()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: { tickStart: true }
});
return true;
}
</script>
</head>
<body>
<form action='index.php' method='post' enctype='multipart/form-data'>
<input type='file' name='file'><br>
<input type='submit' name='submit' value='Submit' onsubmit="return sending()">
</form>
</body>
</html>

There needs to be a bit more checking done on your part, but here is some briefly tested code. I used microtime() instead of time because for small files there is no difference in seconds on my localhost. I also threw in something from here to help inform the user that their file was too big, for example. You might want to catch according to mime-type and inform them of that too...
I threw out Jquery because it seemed superfluous.
You might still get a corrupted file if (and when) multiple clients attempt to write to your logs. (That is why I added the | LOCK_EX flag to your append. I have not done any load-testing, so no guarantees there.) Database???
Otherwise, you'll probably also want to do some filename normalization to get rid of illegal / non-ascii characters. But that's another question that has been treated elsewhere.
Cheers.
EDIT:
duration: 0.084668874740601 (for a 23mb file on localhost)
duration: 0.0021710395812988 (for a 74k file on localhost)
<?php
if (isset($_POST['tickStart']))
{
// this is the moment the script began
$mtime1=$_SERVER['REQUEST_TIME_FLOAT'];
$log = 'sent: ' . $mtime1;
}
if(isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post' && $_FILES['file']['size'] == 0){
$postMax = ini_get('post_max_size');
$fileMax = ini_get('upload_max_filesize');
$message = "Max filesize: $fileMax<br>Max postsize: $postMax";
$log = 'file too large';
}
elseif (!empty($_FILES) && !empty($_POST) && $_FILES['file']['size'] > 0)
{
$f = $_FILES['file'];
$patch = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']);
copy($f['tmp_name'], $patch.$f['name']);
// this is the time NOW
$mtime2=microtime(true);
file_put_contents('logsForSendingForm.txt', $mtime1 . "\n", FILE_APPEND | LOCK_EX);
file_put_contents('logsForReceivedForm.txt', $mtime2 . "\n", FILE_APPEND | LOCK_EX);
$duration = $mtime2 - $mtime1;
$log = $log . '\nduration: '.$duration;
$message = $f['name'].' uploaded.';
}
else
{
$log = 'no file selected';
$message = 'Please choose a file.';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type='text/javascript'>
console.log('<?php print $log ?>');
</script>
</head>
<body>
<form action='index.php' enctype='multipart/form-data' method='POST'>
<input type='file' name='file'><br>
<input type='hidden' value='true' name='tickStart'>
<input type='submit' name='submit' value='Submit'>
</form>
<h2>
<?php print $message; ?>
</h2>
</body>
</html>

Related

HTML Form Text to Speech speaks the file name and PHP, Doubles Form

I am working on a webpage that takes HTML form input, processes it on a loop using PHP, then displays the PHP echo output in a div using jQuery, then TTS speaks a message using ResponsiveVoiceJS.
The problem that is visible right now is that, upon loading of the page, the TTS starts speaking the webpage file name and some random PHP on a loop, then displays the form twice.
It shouldn't do any of that!
Since I am not sure which part of the code is causing the issue, here is the code in its entirety:
<html>
<head>
</head>
<body>
<form action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="post">
What is your URL? <input type="text" name="pastedurl"><br>
What is your minimum interval? <input type="text" name="interval"><br>
<input type ="submit">
</form>
<?php
set_time_limit(18000);
if (isset($_POST['submit']))
{
// echo "stopped here";
// die; //THIS DOESN'T WORK EITHER
$pastedlink = $_POST['pastedurl'];
$pastedlink2 = $_POST['pastedurl'];
$rate = $_POST['interval'];
parse_url($_POST['pastedurl'], PHP_URL_HOST);
if (parse_url($_POST['pastedurl'], PHP_URL_HOST) == 'www.instructables.com')
{
for ($z = 0; $z < 2880; $z++)
{
$tutorial_json = file_get_contents($pastedlink);
$tutorial_array = json_decode($tutorial_json, true);
$oldviews = $tutorial_array['views'];
sleep(30);
$tutorial_json2 = file_get_contents($pastedlink);
$tutorial_array2 = json_decode($tutorial_json2, true);
$currentviews = $tutorial_array2['views'];
$viewcount1 = (int) $oldviews;
$viewcount2 = (int) $currentviews;
$change = $viewcount2;
$change -= $viewcount1;
$rateasint = (int) $rate;
if ($change >= $rateasint)
{
$sayit = "Alert! Your Tutorial has gained " . $change . " more views";
echo $sayit;
}
}
}
else
{
exit("Error: URL submitted was not from www.instructables.com");
}
}
?>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(document).ready(function(readyEvent) {
speakInnerHTML();
});
function speakInnerHTML() {
var speek = document.getElementById("load_updates");
responsiveVoice.speak(speek.innerHTML);
}
</script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_updates').load('<?php
echo $_SERVER['PHP_SELF'];
?>',speakInnerHTML).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_updates"> </div>
</body>
</html>
Sorry about the poor formatting, I am a noob and don't know the methods of formatting these programming languages!
Here is a video of the error in action:
youtube
1.
die; //THIS DOESN'T WORK EITHER
die() is a function, and despite the wonders of echo, all functions are called with parentheses.
2.
isset($_POST['submit'])
This doesn't work because there are variables with the name submit.
To fix that, add the name attribute to your submit control, like this:
<input type="submit" name="submit">
3. You are loading the page itself with jQuery, even though it contains... well... itself. It's going to recursively fill the page with its own instances every 10000ms. And every one of that instance is going to do that too. You need to query the page with the data from the form, not just load it. And add a conditional so that if there is $_POST data, the page does not display all the HTML.

Send image from php server using ajax call

The short of what I'm trying to do is search for a file and display a picture from the server. The HTML has a simple search bar that allows you to type in a search term. The JavaScript uses an ajax request to call the PHP file, and the PHP finds the image on the server and sends it back to be displayed.
What happens right now is that the image isn't displayed, and I get an icon indicating some invalid image. The ajax call appears to be working, but I think the data I'm sending back isn't correct. I've been trying to search for it but everyone seems to have a different opinion on how to do it and it's kind of confusing.
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="search.js"></script>
<style type="text/css"></style>
</head>
</body>
<header>
<h1>My Page</h1>
</header>
<input type=text name="search" id="searchbox" placeholder="Search...">
<input type=button value="Search" id=search><br>
<div id="images"></div>
</body>
JavaScript
$(document).ready(function() {
$("#search").on('click', function(){
$.ajax({
url: '/search.php',
type: 'POST',
data: $("#searchbox").serialize(),
success: function(data) {
$('#images').append(data);
},
error: function() {
alert('failure');
}
});
});
});
PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}
else {
echo 'Error: image not found';
}
PS. For the moment, I'm ignoring any sort of error checking, I'm just trying to get it working and assuming the input is all valid
SUGGESTIONS:
Try this link:
Image Data URIs with PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm."jpeg";
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
echo '<img src="', $src, '">';
...
Debug the actual HTTP traffic between your jQuery/Browser and your PHP/back-end server. You can use a tool like Telerek Fiddler or Firebug, among many others.
'Hope that helps!
Use file_get_contents it will display the image on browser.
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode(file_get_contents($image)).'">';
Please change the url property in the object, used in your .ajax() method call. The path to your search.php is incorrect.
$.ajax({
url: '/search.php',
goes to:
$.ajax({
url: './search.php',

Proper Login screen using PHP and Javascript

I'm working on a login screen for a College project. Right now I have these two files.
index.php
<html>
<head>
<meta charset = 'UTF-8'>
<link rel="shortcut icon" href="images/favicon.ico"/>
<title>Sistema de Estágios - UFMS - Login</title>
<link href = "css/bootstrap.css" rel = "stylesheet" >
<link href = "css/index.css" rel = "stylesheet" >
<script src="js/jquery-1.11.1.min.js"></script>
<?php
session_start(); // start session
if(isset($_SESSION["sessioname"]))
{
if($_SESSION["session_time"] >= time()) //time hasn't expired
{
$_SESSION["session_time"] = time() + 60;
header("Location:users.php"); /* Redirect browser */
exit();
}
}
?>
<script type="text/javascript">
$(document).ready(function()
{
$("input").blur(function() // This makes the container's border turn red when it is empty
{
if($(this).val() == "")
{
$(this).css({"border" : "1px solid #F00"});
}
});
$("#botao").click(function()
{
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
{
$(this).css({"border" : "1px solid #F00"});
cont++;
}
});
if(cont == 0)
{
$("#form").submit();
}
});
});
</script>
</head>
<body>
<center>
<center>
<div class = "container">
<div class = "principal">
<form id="form" name="form" method="post" action="entra.php">
<p>
<label for="a">Nome de Usuário:</label>
<input id="a" type ="text" name="username" class="form-control"/><br/>
<label id="name_null" hidden="hidden">O campo deve ser preenchido</label>
</p>
<p>
<label for="b">Password:</label>
<input id="b" type="password" name="password" class="form-control"/><br/>
<label id="pass_null" hidden="hidden">O campo deve ser preenchido</label>
</p>
<buttom id="botao" name="Entrar" value="login" class="btn btn-primary" style="width: 100%;">Login</buttom>
</form>
<label> <button class="btn">Cadastre-se</button> </label>
</div>
</div>
</center>
</center>
</body>
entra.php
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<?php
require_once "config.php"; // include conection to database
$mysqli = new mysqli("localhost", "root", "", "sistema");
// verify if there is a person with the recived name
$Tipo = $_POST['tipo'];
$user_info = mysqli_query($mysqli,"SELECT * FROM users WHERE username='".addslashes($_POST['username'])."'");
if(mysqli_num_rows($user_info) != 0)
{
$result = mysqli_fetch_array($user_info); // put the informations in an array
if($result['password'] == sha1($_POST['password']))// if the password matches
{
session_start(); // começa a seesion
header("Cache-control: private");
$_SESSION["sessioname"] = $_POST['username'];
$_SESSION["auto"] = $result["Tipo"];
$_SESSION["id"]= $result["id"];
$_SESSION["session_time"] = time() + 60;// expiration timne
header("Location: users.php");
die();
}
else
{ // else show an alert
?>
<script type="text/javascript">
alert("Senha incorreta");
</script>
<?php
header("Location: index.php");
die();
}
}
header("Location: index.php");
?>
I'm looking for a way to make the login actions happen on index.php instead of entra.php.
I'm also looking for a better way to manage the session expire time. Something like a global variable so I don't have to change it on every single file whenever I want to change it for tests.
I'm pretty new with PHP so I would love to receive some help from you guys.
Just move your entra.php code to index.php file and change the form's Post action to index.php as
<form id="form" name="form" method="post" action="index.php">
SESSION: first, start the session using session_start() andstore the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request.
A good way to generally manage settings is to add a file like config.php and have all of them stored there. Since you already have it, you can store everything in it.
$_CONFIG["SESSION_EXPIRATION_TIME"] = 86400;
Then you can require_once it or include it in a lib class.
The good thing about the config file and not doing define("VAR", [val]) is that you can modify the variables if you need to have a custom config (say you have a test server and a production one and have different databases associated with them - you can easily override $_CONFIG. You can't do a lot about define).
Also, something a little harder (but useful) is to have a general file called index.php and include all other php files there (somewhat separating the logic from the view (html code)).
Also, do mysqli_real_escape_string to prevent SQL injections on the username.
As a general rule, it'd be a good idea to put the logic in a separate file and include it, instead of inlining it in the HTML.
If you want it to be one file, you can always check if the user's already logged and if your variables exist. Something along the lines of.
if(isset($_SESSION["sessioname"]) && $_POST['password'] !== NULL) {
//login code
}
Then change action='entra.php' to action='index.php' (alternatively, but not preferably, omit it altogether).
Of course, you can always add a hidden input field with some value if the above makes you squint :)
Oh, and always do an exit() after you do header('...'). php - Should I call exit() after calling Location: header?
I hope that helps!

Search database while I enter data in to a text area

I have a table data [Columns: id,question,answer each question have answer]; In frontend/UI i have a textarea while i paste a question to this field which search for exact question in db and show the result.
I want ajax no need to click any search button. I want this to work when I paste question in to the text area.
Code i am using
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS3</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>PHP5</h1>
<form class="form-inline">
<div class="form-group">
<input size="100" type="text" id="searchid" class="form-control" rows="10" cols="100" />
</div>
<div id="resultdiv"></div>
</form>
</div>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
</body>
</html>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#searchid').keydown(function (e){ // Event for enter keydown.
if(e.keyCode == 13){
var idvalue = $("#searchid").val(); // Input value.
$.ajax({ //Ajax call.
type: "GET",
url: "search.php",
data: 'id=' + idvalue ,
type: 'json',
success: function(msg){
// Show results in textareas.
msg = JSON.parse( msg ); // Line added
alert (msg);
$('#resultdiv').val(msg.answer);
}
}); // Ajax Call
} //If statement
}); //document.ready
</script>
My Search.php
<?php
if ($_GET['id']):
$dataid = json_decode($_GET['id']);
// Connect to database.
$con = mysqli_connect("localhost","root","");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
$sql = "SELECT answer FROM exam_css3 where question LIKE '$dataid' ";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
?>
This code is not working, can anyone help on this?
There are, among other things, some issues in your PHP.
First of all you search for $dataid, which means an exact match. You need to do
"SELECT answer FROM exam_css3 where question LIKE '%{$dataid}' ";
Then you always save only one answer, and you do not specify quote marks around 'answer', which might cause a PHP warning, which would corrupt the JSON output:
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
So you might want to rewrite that as
<?php
if (array_key_exists('id', $_GET)) {
$dataid = json_decode($_GET['id']);
// Here it would be good to check whether the decoding succeeded.
// I'd also try doing in HTML: data: { id: idvalue }
// Connect to database.
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
// Only interested in one match.
$sql = "SELECT answer FROM exam_css3 where question LIKE '%{$dataid}%' LIMIT 1";
$result = mysqli_query($con,$sql);
$answer = mysqli_fetch_assoc($result);
if (null === $answer) {
$answer = array('answer' => 'nothing found', 'status' => 'error');
}
// Since we're putting this into HTML...
$answer['answer'] = HTMLspecialChars($answer['answer']);
} else {
$answer = array('answer' => 'no query was supplied', 'status' => 'error');
}
Header ('Content-Type: application/json');
die(json_encode($answer));
In the code above I have added a 'status' variable so that in the jQuery you can do
if (msg.error) {
alert("Error: " + msg.answer);
return;
}
and further differentiate between correct and incorrect answers.
Other issues exist (for example you ought to use PDO and switch to prepared queries; as things stand, if the question contains a quote sign such as
What's a SQL injection?
your SQL search would throw an error. This is not limited to SQL injection. NO QUERY CONTAINING QUOTE MARKS WILL WORK. You need at least to escape the string dataid before placing it in the query.
You are defining twice the type in your ajax. json is the dataType not simple the type. type is get, what you do not need to set, that is the default.
The second problem is, you pass your data as a string, not as a json object, so on your server side, that will be an array, what you can not json_decode.

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

Categories