Check form for URLs before sending (server side) - javascript

I have the following code which checks the form before submitting on the server side, what I would like to include (if possible) is to check the message for URLs and if present to prevent the message from being sent.
if (!empty($_POST['name']) && !empty($_POST['fromemail']) && !empty($_POST['message']) && $go == TRUE)
{
//data has been filled
$name = Filter::no_html($_POST['name']);
$from = Filter::no_html($_POST['fromemail']);
$start_dt = Filter::no_html($_POST['start_dt']);
$end_dt = Filter::no_html($_POST['end_dt']);
$comments = Filter::no_html($_POST['message']);
$validate->isEmpty($name, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_NAME);
$validate->isEmpty($from, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_EMAIL);
$validate->isSingleEmail($from, LANG_JAVASCRIPT_PLEASE_ENTER_EMAIL);
$validate->isEmpty($start_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_START_DATE);
$validate->isEmpty($end_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_END_DATE);
$validate->isEmpty($comments, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_MESSAGE);
$modules->call_hook('contact_owner_submit', ''); // Call any module functions
$id = (int) #$_POST['ownerid'];
$vehicle = (int) #$_POST['listingid'];
if ($validate->isError())
{

You could search the message using the stristr method for certain criteria within the string:
$has_url = (stristr($comments, 'http') || stristr($comments, 'www.'));
if($has_url) {
// prevent submit
}
More info on the stristr method here:
https://www.php.net/manual/en/function.strstr.php
So your code could look like this:
if (!empty($_POST['name']) && !empty($_POST['fromemail']) && !empty($_POST['message']) && $go == TRUE) {
$has_url = (stristr($_POST['message'], 'http') || stristr($_POST['message'], 'www.'));
if($has_url) {
// whatever happens if contains url
}
$name = Filter::no_html($_POST['name']);
$from = Filter::no_html($_POST['fromemail']);
$start_dt = Filter::no_html($_POST['start_dt']);
$end_dt = Filter::no_html($_POST['end_dt']);
$comments = Filter::no_html($_POST['message']);
$validate->isEmpty($name, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_NAME);
$validate->isEmpty($from, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_EMAIL);
$validate->isSingleEmail($from, LANG_JAVASCRIPT_PLEASE_ENTER_EMAIL);
$validate->isEmpty($start_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_START_DATE);
$validate->isEmpty($end_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_END_DATE);
$validate->isEmpty($comments, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_MESSAGE);
$modules->call_hook('contact_owner_submit', ''); // Call any module functions
$id = (int) #$_POST['ownerid'];
$vehicle = (int) #$_POST['listingid'];
if ($validate->isError())
// whatever goes here
{
}

Related

Assigning PHP variable to JavaScript variable, value is disappearing

I am attempting to assign a PHP variable to a JavaScript variable. When I do 'console.log(ca)'; the console logs it as being an empty variable. But if I click "view page source code" it shows the variable being set correctly.
JavaScript:
function checkAnswer(o, header) {
x = document.getElementById(o);
var ca = "<?php echo $value['a']; ?>";
if (x.value == ca) {
document.getElementById(header).className = 'header bg-green';
console.log("test");
} else {
document.getElementById(header).className = 'header bg-red';
console.log("User: " + x.value + " Answer: " + ca);
}
}
Console Response:
User: Driller Answer:
Page Source Code:
function checkAnswer(o, header) {
x = document.getElementById(o);
var ca = "Driller";
if (x.value == ca) {
document.getElementById(header).className = 'header bg-green';
console.log("test");
} else {
document.getElementById(header).className = 'header bg-red';
console.log("User: " + x.value + " Answer: " + ca);
}
}
HTML/PHP that is calling the function:
<input type='radio' id='".$value['id']."1' name='".$value['id']."' value='".$value['o1']."' onChange='checkAnswer(\"".$value['id']."1\", \"header_".$value['id']."\")'/>
Can you help explain what you are trying to achieve?? as it is very unclear
x.value cannot equal "ca" from the description you gave.
Also you need to add the element with the id header_* to your question
<div id = 'header_" . $value['id'] ."'>
</div>
So that the onchange function can actually run.
The problem is that you are setting an element's property which does not exist in your DOM HTML.
That's why it is showing an error in console. [See Image]
You need to create an element of id header OR comment on the lines which are changing the header's class.
See below code which I have tested.
<?php
$value = array('id'=>1, 'o1' => 'Driller', 'a' => 'Driller');
echo "<input type='radio' id='" . $value['id'] . "1' name='" . $value['id'] . "' value='" . $value['o1'] . "' onChange='checkAnswer(\"" . $value['id'] . "1\", \"header_" . $value['id'] . "\")'/>
";
?>
<script>
function checkAnswer(o, header) {
x = document.getElementById(o);
var ca = "<?php echo $value['a']; ?>";
if (x.value == ca) {
//document.getElementById(header).className = 'header bg-green';
console.log("test");
} else {
//document.getElementById(header).className = 'header bg-red';
console.log("User: " + x.value + " Answer: " + ca);
}
}
</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";
}

Upload image with PHP and AngularJS

I am working on a admin panel which is going to add data on a SQLite DB using AngularJS and PHP and then show it in HTML. All good with data as arrays text date etc. The problem that I have is to upload an Image in a specified folder and store the path in my DB.
This is my PHP which store data in DB
<?php
try {
if (
empty($_POST['item']) ||
empty($_POST['description']) ||
empty($_POST['release']) ||
empty($_POST['demo']) ||
empty($_POST['type']) ||
empty($_POST['live']) ||
empty($_POST['client'])
) {
throw new PDOException("Invalid Request");
}
$item = $_POST['item'];
$description = $_POST['description'];
$release = $_POST['release'];
$demo = $_POST['demo'];
$type = $_POST['type'];
$live = $_POST['live'];
$client = $_POST['client'];
$objDb = new PDO('sqlite:../database/database');
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO 'items'
('id', 'item', 'description', 'release', 'demo', 'type', 'live', 'client')
VALUES (null, ?, ?, ?, ?, ?, ?, ?)";
$statement = $objDb->prepare($sql);
if (!$statement->execute(array($item, $description, $release, $demo, $type, $live, $client))) {
throw new PDOException("The execute method failed");
}
And this is my PHP which upload Images in a specified folder
<?php
if (isset($_POST['submit'])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<b>Stored in:</b> " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "<span>***Invalid file Size or Type***<span>";
}
}
?>
And this is my insert function from angular
$scope.insert = function() {
if ($scope.goodToGo()) {
var thisData = "item=" + $scope.item;
thisData += "&description=" + $scope.description;
thisData += "&release=" + $scope.release;
thisData += "&demo=" + $scope.demo;
thisData += "&client=" + $scope.client;
thisData += "&type=" + $scope.type;
thisData += "&live=" + $scope.live;
thisData += "&image=" + $scope.image;
$http({
method : 'POST',
url : urlInsert,
data : thisData,
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(_recordAddedSuccessfully(data)){
$scope.items.push({
id : data.item.id,
item : data.item.item,
description : data.item.description,
release : data.item.release,
demo : data.item.demo,
client : data.item.client,
client_name : data.item.client_name,
type : data.item.type,
type_name : data.item.type_name,
live : data.item.live,
live_name : data.item.live_name,
image : data.item.image,
done : data.item.done
});
$scope.clear();
}
})
.error(function(data, status, headers, config){
throw new Error('Something went wrong with inserting');
});
}
};
Have anyone any idea how to do this?
If you are uploading image then content type should be set to multipart/form-data i.e
headers : {'Content-Type' : 'multipart/form-data'}
rest looks fine.

How to see database values in html

I'm trying to visualize sql database. At the end I hope to see some kind of chart but I can't transform values from php to js and html. In my database are two entries from the same form. First file is a php file and I called it "read.php":
<?php
$con=mysqli_connect("localhost","root","password","databasename");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tablename");
while($row = mysqli_fetch_array($result)) {
$data[] = array(
'join_date' => $row['join_date'],
'column1' => $row['column1'],
'column2' => $row['column2'],
'column3' => $row['column3'],
'column4' => $row['column4']
);
echo json_encode($data);
}
mysqli_close($con);
?>
When I open this file I see it as json. I would like to see these columns in a html file so I made "readjson.html":
<!DOCTYPE html>
<html>
<body>
<h2> Database in html</h2>
One: <p1 id="origname1"></p1><br>
two: <span id="origname2"></span><br>
<script type="text/javascript" >
var baza = "<?php ($data )[http://localhost/read.php]; ?>";
document.getElementById("origname1").innerHTML=baza[0].join_date + ", " + baza[1].column1 + ", " + baza[0].column2 + ", " + baza[0].column3 + ", " + baza[0].column4;
document.getElementById("origname2").innerHTML=baza[1].join_date + ", " + baza[1].column1 + ", " + baza[1].column2 + ", " + baza[1].column3 + ", " + baza[1].column4;
</script>
</body>
</html>
When I open the readjson.html I see:
Database in html
One: undefined, undefined, undefined, undefined, undefined
two: undefined, undefined, undefined, undefined, undefined
Instead of undefined I would like to see the database entries. Please help.
Firsly, I want to know how you came up with this:
"<?php ($data )[http://localhost/read.php]; ?>";
This is no PHP syntax. What you want is to include that file, and in read.php do not print json_encode
<?php
$con=mysqli_connect("localhost","root","password","databasename");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tablename");
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] = array(
'join_date' => $row['join_date'],
'column1' => $row['column1'],
'column2' => $row['column2'],
'column3' => $row['column3'],
'column4' => $row['column4']
);
}
mysqli_close($con);
?>
Then including it:
<?php
include 'read.php';
?>
<!DOCTYPE html>
<html>
<body>
<h2> Database in html</h2>
One: <p1 id="origname1"></p1><br>
two: <span id="origname2"></span><br>
<script type="text/javascript" >
var baza = JSON.parse(<?php echo '"' . json_encode($data) . '"'; ?>);
document.getElementById("origname1").innerHTML=baza[0].join_date + ", " + baza[1].column1 + ", " + baza[0].column2 + ", " + baza[0].column3 + ", " + baza[0].column4;
document.getElementById("origname2").innerHTML=baza[1].join_date + ", " + baza[1].column1 + ", " + baza[1].column2 + ", " + baza[1].column3 + ", " + baza[1].column4;
</script>
</body>
</html>
I can't assure you this will work but do try it out!

A way to merge td's in a table

So I'm trying to create a weekly calendar.
I coded a loop in javascript creating the empty table and then afterwards modified the innerHTML of the appropriate td's from values taken from an SQL table using php and javascript.
My problem is that when I set the rowspan of the specific td instead of merging with the next td's it is moving them to the end of my table. If I have 2 more reputation points i will post pictures to show my problem.
Here is my code if you want to take a look at it
// Declare usefull information about the database and host
$mysql_host = "-host info-";
$mysql_database = "-database info-";
$mysql_user = "user";
$mysql_password = "pass";
// open the connection
$link = mysql_connect($mysql_host,$mysql_user, $mysql_password, $mysql_database);
// connect to the database
mysql_select_db($mysql_database, $link) or die('database not selected'. mysql_error());
// Select * from the table created in the database
$result = mysql_query("SELECT * FROM Appointment;")
or die("Could not query:" . mysql_error());
echo "<script type='text/javascript' > "
. "var hours = new Array('9:00','9:30','10:00','10:30','11:00','11:30', "
. "'12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30');"
. ""
. "var days = new Array('Mon','Tue','Wed','Thu','Fri','Sat');"
. ""
. "for ( i = 0; i < 14 ; i++ ) "
. "{"
. "document.write('<tr id='+hours[i]+':00'+'>');"
. "document.write('<th>'+ hours[i]+'</th> '); "
." for ( k = 0 ; k < 6; k++)"
."{"
. "document.write('<td id='+days[k] +'> </td>'); "
. "}"
. "document.write('</tr>');"
."}"
. " </script> ";
while( $row = mysql_fetch_array( $result ))
{
$timestamp = strtotime($row['Date']);
$day = date('D', $timestamp);
$from = $row['StartTime'];
$to = $row['EndTime'];
$rowspan = determinRowSpanBetween($from,$to);
echo "<script type='text/javascript'> "
. " var divToAddTo = GetElementInsideContainer('".$from."','".$day."');"
. "divToAddTo.className = 'busy';"
. "divToAddTo.rowspan='".$rowspan."';"
. "divToAddTo.innerHTML='Something to do';"
. "function GetElementInsideContainer(containerID, childID) {"
. " var elm = {};"
. " var elms = document.getElementById(containerID).getElementsByTagName('*');"
. " for (var i = 0; i < elms.length; i++) {"
. " if (elms[i].id === childID) {"
. " elm = elms[i];"
. " break;"
. " }"
. "}"
. "return elm;"
. "}"
. " </script>" ;
}
the function determinRowSpanBetween is created later on in the code.
Having a rowspan > 1 in a td that is only supposed to take up one space (i.e. one that is not merged with other td's) will cause a whole bunch of errors. Make sure you account for every row you add to rowspan.

Categories