PHP chat censorship - php

I have a chat on my website, but it doesn't have accounts, so cursing is rampant. I use PHP to write all of my data to user.txt. Is there a simple filter for mindless cursing in php? Because this js I use doesn't seem to work too well:
$(function() {
$("input:submit[name='submit']").on("click",function() {
var name = $("input:text[name='name']").val();
var message = $("input:text[name='field2']").val();
var badwords = ["dingbat", "poopy"];
/* do this */
if($.inArray(name, badwords) !==-1 || $.inArray(message, badwords) !==-1) {
alert("Your Message Contains Bad Words, Please Remove Them Before Proceeding");
return false;
}
});
});
Here is my full code (minus txt.php which just displays user.txt)
#import url(https://fonts.googleapis.com/css?family=Lato:400,100,300);
#blu {
background: #F0FAFF;
padding: 3;
width: 310;
}
b, i, p {
-webkit-transition: all 0.5s ease;
font-size: 16px;
font-size: 1rem;
line-height: 23px;
line-height: 1.4375rem;
font-weight: 400;
font-style: normal;
font-family:"Lato";
}
iframe{border: 3px solid white;}
button,input, #rcp_submit, #rcp_update_card {
display: inline-block;
font-family: "Lato", sans-serif;
font-weight: 500;
outline: 0;
border-radius: 0;
color: black;
background: #FFFFFF;
white-space: nowrap;
padding: 9px 16px !important;
line-height: 1.4;
border: 0;
color:black;
position: relative;
-webkit-transition: 0.1s;
transition: 0.1s;
}
,!--this file is called c5.php-->
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file<a href ='javascript:history.go(-1)'>go back</a>";
}
}
else {
die('no post data to process');
}
?>
<html>
<body onload="reloadIFrame();">
<script>
window.setInterval("reloadIFrame();", 3000);
function reloadIFrame() {
document.getElementById("myIframe").src="txt.php";
}
</script>
<div id ="blu">
<table>
<p>Chat about your code</p>
<td>
<iframe src ="txt.php" id ="myIframe"></iframe><br/>
<button onclick="reloadIFrame();">Refresh feed</button>
<form action="c5.php" method="POST">
<p>Name:</p>
<input name="field1" type="text" />
<h3> </h3>
<p>Question:<p>
<input name="field2" type="text" />
<input type="submit" name="submit" value="Submit">
</form>
download chat logs
</td>
</table>
</div>

let's take a look at why your js was not working
You are matching a whole sentence for a word .
here is an example if the var name is BADWORD SOMEONE_BADWORD
what you are searching if the array holds that value (BADWORD SOMEONE_BADWORD)
so what you should do is split the sentence into it's basic component words
name.split(/[(\s|_)]/) // split the name by white space or underscore
now you will have an array of
["BADWORD", "SOMEONE", "BADWORD"]
and the code becomes:
$(function() {
function containBadWord(words , banlist){
var bad = false;
$.each(words , function(k , v){
if($.inArray(v, banlist) !==-1){
bad = true;
return false;
}
});
return bad;
}
$("input:submit[name='submit']").on("click",function() {
var name = $("input:text[name='']").val();
var name_split = name.split(/[(\s|_)]/);
var message = $("input:text[name='field2']").val();
var message_split = message .split(/[(\s|_)]/);
var badwords = ["dingbat", "poopy"];
/* do this */
if(containBadWord(name_split , badwords )){
alert("your name has bad words")
}
if(containBadWord(message_split , badwords )){
alert("your messagehas bad words")
}
});
});
edit :
the code above was not working because your jquery selectors are all wrong as well .
`input:text[name='']` will select an input with an empty attribute of `name`
here is working code
https://jsfiddle.net/tq7odeLg/

I tried this, and it worked:
<?php
$find=array('bad','word','words');
$replace=array('...','...','...');
if(isset($_POST['user_input'])&&!empty($_POST['user_input']))
$data = $_POST['name'] . '-' . $_POST['user_input'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
}
{
$user_input=$_POST['user_input'];
$user_input_new=str_ireplace($find,$replace,$user_input);
}
?>
<p> <?php
$text = file_get_contents('user.txt');
echo $text;
?>
</p>
<style>
#import url(https://fonts.googleapis.com/css?family=Lato:400,100,300);
b, i, p {
-webkit-transition: all 0.5s ease;
font-size: 16px;
font-size: 1rem;
line-height: 23px;
line-height: 1.4375rem;
font-weight: 400;
font-style: normal;
font-family:"lato";
}
</style>
<hr>
<form action="ws.php" method="POST">
<p>name:</p><input name ="name" type ="text"></input><br/>
<p>comment:</p><br/><textarea name="user_input" rows="6" col="30">
</textarea><br/>
<input type="Submit" value="Submit">
</form>
</form>

Related

Updating SQL 'WHERE' based on JSON AJAX checkbox selection

I have an AJAX HTML page and a submit PHP page, which sends data from SQL to update HTML on page.
I have a list of films within a PHPMyAdmin MariaDB table. One of the columns is "channel". Channel will either say "NOWTV", "BBC", or "SKYTV". I want the user to be able to select the channel and for this to update.
If I check the array for 1 string - for example: skytv, the SQL pulls the data. However, if I want to change the WHERE clause, based on selection - the filtering does not work.
I've tried ".=where OR" to change the channel selection.
ajax.html
<html>
<style>
body {
padding: 10px;
}
h2 {
margin: 1em 0 0.3em 0;
color: #343434;
font-weight: normal;
font-size: 30px;
line-height: 40px;
font-fnuamily: 'Orienta', sans-serif;
}
#employees {
font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
font-size: 12px;
background: #fff;
margin: 10px 10px 0 0;
border-collapse: collapse;
text-align: center;
float: left;
width: 100%;
}
#employees th {
font-size: 14px;
font-weight: normal;
color: #039;
padding: 4px 4px;
border-bottom: 1px solid #6678b1;
}
#employees td {
border-bottom: 1px solid #ccc;
color: #669;
padding: 8px 10px;
}
#employees tbody tr:hover td {
color: #009;
}
.slidecontainer {
width: 50%; /* Width of the outside container */
}
/* The slider itself */
.slider {
-webkit-appearance: none; /* Override default CSS styles */
appearance: none;
width: 50%; /* Full-width */
height: 25px; /* Specified height */
background: #d3d3d3; /* Grey background */
outline: none; /* Remove outline */
opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
-webkit-transition: .2s; /* 0.2 seconds transition on hover */
transition: opacity .2s;
}
/* Mouse-over effects */
.slider:hover {
opacity: 1; /* Fully shown on mouse-over */
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none; /* Override default look */
appearance: none;
width: 25px; /* Set a specific slider handle width */
height: 25px; /* Slider handle height */
background: #000000; /* Square background */
cursor: pointer; /* Cursor on hover */
}
.slider::-moz-range-thumb {
width: 25px; /* Set a specific slider handle width */
height: 25px; /* Slider handle height */
background: #4CAF50; /* Green background */
cursor: pointer; /* Cursor on hover */
}
</style>
</head>
<body>
<input type="checkbox" id="nowtv" name="nowtv" >
<label for="nowtv">Now TV</label>
</div>
<div>
<input type="checkbox" id="skytv" name="skytv" >
<label for="skytv">Sky Movies</label>
</div>
<div>
<input type="checkbox" id="iplayer" name="iplayer" >
<label for="iplayer">BBC iPlayer</label>
</div>
<h2>Max Run-Time:</h2>
<div class="slidecontainer">
<input type="range" min="0" max="200" value="0" class="slider" id="runtime">
<p>Runtime: <span id="runtime_"></span></p>
</div>
<table id="employees">
<tbody>
</tbody>
</table>
<script>
var slider = document.getElementById("runtime");
var output = document.getElementById("runtime_");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
/script>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<p id="record_count"></p>
<script>
function makeTable(data){
var tbl_body = "";
for (var i = 0; i < data.length; i++)
{
var tbl_row = "";
var t = i;
for (var j=0; j<4; j++)
{
//tbl_row +=("<td>" + data[i].tmdbid + "</td>");
tbl_row +=("<td><a href='new/" + data[i].tmdbid + "'><IMG SRC='webaddress"+ data[i].poster +"'></a></td>");
i++;
}
tbl_body += "<tr>"+tbl_row+"</tr>"
}
return tbl_body;
}
function getEmployeeFilterOptions(){
var opts = {
checkboxes: [],
sliderValue: null
};
$checkboxes.each(function(){
if(this.checked){
opts.checkboxes.push(this.name);
}
});
var slider = document.getElementById("runtime");
opts.sliderValue = slider.value;
return opts;
}
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: opts,
success: function(records){
console.log(records);
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
</script>
</body>
</html>
submit.php
<?php
$pdo = new PDO(
'mysql:host=xxxxxxxx;dbname=xxxxxxxx', 'xxxxxxxx', 'xxxxxxxx'
);
$checkboxes = $_POST["checkboxes"];
$slider_value = $_POST["sliderValue"];
$select = 'SELECT *';
$from = ' FROM streaming';
$where = ' WHERE poster <>"" AND runtime <' . $slider_value . ' AND channel = "X" ';
if (in_array("nowtv", $checkboxes))
{
$where .= ' OR channel = "NOWTV" ';
}
if (in_array("skytv", $checkboxes))
{
$where .= ' OR channel = "SKYTV" ';
}
if (in_array("iplayer", $checkboxes))
{
$where .= ' OR channel = "BBC" ';
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
>
The output I am expecting is for the user to be able to select the checkboxes and runtime - to then update the films available.
The current output shows nothing. :(

A large box keeps appearing above the form

I have a small problem with my website's contact page. Whenever I use php for the form another large box appears above the form as if there was a additional set of <p> tags there; I am not sure why this keeps happening.
Here is the code.
Update: I have removed the box problem but now I have to figure out the css to change so that the form fits in with the rest of the webpage, and auto; doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cromika Web Designs - Contact</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript">
function checkForm() {
var theName = document.getElementById('name').value;
var theEmail = document.getElementById('email').value;
var theMessage = document.getElementById('message');
var emailerr = document.getElementById('emailspan');
var nameerr = document.getElementById('namespan');
var messageerr = document.getElementById('messagespan');
var message;
var myregex = /\S+#\S+\.\S+/;
if(theName==""){
message = 'Name is required;';
document.form1.name.focus();
nameerr.innerHTML = message;
return false;
} else{
nameerr.innerHTML ="";
}
if(theEmail=="") {
message = 'Email is required;';
document.form1.email.focus();
emailerr.innerHTML = message;
return false;
} else if (!myregex.test(theEmail)){
emailerr.innerHTML = "Your email entry is invalid;";
document.form1.email.focus();
return false;
} else {
emailer.innerHTML ="";
}
if(theMessage.value=="" || theMessage.value ==null || theMessage.value.indexOf('\n') > 0) {
message = 'Please enter your message;';
document.form1.message.focus();
messageerr.innerHTML = message;
return false;
} else {
messageerr.innerHTML = "";
}
}
</script>
</head>
<body>
<header><img src="images/simple-logo.png" alt=""</img> </header>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Gallery</li>
</ul>
</nav>
<h1> Contact me!</h1>
<?php
if(isset($_POST['send_email'])){
// collect the form values
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// set the email properties
$to = 'email#email.com';
$subject = "Contact Form Submission";
$from = $email;
$headers = "From: $from";
// attempt to send the mail, catch errors if they occur
try {
mail($to, $subject, $message, $headers);
$msg = "<strong>Your mail was sent successfully!</strong>";
} catch(Exception $e) {
$msg = "An Exception was thrown: ".$e -> getMessage()."<br>";
}
}
?>
<table align="left">
<form name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>" onSubmit="return checkForm()">
<tr><th>Name:</th>
<td><input type="text" name="name" id="name" /><br><span style="color:red;" id="namespan"></span>
</td>
</tr>
<tr><th>Email:</th>
<td><input type="text" name="email" id="email" /><br><span style="color:red;" id="emailspan"></span>
</td>
</tr>
<tr><th>Message:</th>
<td><textarea name="message" id="message"></textarea><br><span style="color:red;" id="messagespan"></span>
</td>
</tr>
<tr><td></td><td><input type="submit" name="send_email" value="Send Email Message" /></td></tr>
</form>
</table>
<footer></footer>
</body>
</html>
And here is the CSS for the site
#charset "UTF-8";
/* CSS Document */
body{
font-size:16px;
cursor:default;
font-family:Georgia, serif;
background-color:#000000;
color: white;
}
header {
border-radius: 5px;
text-align: center;
margin-top: 12px;
height: 71px;
}
nav {
border-radius: 5px;
height: 20px;
width: auto;
display: block;
text-align:center;
padding-right: 35px;
color: #ffffff;
font-weight:bold;
background-color:#8000aa;
padding-top: .05px;
padding-bottom: 20px;
margin-top: 12px;
margin-bottom: 12px;}
nav li {
display: inline;
float: center;
}
nav a {
display: block, inline;
width: 60px;
}
/*link styles*/
a:link {
text-decoration: none;
}
a:visited {
text-decoration: underline;
color: white;
}
a:hover {
text-decoration: underline;
color: blue;
}
a:active {
text-decoration: underline;
}
/* end link styles */
/* main content */
h1 {
border-radius: 5px;
width: auto;
margin: 0 auto;
text-align: center;
margin-bottom: 12px;
background-color: #8000aa;}
table {
border-radius: 5px;
width: 36px;
height: 150px;
margin: 0 auto;
text-align: center;
padding-top:12px;
padding-bottom:12px;
margin-bottom: 12px;
background-color: #8000aa;
}
p {
border-radius: 5px;
width: auto;
height: auto;
margin: 0 auto;
text-align: center;
padding-top:12px;
padding-bottom:12px;
margin-bottom: 12px;
background-color: #8000aa;}
p a {
font-weight: bold;
}
/* end main content*/
footer {
border-radius: 5px;
clear: both;
text-align: center;
padding-top:12px;
padding-bottom:12px;
margin-bottom: 12px;
font-weight:bold;
background-color:#8000aa;}
Any help is appreciated!
Try removing the <p> and </p> from around the table you use for your form. While on my test system this didn't put an actual box, it certainly pushed the form part well down the page.
FYI, I used Google Chrome and right click and select Inspect Element and it's showed up quite quickly.

codeigniter chat box is not working

I am making a chat box in codeigniter, but after enter the name and message, pop up box is coming showing 'Forbidden'.
I am really confused what I put instead shout.php here(chatbox.php')
$.post('shout.php', load_data, function(data) {
instead of 'shout.php' I put http://localhost/myfoldername/application/views/shout.php
my controller
money_c
function chat(){
$this->load->view('chatbox');
}
chatbox.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chat Box</title>
<style type="text/css">
<!--
.shout_box {
background: #627BAE;
width: 260px;
overflow: hidden;
position: fixed;
bottom: 0;
right: 20%;
z-index:9;
}
.shout_box .header .close_btn {
background: url(images/close_btn.png) no-repeat 0px 0px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .close_btn:hover {
background: url(images/close_btn.png) no-repeat 0px -16px;
}
.shout_box .header .open_btn {
background: url(images/close_btn.png) no-repeat 0px -32px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .open_btn:hover {
background: url(images/close_btn.png) no-repeat 0px -48px;
}
.shout_box .header{
padding: 5px 3px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: bold;
color:#fff;
border: 1px solid rgba(0, 39, 121, .76);
border-bottom:none;
cursor: pointer;
}
.shout_box .header:hover{
background-color: #627BAE;
}
.shout_box .message_box {
background: #FFFFFF;
height: 200px;
overflow:auto;
border: 1px solid #CCC;
}
.shout_msg{
margin-bottom: 10px;
display: block;
border-bottom: 1px solid #F3F3F3;
padding: 0px 5px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
color:#7C7C7C;
}
.message_box:last-child {
border-bottom:none;
}
time{
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: normal;
float:right;
color: #D5D5D5;
}
.shout_msg .username{
margin-bottom: 10px;
margin-top: 10px;
}
.user_info input {
width: 98%;
height: 25px;
border: 1px solid #CCC;
border-top: none;
padding: 3px 0px 0px 3px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.shout_msg .username{
font-weight: bold;
display: block;
}
-->
</style>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('.message_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
//reset value of message box
$('#shout_message').val('');
}).fail(function(err) {
//alert HTTP server error
alert(err.statusText);
});
}
});
//toggle hide/show shout box
$(".close_btn").click(function (e) {
//get CSS display state of .toggle_chat element
var toggleState = $('.toggle_chat').css('display');
//toggle show/hide chat box
$('.toggle_chat').slideToggle();
//use toggleState var to change close/open icon image
if(toggleState == 'block')
{
$(".header div").attr('class', 'open_btn');
}else{
$(".header div").attr('class', 'close_btn');
}
});
});
</script>
</head>
<body>
<div class="shout_box">
<div class="header">chat box<div class="close_btn"> </div></div>
<div class="toggle_chat">
<div class="message_box">
</div>
<div class="user_info">
<input name="shout_username" id="shout_username" type="text" placeholder="Your Name" maxlength="15" />
<input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" />
</div>
</div>
</div>
</body>
</html>
shout.php
<?php
####### db config ##########
$db_username = 'root';
$db_password = '';
$db_name = 'money1';
$db_host = 'localhost';
####### db config end ##########
if($_POST)
{
//connect to mysql db
$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
if(isset($_POST["message"]) && strlen($_POST["message"])>0)
{
//sanitize user name and message received from chat box
//You can replace username with registerd username, if only registered users are allowed.
$username = filter_var(trim($_POST["username"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$message = filter_var(trim($_POST["message"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$user_ip = $_SERVER['REMOTE_ADDR'];
//insert new message in db
if(mysqli_query($sql_con,"INSERT INTO shout_box(user, message, ip_address) value('$username','$message','$user_ip')"))
{
$msg_time = date('h:i A M d',time()); // current time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$username.'</span><span class="message">'.$message.'</span></div>';
}
// delete all records except last 10, if you don't want to grow your db size!
mysqli_query($sql_con,"DELETE FROM shout_box WHERE id NOT IN (SELECT * FROM (SELECT id FROM shout_box ORDER BY id DESC LIMIT 0, 10) as sb)");
}
elseif($_POST["fetch"]==1)
{
$results = mysqli_query($sql_con,"SELECT user, message, date_time FROM (select * from shout_box ORDER BY id DESC LIMIT 10) shout_box ORDER BY shout_box.id ASC");
while($row = mysqli_fetch_array($results))
{
$msg_time = date('h:i A M d',strtotime($row["date_time"])); //message posted time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$row["user"].'</span> <span class="message">'.$row["message"].'</span></div>';
}
}
else
{
header('HTTP/1.1 500 Are you kiddin me?');
exit();
}
}
but after entering name and message alert box will pop up showing 'Forbidden'.
I don't think you fully grasp MVC architecture and this is not really the place to explain it.
I suggest you study it more but what may work for you here is to modify your controller function to this:
function chat(){
$this->load->view('chatbox');
}
function shout(){
$this->load->view('shout');
}
You would then need to ensure that the URL(route) works.
Assume you current URL is www.mysite.com/someController/chat/
then the new URL would be www.mysite.com/someController/shout/
If this URL does not work then you would need to sort out your route to make it work.
If this URL works, then you need to update your JQuery URL from
.post('shout.php', load_data, function(data) {
to
.post('/someController/shout/', load_data, function(data) {
TL;DR
The jquery post function accesses the fule via the URL like a real person. It cannot load the file directly.

jQuery get keyup on current change on input and output live

I had attempted with the following code and a little stuck now but here is what I'm wanting to achieve:
enter value in input and update preview html below
once user is happy with preview output can click generate
once clicked generate it will actually write the preview HTML to a first_name-last_name.html file within that same folder and then redirect to the first_name-last_name.html file
jQuery / HTML form:
<html>
<head>
<title>Ambient Lounge - Create eSig</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<!-- Include JS File Here -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url('http://fonts.googleapis.com/css?family=Open+Sans');
body {
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, sans-serif;
}
hr {
margin-bottom: 1.5em;
}
.error_wrapper {
color: #D8000C;
background-color: #FFBABA;
padding: 10px;
margin-bottom: 1em;
}
.success_wrapper {
color: #4F8A10;
background-color: #DFF2BF;
padding: 10px;
margin-bottom: 1em;
}
#main {
float: left;
width: 20%;
}
#preview {
float: left;
width: 80%;
}
form label {
display: none;
}
form input {
margin-bottom: 0.5em;
padding: 5px;
width: 80%;
}
</style>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".error_wrapper, .success_wrapper").hide();
var v_first_name = $("#first_name").val();
var v_last_name = $("#last_name").val();
var v_title = $("#title").val();
var v_address = $("#address").val();
var v_phone = $("#phone").val();
var v_mobile = $("#mobile").val();
var v_email = $("#email").val();
var v_web = $("#web").val();
$(".input_change").keyup(function(){
$("#btn").attr("disabled", "disabled");
var current_input = $(this).attr("id");
console.log(current_input);
$("#p_" + current_input).html($("#" + current_input).val());
});
$("#verify").click(function() {
var has_error = false;
$('#first_name, #last_name, #title, #address, #email, #web').each(function() {
$(this).attr('style', 'border: 0;');
if ($(this).val() == '') {
$(".error_msg").html("<strong>Error(s):</strong> You are missing some enteries, please check and try again.");
$(".error_wrapper").show();
$(this).attr('style', 'border: 1px solid red;');
has_error = true;
}
});
if (has_error != true) {
$(".error_wrapper").hide();
alert("You have verified changes, please double check and if happy click create otherwise change values and verify again.");
$("#btn").removeAttr('disabled');
}
});
$("#btn").click(function() {
$.post("create_post.php", { // Data Sending With Request To Server
first_name:v_first_name,
last_name:v_last_name,
title:v_title,
address:v_address,
phone:v_phone,
mobile:v_mobile,
email:v_email,
web:v_web
}, function(response,status) { // Required Callback Function
alert("*----Received Data----*\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
alert(response);
if(status == "success") {
$("#form")[0].reset();
} else {
}
});
});
});
</script>
</head>
<body>
<h2>Create e-mail signature</h2>
<hr>
<div class="error_wrapper">
<div class="error_msg"></div>
<ul></ul>
</div>
<div class="success_wrapper">
<div class="success_msg"><strong>Congraulations!</strong> You have successfully create your e-mail signature. You can view your e-mail signature by clicking here.</div>
</div>
<div id="main">
<form id="form" method="post">
<label>First Name</label>
<input type="text" name="first_name" id="first_name" class="input_change" placeholder="First name"/><br>
<label>Last Name</label>
<input type="text" name="last_name" id="last_name" class="input_change" placeholder="Last name"/><br>
<label>Title</label>
<input type="text" name="title" id="title" class="input_change" placeholder="Job title"/><br>
<label>Address</label>
<input type="text" name="address" id="address" class="input_change" placeholder="Business Address"/><br>
<label>Phone</label>
<input type="text" name="phone" id="phone" class="input_change" placeholder="Phone number"/><br>
<label>Mobile</label>
<input type="text" name="mobile" id="mobile" class="input_change" placeholder="Mobile number"/><br>
<label>Email</label>
<input type="text" name="email" id="email" class="input_change" placeholder="Email address"/><br>
<label>Web</label>
<input type="text" name="web" id="web" class="input_change" placeholder="Web address"/>
</form>
<button id="verify">Verify</button> <button id="btn" disabled>Create</button>
</div>
<div id="preview">
<!-- PREVIEW OF HTML EMAIL -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url('http://fonts.googleapis.com/css?family=Open+Sans');
.clear {
clear: both;
}
b {
font-weight: normal;
}
b.bold {
font-weight: bold;
}
.emailContent {
font-family:'Open Sans', 'Helvetica Neue', Helvetica, sans-serif;
width: 480px;
color: #767676;
}
.emailContent a {
color: #2A96B4;
text-decoration: none;
}
.emailName {
height: 62px;
}
.emailName img {
float: right;
margin-top: 1.2em;
margin-right: 0.8em;
}
.emailName p {
color: #767676;
font-size: 0.8em;
float: left;
}
.emailName p span {
color: #2A96B4;
font-weight: bold;
font-size: 1.2em;
}
.emailLogo {
height: 46px;
clear: both;
}
.emailLogo img {
float: left;
margin-top: 0.3em;
}
.emailLogo ul.socialList {
list-style: none;
border-left: 1px solid #aaaaaa;
padding-left: 1.5em;
margin: 0 0 0 1.5em;
float: left;
}
.emailLogo ul.socialList li {
display: inline-block;
}
.emailLogo ul.socialList li img {
margin: 0;
}
.emailDetails {
clear: both;
border-top: 5px solid #2A96B4;
margin-top: 1em;
}
.emailDetails p {
font-size: 12px;
margin: 0.3em 0;
}
.emailDetails p.larger {
font-size: 14px;
}
.emailDetails p span {
color: #2A96B4;
}
.emailNotice {
border-top: 1px solid #aaaaaa;
font-size: 0.6em;
padding-top: 0.8em;
margin-top: 2.5em;
}
</style>
<div class="emailContent">
<div class="emailName">
<p><span><b id="p_first_name" class="bold">James</b> <b id="p_last_name" class="bold">Brandon</b></span><br><b id="p_title">Global Technical Lead</b></p>
<img src="http://www.ambientlounge.com/emails/like-us-on-facebook.png" alt="Like us on Facebook" />
</div>
<div class="clear"></div>
<div class="emailLogo">
<img src="http://www.ambientlounge.com/emails/ambient-logo-email.png" alt="Ambient Lounge" />
<ul class="socialList">
<li><img src="http://www.ambientlounge.com/emails/icon-facebook.png" alt="Facebook" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-twitter.png" alt="Twitter" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-instagram.png" alt="Instagram" /></li>
</ul>
</div>
<div class="clear"></div>
<div class="emailDetails">
<p><span>a:</span> <b id="p_address">Old knows Factory, Unit 5C, Office 14, St Anns Hill Road, Nottingham, NG3 4GN</b></p>
<p><span>p:</span> <b id="p_phone">+44(0) 844 579 1112</b> | <span>m:</span> <b id="p_mobile">+44(0) 771 809 0 809</b></p>
<p class="larger"><span id="p_email">james#ambientlounge.com</b> | <b id="p_web">www.ambientlounge.co.uk</b></p>
</div>
<p class="emailNotice">This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.</p>
</div>
</div>
</body>
</html>
Current PHP Post file:
<?php
if($_POST["first_name"]) {
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$title = $_POST["title"];
$address = $_POST["address"];
$phone = $_POST["phone"];
$mobile = $_POST["mobile"];
$email = $_POST["email"];
$web = $_POST["web"];
$filePath == $first_name + "-" + $last_name + ".html";
if(file_exists($filePath)){
echo "Already exisits";
} else {
touch( $filePath ); //create file if it does not exist
fwrite( $file, '
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Ambient Lounge - e-Mail Signature (James Brandon)</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url("http://fonts.googleapis.com/css?family=Open+Sans");
.clear {
clear: both;
}
.emailContent {
font-family:"Open Sans", "Helvetica Neue", Helvetica, sans-serif;
width: 480px;
color: #767676;
}
.emailContent a {
color: #2A96B4;
text-decoration: none;
}
.emailName {
height: 62px;
}
.emailName img {
float: right;
margin-top: 1.2em;
margin-right: 0.8em;
}
.emailName p {
color: #767676;
font-size: 0.8em;
float: left;
}
.emailName p span {
color: #2A96B4;
font-weight: bold;
font-size: 1.2em;
}
.emailLogo {
height: 46px;
clear: both;
}
.emailLogo img {
float: left;
margin-top: 0.3em;
}
.emailLogo ul.socialList {
list-style: none;
border-left: 1px solid #aaaaaa;
padding-left: 1.5em;
margin: 0 0 0 1.5em;
float: left;
}
.emailLogo ul.socialList li {
display: inline-block;
}
.emailLogo ul.socialList li img {
margin: 0;
}
.emailDetails {
clear: both;
border-top: 5px solid #2A96B4;
margin-top: 1em;
}
.emailDetails p {
font-size: 12px;
margin: 0.3em 0;
}
.emailDetails p.larger {
font-size: 14px;
}
.emailDetails p span {
color: #2A96B4;
}
.emailNotice {
border-top: 1px solid #aaaaaa;
font-size: 0.6em;
padding-top: 0.8em;
margin-top: 2.5em;
}
</style>
<div class="emailContent">
');
fwrite( $file, '
<div class="emailName">
<p><span>'.$first_name.' '.$last_name.'</span><br>'.$title.'</p>
<img src="http://www.ambientlounge.com/emails/like-us-on-facebook.png" alt="Like us on Facebook" />
</div>
<div class="clear"></div>
<div class="emailLogo">
<img src="http://www.ambientlounge.com/emails/ambient-logo-email.png" alt="Ambient Lounge" />
<ul class="socialList">
<li><img src="http://www.ambientlounge.com/emails/icon-facebook.png" alt="Facebook" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-twitter.png" alt="Twitter" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-instagram.png" alt="Instagram" /></li>
</ul>
</div>
<div class="clear"></div>
<div class="emailDetails">
<p><span>a:</span> '.$address.'</p>
<p><span>p:</span> '.$phone.' | <span>m:</span> '.$mobile.'</p>
<p class="larger">'.$email.' | '.$web.'</p>
</div>
');
fwrite( $file, '
<p class="emailNotice">This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.</p>
</div>
</body>
</html>
');
$file = fopen( $filePath, "w" );
fwrite( $file, $data );
fclose( $file );
$data = file_get_contents( $filePath ); //do this after closing your writing
}
}
?>
You can write to a file with:
touch( $filePath ); //create file if it does not exist
$file = fopen( $filePath, "w" );
fwrite( $file, $data );
fclose( $file );
This will replace the entire file contents with what you fwrite().
You can check if a file already exists with
file_exists( $filePath );
You can define your custom file path in a manner like
$filePath = "whatever directory you want it to go to/". $firstnamevariable ."-". $lastnamevariable .".html";
You can keep a running $data variable that you write to the file at the end by appending to, like how $filePath above is appending. Or you can simply write to the file multiple time.
fwrite( $file, "<html><head></head><body>" );
fwrite( $file, "<div>First Name: ". $firstnamevaraible ."</div>" );
fwrite( $file, "<div>Last Name: ". $lastnamevariable ."</div>" );
fwrite( $file, "</body></html>" );
Once you've created your file, if you want to return the entire contents to the user you can do
$data = file_get_contents( $filePath ); //do this after closing your writing
Then you can echo $data to the user or if you want, just echo that function without the need for a variable.

Input sends empty message

I'm making live chatter for my project, and I need this script to recognize this:
If clientmsg is empty, it will call out an error and won't post the
message.
If clientmsg has more than 3 or 4 chars (letters) - it will post the message.
The code:
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
I can't find out how this works.
Here you can see the whole code for it.
index.php
<?php
/*****************************
File: index.php
Written by: exZerry development crew
******************************/
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "";
} else {
header ("Location: login.php");
}
require('includes/config.php');
echo $sOutput;
if(isset($_POST['enter'])){
if($_POST['username'] != ""){
$_SESSION['username'] = stripslashes(htmlspecialchars($_POST['username']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
?>
<style type="text/css">
input {
font: 12px;
}
.loginbox {
background-image: url(bar.png);
width: 100%;
height: 100%;
margin-top: -38;
}
#loginform {
font:16px dinpro;
color: #ffffff;
margin-top: 100;
}
#hedthe {
background-image: url(spacer.png);
font-family: bank-gt, sans-serif;
font-size: 34;
width: 830;
height: 34;
font-weight: normal;
}
#thereis {
magrin-top: -20;
}
#chatbox {
text-align: justify;
height: 70%;
width: 100%;
overflow: auto;
opacity: 0.91;
}
#usermsg {
width: 100%;
font-family: Play, sans-serif;
font-size: 14;
font-weight: normal;
color: #ffffff;
border: 0px solid black;
text-indent: 5px;
height: 32;
margin-top: 5px;
border: 0px solid black;
color: #ffffff;
background-image: url(chatinp.png);
}
input {
opacity: 0.7;
}
#submitmsg {
background-color: #48513e;
width: 0;
height: 0;
font-size: 20;
font-weight: normal;
color: #ffffff;
text-align: left;
border: 0px solid black;
}
.error {
color: #000000;
}
#menu {
margin-right: 0;
}
.welcome {
float:left;
}
.logout {
float:right;
}
.msgln {
margin-right: 0;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="modules/chatbox.js"></script>
<!-- Actual chat -->
<div id="chatbox">
<?php
if(file_exists("tmp/log.html") && filesize("tmp/log.html") > 0){
$handle = fopen("tmp/log.html", "r");
$contents = fread($handle, filesize("tmp/log.html"));
fclose($handle);
echo $contents;
}
?>
</div>
<form name="message" action="" id="sender" class="sender">
<input name="usermsg" id="usermsg" class="required" type="text" placeholder="Your message here" maxlength="60"/>
<input name="submitmsg" type="submit" id="submitmsg" width="0" height="0"/>
</form>
chatbox.js file
// jQuery Document
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url: "tmp/log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2000); //Reload file every 3 seconds
});
post3.php file
<?
session_start();
if(isset($_SESSION['username'])){
$text = $_POST['text'];
$fp = fopen("tmp/log.html", 'a');
fwrite($fp, "<div class='msgln'> <b>".$_SESSION['username']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
This is full js + php chatter.
Like this?
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 3){
$.post("post3.php", {text: clientmsg});
$("#usermsg").val("");
}else{
alert('error');
}
return false;
});
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
// check if the length of the string is greater than 3 letters
if(clientmsg.length > 3)
$.post("post3.php", {text: clientmsg});
else
alert("Error");
$("#usermsg").attr("value", "");
return false;
});

Categories