Prevent submitting if input field is empty - javascript

I developing a comment system for my social media, but comments are inserted into database even if it's empty.So i want nothing to happen if comment field is empty,i don't want to echo any message or submitting the comment.
This is my code
<?php
// Get id of post
if(isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
}
$user_query = mysqli_query($con, "SELECT added_by, user_to FROM posts
WHERE id='post_id'");
$row = mysqli_fetch_array($user_query);
$posted_to = $row['added_by'];
$user_to = $row['user_to'];
if(isset($_POST['postComment' . $post_id])) {
$post_body = $_POST['post_body'];
$post_body = mysqli_escape_string($con, $post_body);
$date_time_now = date("Y-m-d H:i:s");
$insert_post = mysqli_query($con, "INSERT INTO comments VALUES ('',
'$post_body', '$userLoggedIn', '$posted_to', '$date_time_now', 'no',
'$post_id')");
if($posted_to != $userLoggedIn) {
$notification = new Notification($con, $userLoggedIn);
$notification->insertNotification($post_id, $posted_to, "comment");
}
if($user_to != 'none' && $user_to != $userLoggedIn) {
$notification = new Notification($con, $userLoggedIn);
$notification->insertNotification($post_id, $user_to,
"profile_comment");
}
$get_commenters = mysqli_query($con, "SELECT * FROM comments WHERE
post_id='$post_id'");
$notified_users = array();
while($row = mysqli_fetch_array($get_commenters)) {
if($row['posted_by'] != $posted_to && $row['posted_by'] != $user_to
&& $row['posted_by'] != $userLoggedIn &&
!in_array($row['posted_by'], $notified_users)) {
$notification = new Notification($con, $userLoggedIn);
$notification->insertNotification($post_id, $row['posted_by'],
"comment_non_owner");
array_push($notified_users, $row['posted_by']);
}
}
echo "<p>Comment Posted! </p>";
}
?>
<form action="comment_frame.php?post_id=<?php echo $post_id; ?>"
id="comment_form" name="postComment<?php echo $post_id; ?>"
method="POST">
<textarea name="post_body" placeholder="Add a comment"></textarea>
<input type="submit" name="postComment<?php echo $post_id; ?>"
value="Comment">
</form>
<!-- Load Comments -->
<?php
$get_comments = mysqli_query($con, "SELECT * FROM comments WHERE
post_id='$post_id' ORDER BY id ASC");
$count = mysqli_num_rows($get_comments);
if ($count != 0) {
while($comment = mysqli_fetch_array($get_comments)) {
$comment_body = $comment['post_body'];
$posted_to = $comment['posted_to'];
$posted_by = $comment['posted_by'];
$date_added = $comment['date_added'];
$removed = $comment['removed'];
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_added); // Time of Post
$end_date = new DateTime($date_time_now); // Current time
$interval = $start_date->diff($end_date); // Difference between
dates
if($interval->y >= 1) {
if($interval == 1)
$time_message = $interval->y . " year ago"; // 1 year ago
else
$time_message = $interval->y . " years ago"; // 1+ year ago
}
else if ($interval-> m >= 1) {
if($interval->d == 0) {
$days = " ago";
}
else if($interval->d == 1) {
$days = $interval->d . " days ago";
}
else {
$days = $interval->d . " days ago";
}
if($interval->m == 1) {
$time_message = $interval->m . " month". $days;
}
else {
$time_message = $interval->m . " months". $days;
}
}
else if($interval->d >=1) {
if($interval->d == 1) {
$time_message = "Yesterday";
}
else {
$time_message = $interval->d . " days ago";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . " hour ago";
}
else {
$time_message = $interval->h . " hours ago";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . " minute ago";
}
else {
$time_message = $interval->i . " minutes ago";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . " seconds ago";
}
}
$user_obj = new User($con, $posted_by);
?>
<div class="comment_section">
<a href="<?php echo $posted_by?>" target="_parent"><img src="<?php
echo $user_obj->getProfilePic(); ?>" title="<?php echo $posted_by;
?>" style="float:left;" height="30"></a>
<a href="<?php echo $posted_by?>" target="_parent"> <b><?php echo
$user_obj->getFirstAndLastName(); ?> </b> </a>
<?php echo $time_message . "<br>" .
$comment_body; ?>
<hr>
</div>
<?php
}
}
else {
echo "<center><br><br>No comments to show</center>";
}
?>
</body>
</html>

Add this attribute to the correct input field: <input required: required;> that should fix it for you :-)
see http://w3c.github.io/html/sec-forms.html#the-required-attribute for more information

Included a demo below. The first form will display an error message when it is submitted - attribute required - (which you probably don't want) and the second form doesn't give any feedback - attribute required but novalidate for the form.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<textarea required onsubmit="return false;"></textarea><br>
<input type="submit" value="submit">
</form><br><br>
<form novalidate onsubmit="return false;">
<textarea required></textarea><br>
<input type="submit" value="submit">
</form>

Related

What should I put in my updating.php when I need to update users status if online or offline every 5 seconds?

Hi I've made a messaging feature,it displays the receivers of the message in an account, beside the receiver's name is a green or red dot, for online or offline, it is successful when I log in 2 accounts and messaged each other, when I open the first account, the other account is offline, when I open the second account, the other is online, what my problem is I want to update their status in every five seconds so that their dot will be accurate whenever they log out or log in. I have made a javascript and ajax below this page left-col.php and I've tried copying the whole code, putting it to updating.php but it did not work, what should be the appropriate data inorder to update user receiver status in every 5 seconds inside the updating.php? and also, does my the javascript and ajax needs a library to be included that's why it didn't work? Please help.
<?php
require('connection.php');
$user_name=$_SESSION['username'];
$user_id=$_SESSION['user_id'];
if(!isset($_SESSION['user_id'])){
header("LOCATION: index.php");
}else{
$advance_time=time()+15;
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q='SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="'.$_SESSION['username'].'" OR
`receiver_name`="'.$_SESSION['username'].'"
ORDER BY `date_time` DESC';
$e='SELECT * from messages';
$r=mysqli_query($con,$q);
if($r){
if(mysqli_num_rows($r)>0){
$counter=0;
$added_user=array();
while($row=mysqli_fetch_assoc($r)){
$sender_name=$row['sender_name'];
$receiver_name=$row['receiver_name'];
$timestamp=$row['date_time'];
if($_SESSION['username']==$sender_name){
//add the receiver_name but only once
//so to do that check the user in array
if(in_array($receiver_name,$added_user)){
//dont add receiver_name because
//he is already added
}else{
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo ''.$receiver_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user=array($counter=>$receiver_name);
//increment the counter
$counter++;
}
}elseif($_SESSION['username']==$receiver_name){
//add the sender_name but only once
//so to do that check the user in array
if(in_array($sender_name,$added_user)){
//dont add sender_name because
//he is already added
}else{
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo ''.$sender_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user=array($counter=>$sender_name);
//increment the counter
$counter++;
}
}
}
}
else{
//no message sent
echo 'no user';
}
}else{
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#content').html(response);
}
});
}
</script>
You need to handle the $_SESSION in all pages
Updating.php code:
<?php
require('connection.php');
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if(isset($_REQUEST['from_user'])){
$advance_time=time()+15;
$user_id = $_REQUEST['from_user'];
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
$html_left_div = '';
$html_left_div .='<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById(\'new-message\').style.display=\'block\'" class="white-back">
<p align="center">New Message </p>
</div>';
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
// echo $q;
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
$html_left_div .='<div class="grey-back first">
<img src="s.jpg" class="image"/>
' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$receiver_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
$html_left_div .='<div class="grey-back second">
<img src="s.jpg" class="image"/>
' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$sender_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
$html_left_div .='</div>';
echo $html_left_div;
Left-col.php code:
<?php
require 'connection.php';
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if (!isset($_SESSION['user_id'])) {
header("LOCATION: index.php");
} else {
$advance_time = time() + 15;
$query = mysqli_query($con, "SELECT * FROM status WHERE user_id='$user_id'");
if (mysqli_num_rows($query) > 0) {
mysqli_query($con, "UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
} else {
mysqli_query($con, "INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo '' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo '' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#left-col-container').html(response);
}
});
}
</script>

innerHtml on responding ajax method

I am using ajax for sending data to PHP script and set a query in my database. my codes :
HTML script :
<span id="btn_span_<?php echo $user_id ?>">
<?php if ($online == 1) { ?>
<button onclick="update_online(1,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-delete btn btn-status">is active</button>
<?php } elseif ($online == 0) { ?>
<button onclick="update_online(0,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-services btn btn-status">active
</button>
<?php } ?>
</span>
JAVASCRIPT script :
function update_online(status, id, span_id) {
var settings = {
"async": true,
"crossDomain": true,
"url": "script_edit_status.php?status=" + status + '&id=' + id + '&span_id=' + span_id,
"method": "GET"
};
$.ajax(settings).done(function (response) {
var obj = JSON.parse(response);
var btn = document.getElementById(span_id);
if (obj.status == "1") {
btn.innerHTML = "<button onclick='update_online(1,obj.id,obj.span_id)' class='btn-custom-services btn btn-status'>active</button>";
} else if (obj.status == "0") {
btn.innerHTML = "<button onclick='update_online(0,obj.id,obj.span_id)' class='btn-custom-delete btn btn-status'>is active</button>";
}
});
}
PHP script :
<?php
include_once "../db/connection.php";
$id = $_GET['id'];
$status = $_GET['status'];
$span_id = $_GET['span_id'];
try {
if ($status == 1) {
$sql_edit_status = "update api_user set online=0 where id='$id';";
} elseif ($status == 0) {
$sql_edit_status = "update api_user set online=1 where id='$id';";
}
$conn->query($sql_edit_status);
$status_arr = array(
"id" => $id,
"status" => $status,
"span_id" => $span_id
);
echo json_encode($status_arr);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
it is ok for the first action but when I want to click to button for second time consol shows following error :
Uncaught ReferenceError: obj is not defined
The error is for innerHTML that don't send correctly methods...
Can you help me?
btn.innerHTML = "<button onclick='update_online(0," + obj.id + "," + obj.span_id + ")' class='btn-custom-delete btn btn-status'>is active</button>";

More than one timer on a page at a time

Okay I am wondering how I get two countdown timers on the one page?
<script type = 'text/javascript'>
window.onload=function() {
setInterval("<?php
$array = count($settime);
for ($i = 0; $i < $array; $i++) {
$thitime = explode(":", $settime[$i]);
echo "timeleft(" . $thitime[1] . ", " . $thitime[0] . "); ";
}
?>", 1000);
}
function timeleft(string, id)
{
var xmlhttp=GetXmlHttpObject();
if(xmlhttp==null) { alert("Sorry, Your browser doesnt support HTTP Requests");
return;
}
var elem = "time" + id;
var load = "time_left.php?string=" + string;
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
document.getElementById(elem).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", load, true);
xmlhttp.send(null);
}
function GetXmlHttpObject() {
var xmlhttp=null;
try {
xmlhttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
</script>
The page I am trying to run the two timers off is only loading one of the timers, I have tried multiple things to try and fix the issue, and can't seem to figure out what it is that is wrong with it..
I even tried making two different timer scripts and that didn't work..
Here is the complete code of the page I want to run the two timers on..
<?php
/*------------includes--------------*/
include('./includes/connections.php');
include('./includes/brain_file.php');
include('./includes/style_top.php');
/*------------includes--------------*/
if ($pl['my_tuts_on'] == 'yes') {
echo "<tr bgcolor=#E6E6E6><td>
Here you can view all the inmates currently in jail. You may attempt to bust/bail them, Bailing them costs a fee, Busting them uses 10 energy and is not a garantee you will bust them, Just be carefull not to get caught and end up in jail yourself.
</td></td></tr></table></center><hr/ width=95%>";
}
echo "<center><main>Jail</main><hr width='95%'/>";
if ($pl['my_hosp'] > gmtime()) {
echo "Sorry this page is not viewable while in hospital!<hr width='85%'/>";
include('./includes/style_bottom.php');
exit();
}
$_GET['page'] = abs(intval($_GET['page']));
$min = ($_GET['page'] > '1') ? (($_GET['page'] - 1) * 25) : $min = 0;
$q_ry = array();
$q_ry = "SELECT `playerid` FROM `members`
WHERE `my_jail` > '" . mysql_real_escape_string(gmtime()) . "'";
$tot = array();
$tot = mysql_query($q_ry);
if ($joh['my_jail'] > gmtime()) {
$settime[] = $pl['playerid'] . ":" . $pl['my_jail'];
echo "<br><font size=2><b>", stripslashes($pl['jail_reason']), "</b>
<br>You will be in jail for another <span id = 'time" . $pl['playerid'] . "'><b>" . gettimeleft($pl['my_jail']) . "</b></span> yet!</font><br><br><hr width='85%'>";
}
?>
<script type = 'text/javascript'>
window.onload=function() {
setInterval("<?php
$array = count($settime);
for ($i = 0; $i < $array; $i++) {
$thitime = explode(":", $settime[$i]);
echo "timeleft(" . $thitime[1] . ", " . $thitime[0] . "); ";
}
?>", 1000);
}
function timeleft(string, id)
{
var xmlhttp=GetXmlHttpObject();
if(xmlhttp==null) { alert("Sorry, Your browser doesnt support HTTP Requests");
return;
}
var elem = "time" + id;
var load = "time_left.php?string=" + string;
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
document.getElementById(elem).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", load, true);
xmlhttp.send(null);
}
function GetXmlHttpObject() {
var xmlhttp=null;
try {
xmlhttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
</script>
<?php
if ($pl['my_jail'] > gmtime()) {
echo "<b>><a href='bust.php'>Try and escape for " . abs(intval($pl['my_maxnerve'] / 2)) . " nerve</a></b>
<hr width='85%'>";
}
echo "<b></b> ";
if (mysql_num_rows($tot) <= '25') {
echo "";
} else {
if ($_GET['page'] > '1') {
echo "<a href='jail.php?page=" . ($_GET['page'] - 1) . "'><<</a> ";
}
for ($i = 0; $i < (mysql_num_rows($tot) / 25); $i++) {
echo "<a href='jail.php?page=" . ($i + 1) . "'>";
if (($i + 1) == $_GET['page']) {
echo "<b>" . ($i + 1) . "</b>";
} else {
echo "<font color = '#999999'>" . ($i + 1) . "</font>";
}
echo "</a> ";
}
if ($_GET['page'] < $i) {
echo " <a href='jail.php?page=" . ($_GET['page'] + 1) . "'>>></a>";
exit();
}
}
echo "<table class='sidebarLink' border='0' width=95% class='rounded'><tr bgcolor=#151515>
<td height='20'><font color = '#FFFFFF'><b>ID#</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Player</b></font></td>
<td width=25%><font color = '#FFFFFF'><b>Time</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Level</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Reason</b></font></td>
<td height='20'><font color = '#FFFFFF'><b>Release</b></font></td></tr>";
$num = 0;
$q_ry = array();
$q_ry = "SELECT `playerid`,`playername`,`my_level`,`jail_offer`,`my_jail`,`jail_reason`
FROM `members`
WHERE `my_jail` > '" . mysql_real_escape_string(gmtime()) . "'
ORDER BY `my_jail` DESC
LIMIT $min,25";
$hopl = array();
$hopl = mysql_query($q_ry);
if (mysql_num_rows($hopl)) {
$hp = array();
while ($hp = mysql_fetch_array($hopl)) {
$num++;
if ($num % 2) {
$color = "#E6E6E6";
} else {
$color = "#E6E6E6";
}
$q_ry = array();
$q_ry = "SELECT `my_bustreward`
FROM `members_extra`
WHERE `playerid` = '" . $hp['playerid'] . "'";
$du = array();
$du = mysql_fetch_array(mysql_query($q_ry));
$settime[] = $hp['playerid'] . ":" . $hp['my_jail'];
echo "<tr bgcolor=#E6E6E6>
<td><a href = 'messages.php?action=send&XID=" . $hp['playerid'] . "'>" . $hp['playerid'] . "</a></td>
<td><a href = 'profile.php?XID=" . $hp['playerid'] . "'>" . htmlentities($hp['playername']) . "</a></td>
<td><span id = 'time" . $hp['playerid'] . "'><b>" . gettimeleft($hp['my_jail']) . "</b></span></td>
<td>" . $hp['my_level'] . "</td>
<td>" . stripslashes($hp['jail_reason']) . "</td>
<td>[<a href='release.php?action=bail&XID=" . $hp['playerid'] . "'>Bail</a>]
[<a href='release.php?action=bust&XID=" . $hp['playerid'] . "'>Bust</a>]</td></tr>";
}
} else {
echo "<tr>
<td colspan = '7' align = 'center'>
You walk into the jail to tease some inmates, but there are no inmates to tease!
</td></tr>";
}
echo "</table>
<hr width = '95%'>";
if ($pl['my_jail'] > gmtime() || $pl['am_i_staff'] > 4) {
if ($pl['am_i_staff'] > 4) {
echo '<table width="95%" align="center" border="0" bgcolor="#E6E6E6">
<b>Clear the current shoutbox.</b>
<form method="post" action="#"><tr>
<td><input type="hidden" name="clear"></td>
</tr><tr>
<td colspan="2" valign="middle" align="center"><input class="hospchat" type="submit" value="Clear ALL Shouts"></td>
<td></td>
</tr></form></table><br />';
}
if (isset($_POST['clear'])) {
if ($pl['am_i_staff'] < 5) {
print "Sorry, staff only. <a href=jail.php>> back</a>.";
exit();
} else {
mysql_query("TRUNCATE table `jailshoutsbox`");
print "All of the jail shouts have been <b>cleared</b> <a href=jail.php>> back</a>.";
}
}
if (isset($_POST['shout'])) {
if ($pl['lastShoutj'] == date("i") && $pl['am_i_staff'] < 5 && $pl['my_dondays'] < 1) {
echo "<div style='background: #DFDFDF;' width='85%'>Sorry, non donators can only post once per minute. <br /> <a href=jail.php> > back</a></div><br />";
exit();
}
if ($pl['my_jail'] <= 0 && $pl['am_i_staff'] < 5) {
echo "You are not in the jail. <a href=jail.php>> Back</a>";
exit();
}
echo "<div style='background: #E6E6E6;' width='85%'>You've shouted<br /><a href=jail.php>Refresh</a></div><br />";
$_POST['shout'] = htmlspecialchars(($_POST['shout']));
$not = array(
"'",
"/",
"<",
">",
";"
);
$_POST['shout'] = str_replace($not, "", $_POST['shout']);
mysql_query("INSERT INTO `jailshoutsbox` VALUES ('NULL', {$_SESSION['playerid']}, '{$_POST['shout']}', " . date("d") . ")");
}
echo ' <hr width=95% /> Post a message on the shoutbox.
<table width="95%" align="center" border="0" bgcolor="#E6E6E6">
<form method="post" action="#"><tr>
<td>Your Message: (max 155) </td>
<td><input class="hospchat" type="text" name="shout" maxlength="155"></td>
</tr><tr>
<td colspan="2" valign="middle" align="center"><input class="hospchat" type="submit" value="Shout"></td>
<td></td>
</tr></form></table><br /><table width="95%" style=text-align:left class="table2" border="0" cellspacing="2">
<tr bgcolor="#151515" style="font-style:bold; text-align:center;"><td style="font-style:bold;" width=55%><b><font color="#FFFFFF">Posted By:</b></td><td style="font-style:bold;" width="44%"><b><font color="#FFFFFF">Messsage:</b></td></tr>
';
$get = mysql_query("SELECT * FROM `jailshoutsbox` ORDER BY `ID` DESC LIMIT 10");
while ($r = mysql_fetch_array($get)) {
$num9 = $num9 + 1;
$odd9 = "#CCCCCC";
$even9 = "#e3e3e3";
if ($num9 % 2) {
$color9 = "$even9";
} else {
$color9 = "$odd9";
}
if ($r['User'] == 1) {
$r['Shout'] = "<font color='blue'>" . $r['Shout'] . "</font>";
}
$user = mysql_query("SELECT `playername` FROM `members` WHERE `playerid`={$r['User']}");
while ($user1 = mysql_fetch_array($user))
$player = ($r['User'] == 0) ? "SYSTEM" : "<a href='profile.php?XID={$r['User']}'>[{$r['User']}] {$user1['playername']}</a>";
echo "<tr height='50px' bgcolor=#E6E6E6><td>$player</td><td style='text-align:center;'>{$r['Shout']}</td></tr>";
}
echo "</table>";
}
include('./includes/style_bottom.php');
?>
And here is the gettimeleft function.
function gettimeleft($tl) {
if($tl <= time()) { $release = "0 Seconds"; }
else
{
$mins = floor(($tl - time()) / 60);
$hours = floor($mins / 60);
$mins -= $hours * 60;
$days = floor($hours / 24);
$hours -= $days * 24;
$months = floor($days / 31);
$days -= $months * 31;
$weeks = floor($days / 7);
$days -= $weeks * 7;
$timeleft = ($tl - time());
$secs = round($timeleft%60);
if ($months > 0)//MONTHS
{
$release .= " $months Month" . ($months > 1 ? "s" : "");
}
if ($weeks > 0)//WEEKS
{
if ($months > 0)
{
$release .= ",";
}
$release .= " $weeks Week" . ($weeks > 1 ? "s" : "");
}
if ($days > 0)//DAYS
{
if ($months > 0 ||$weeks > 0)
{
$release .= ",";
}
$release .= " $days Day" . ($days > 1 ? "s" : "");
}
if ($hours > 0)//HOURS
{
if ($months > 0 ||$weeks > 0 || $days > 0)
{
$release .= ",";
}
$release .= " $hours Hour" . ($hours > 1 ? "s" : "");
}
if ($mins > 0)//MINUTES
{
if ($months > 0 ||$weeks > 0 || $days > 0 || $hours > 0)
{
$release .= ",";
}
$release .= " $mins Minute" . ($mins > 1 ? "s" : "");
}
if($secs > 0)//SECONDS
{
if($release != "")
{
$release .= " and";
}
$release .= " $secs Second" . ($secs > 1 ? "s" : "");
}
}
return $release;
}
Is anyone please able to help me out with this?

Display a php cookie in html

I have set a cookie using php.
Here's my code:
<?php
include_once 'php/config.php';
session_start(); //starting the session for user profile page
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM users where username = '$username' AND password = '$password'") or die(mysql_error());
$row = mysql_num_rows($query) or die(mysql_error());
if($row==1)
{
$_SESSION['username'] = $username;
setcookie('username', $username, time() + (86400 * 30), "/"); // 86400 = 1 day
echo $_SESSION['username'];
echo "SUCCESSFULLY LOGGEDIN...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
}
?>
I want display the 'username' cookie in html like Hi ""
.
Please Help.
Tried this javascript:
<script type="text/javascript">
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
Use echo $_COOKIE['username']; instead of echo $_SESSION['username'];. It will echo out of the second reload of the page. (Why?)
<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
</script>

php | Defend move_upload_file or delete files from input[type="file"] using jQuery

I have an input[type="file"] had multiple option. I made it preview function so that user can delete the image by clicking the button before submit. The images are deleted well on browser by remove() function however the problem is the values of input including the deleted images are posted when i submit. I don't know how to delete real value of input.
I've tried to figure it out to delete in the server side.
This is the part of html code.
<div class="col-xs-4 vcenter from-group">
<span class="glyphicon glyphicon-asterisk" style="color:red;"></span><label for="inputScreenshots">스크린샷</label>
<p style="display:inline; padding-left:270px; color:red; font-size: 12px">* 이미지 사이즈 : 800 X 450</p>
<input type="file" id="inputScreenshots" name="inputScreenshots[]" class="form-control" accept="image/*" multiple>
<div id="filenameList" style="width : 400px">
<div id="insertScreenshots" style="margin : 30px; position :relative;">
<input type="hidden" name="screenshots_filename[]" value="<?=$screenshot_urls?>">
</div>
</div>
This is the php code where im trying to defend uploading images.
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
// del_screenshots are images that deleted from client.
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
// ss_count is the size of all images including deleted images from input field.
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
// tmp_filename is the posted real file name.
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
//=========================================================================
for ($j = 0; $j < sizeof($ds_count); $j++) {
// Compare all images name and deleted images name
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
// The $tmp_filename has to be deleted. not to be uploaded to server.
// $tmp_filename = null;
}else {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."false";
// This files are okay to be uploaded to server.
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
$newFilePath = uniqid().".".$ext;
if ($screenshots != "") {
$screenshots .= "+";
}
$screenshots .= $newFilePath;
// $screenshots has be uploaded to DB except the deleted images. (ex : uniqFileName.png + uniqFileName.png + .. )
echo "<br/> 1) screenshots : ". $screenshots;
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
$ss_upload="true";
}
I want to defend uploading the deleted images but it is no matter to use unlink() in somewhere. The point is how cant i make the string except the deleted images.
=========================================================================
I suppose there is another way to do in jQuery but i have no idea.
I'll put the code below.
$("#inputScreenshots").change(function(){
$("#filenameList div.notyet").remove();
for(var i = 0, len = this.files.length; i < len; i++){
var file = this.files[i];
var fr = new FileReader();
fr.onload = screenshots_processFile(file);
fr.readAsDataURL(file);
}
});
var screenshots_processFile = function screenshots_processFile(file) {
return (function(file) {
return function(e) {
var div = document.createElement("div");
$(div).addClass("notyet").css({
margin: "30px",
position: "relative"
});
var html = [,'<img src="" width="100%" id="tmp_screenshots">'
,'<button type="button" class="close img-close" aria-label="Close"><span aria-hidden="true">×</span></button>'
].join("");
$(div).append(html);
$(div).find("button").click(function() {
alert("remove");
//=========================================================== * TODO : remove the files in server!
var targetDom = document.getElementById( "filenameList" );
var targetInput = document.createElement("input");
targetInput.setAttribute("name", "del_screenshots[]" );
targetInput.setAttribute("type","hidden");
targetDom.appendChild(targetInput);
alert(file.name);
targetInput.setAttribute("value", file.name);
//===========================================================
$(this).parent().remove();
});
$(div).find("img").attr("src", e.target.result);
$("#filenameList").append(div);
}
})(file)
};
How can i do this? Does anyone have an idea?
-----------------------------------------------------------------------------------------------------------
I solved it like this. I know my code is so dirty :-/
$ss_upload="false";
if (isset($_POST["del_screenshots"])){
$ds_count = $_POST["del_screenshots"];
foreach($ds_count as $del) {
echo "<br/> del_screenshots : ".$del;
}
//echo "<br/> << TEST >>"."<br/>ds_count[0] : " . $ds_count[0] . "<br/>ds_count[1] : " . $ds_count[1] ;
}
$ss_count = sizeof($_FILES['inputScreenshots']['tmp_name']);
echo "<br/>ss_cout : ". $ss_count;
for ($i = 0; $i < $ss_count; $i++) {
$tmpFilePath = $_FILES['inputScreenshots']['tmp_name'][$i];
$tmp_filename = $_FILES['inputScreenshots']['name'][$i];
echo "<br/> tmp_filename".$i. " : " .$tmp_filename;
$ss_del_mode="false";
//=========================================================================
if (isset($_POST["del_screenshots"])) {
for ($j = 0; $j < sizeof($ds_count); $j++) {
if (strcmp($ds_count[$j] , $tmp_filename) == 0) {
echo "<br/>".$ds_count[$j] . " == " . $tmp_filename . "==> " ."true";
$ss_del_mode = "true";
}
}
}
//=========================================================================
$ext = pathinfo($tmp_filename, PATHINFO_EXTENSION);
// $ext = pathinfo($_FILES['inputScreenshots']['name'][$i], PATHINFO_EXTENSION);
echo "<br/>". $i . " ext (pathinfo) : ". $ext;
if ($ext == "") {
continue;
$ss_upload="false";
}
if ($ss_del_mode == "true") {
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
$newFilePath = "";
} else {
$newFilePath = uniqid().".".$ext;
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]";
}
if ($screenshots != "") {
if ($ss_del_mode != "true"){
echo "<br/> ss_del_mode [[[[ " . $ss_del_mode. " ]]]]". " --> screenshots";
$screenshots .= "+";
}
}
$screenshots .= $newFilePath;
echo "<br/> 1) screenshots (newFilePath) : ". $screenshots;
if ($newFilePath != "") {
move_uploaded_file($tmpFilePath, $SS_PATH."/".$newFilePath);
}
$ss_upload="true";
}

Categories