How to enable javascript in my website? - javascript

I am doing a project to remotely display the data on the P10 Modules. I made the website for it, but whenever I want to retrieve data from the specific webpage on my website I get the error that is mentioned below;
The error I get when I try to retrieve data from the webpage1
The URL for the webpage is http://haider.paks.pk/test1/newfile.txt
<html>
<body>
<script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("b2a5a77ff21b1f1b4e9b8d9099c2f834");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://haider.paks.pk/test1/newfile.txt?i=1";</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body>
</html>
How can I possibly solve this issue? How to enable javascript in the coding? Where I would do it?
The codes for the web pages are;
Index page (Main Page)
<?php
//include auth.php file on all secure pages
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome Home</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<form action="get_msg.php" method="post">
<p>Select Department </p>
<br>
<select name="dept">
<option value="cs">CS</option>
<option value="ee">EE</option>
<option value="btn">BTN</option>
</select>
<p>Enter your message:<br />
<textarea name="sms" rows="10" cols="40"></textarea></p>
<p><input type="submit" value="Send it!" onclick="show()"></p>
</form>
<script>
function show() {
alert("Message send successfully");
}
</script>
<input type="button" name="b1" value="Show History"onclick="location.href='history.php'">
<p>This is secure area.</p>
<p>Dashboard</p>
Logout
</div>
</body>
</html>
get message page (The page that retrieves the sent message from the server
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
**Index2 webpage (The webpage that retrieves the message from get message webpage and sends it to the text file **
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>

I have resolved the issue. There is nothing wrong with the code. The only thing due to which this issue raised was that I was using free domain for my website. When I uploaded the same files on a paid hosting service, the issue was resolved and my arduino was able to retrieve the data from the web server.

Related

JS/HTML/PHP in one PHP program and MYSQL Updates via Server Sent Events

I'm building a two-way chat application that stores messages into a MySQL database. I would like to use Server Sent Events and have the PHP and HTML all in one page but the problem I'm facing is that the header cannot be set to text/event-stream or I will break the HTML.
My question is how can I have the PHP, JS and HTML on the same page when using Server Sent Events?
Here is my opening JS. I set the EventSource to index.php even though this might be wrong.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index.php");
source.onmessage = function(event) {
document.getElementsByClassName("message").innerHTML = event.data;
};
}else {
document.getElementsByClassName("message").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream");
}
else {
header("Content-Type: text/html");
}
//Database Stuff
$connect = mysqli_connect('localhost', 'user', 'Pass');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
?>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<?php echo "data: ".$row['mymessages']; flush();?>
</div>
</div>
<?php
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
?>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<?php echo "data: ".$row['yourmessages']; flush();?>
</div>
</div>
<?php
}
}
?>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
EDIT: I have tried separating the PHP the HTML and put the PHP logical part outside the HTML. I'm able to get Server Sent Events via inspector in Chrome but not sure how to loop through the DB entries in JS. I'm not comfortable with JS syntax.
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
if(isset($_POST['submit'])){
$send = $_POST['mymessage'];
$sendmsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('".$send."', '')";
}
if (!empty($_GET['yourmessage'])){
$recieve = $_GET['yourmessage'];
$recievemsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('', '".$recieve."')";
}
$connect = mysqli_connect('localhost', 'root', 'Walcott34');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$sqlrecieve = mysqli_query($connect, $recievemsg);
$sqlsend = mysqli_query($connect, $sendmsg);
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
echo "data: ".$row['mymessages']."\n\n";
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
echo "data: ".$row['yourmessages']."\n\n";
}
ob_flush();
flush();
}
}
else {
?>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index2.php");
source.onmessage = function(e){
document.getElementById("mymessages").innerHTML = event.data;
document.getElementById("yourmessages").innerHTML = event.data;
};
}else {
document.getElementsById('message').innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<div id='mymessage'>
</div>
</div>
</div>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<div id='yourmessage'>
</div>
</div>
</div>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
<?php } ?>
If your after it being in one file you just need the one outer if statement which separates the two logical parts.
<?php
if ($_SERVER["HTTP_ACCEPT"] === 'text/event-stream') {
// event stream code
...
while (true) {
...
} else {
// client side code
?>
<head>
<meta name="viewport" content="w
...
<?php }
You cant intertwine the two parts like your doing:
<div class='message'>
<?php echo "data: $row['mymessages']"; flush();?>
</div>
Your serverside part is incomplete but that's beyond the scope of the question,ive commented with a link to a working example.

Browser does not response to header redirect

please help... i am new to php. Thanks
php1 is to send a data ('1234') via method Post to php2. php2 is supposed to redirect using Header Location to php3 with a data ('invalid').
Developer Tools of Chrome indicate that everything went well (Post data sent and received. Get data sent and received).
Somehow, the browser does not response and stay at php1. I have tried Safari and Firefox. No response.
Would be really grateful if you could advise. Thanks
The 3 php files are:
php1
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
}
);
});
});
</script>
</head>
<body>
<div>
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>
php2
<?php
session_start();
ob_start();
error_reporting(E_ALL);
if (!empty($_POST)){
$Email = $_POST['email'];
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Location: php3.php?m=invalid');
exit();
}
} else {
header('Location: php1.php?m=nodata');
exit();
}
ob_end_flush();
?>
php3
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<?php echo $M; ?>
</div>
</body>
</html>
Here is a screenshot of chrome developer:
You should change the code for php1.php like this
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
$("#content").html(data); // <----- ADDED
}
);
});
});
</script>
</head>
<body>
<div id="content">
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

I'm just learning code.I want to know javascript or php code to show hidden paragraph <p>

<p hidden> Wrong email or password
html
$email=$_POST["login"];
$password=$_POST["password"];
$zz= "Select * from employer where EMMail='$email' and EMpassword='$password'";
$sql="select * from student where StudentEmail='$email' and StudentPassword='$password'";
if $email && $password !=$zz || $email && $password !=$sql{
}
how to show that para when username or password is incorrect?
Using PHP
You can simply just do something like this
$failed=true;
if $email && $password !=$zz || $email && $password !=$sql{
$failed=false;
}
and later where this certain paragraph is found:
echo "<p ". ($failed?"hidden":"")+">Wrong password!</p>
Different Pages
I would recommend to use different pages like this:
login
|--index.php //loginform
|--login.php
|--fail
| |--index.php //with link to login form
home
|--index.php
includes
|--sql.php
login/index.php
<html>
<head>
<title>
Login
</title>
<body>
<form action="login.php" method="POST">
<table>
<tr><td>User</td><td><input name="user" placeholder="johndoe123/></td></tr>
<tr><td>Pass</td><td><input type="password" name="pass" placeholder="iluvyou%&-"/></td></tr>
<tr colspan=2><td><input type="submit" value="Login" /></td></tr>
</table>
</form>
</body>
</html>
login/login.php
Note: Use prepared statements!!! The method you used is extremly vulnerable to SQL injection and XSS. Also: PLEASE hash the password(s)!
<?php
include "/includes/sql.php";
$user=$_POST["user"];
$passtry=$_POST["pass"];
$sql="SELECT * FROM users WHERE user='?'";
$cmd = $con->prepare($sql);
$cmd->execute(array($user));
if($entry=$cmd->fetchObject()){
$pass=$entry->pass;
}else{
header("Location: fail");
exit(0);
}
if(password_verify($passtry,$pass)){
session_start();
$_SESSION["login"]=true;
$_SESSION["user"]=$user;
header("Location: ../home");
}else{
header("Location: fail");
exit(0);
}
?>
fail/index.html
<html>
<head>
<title>
Wrong password!
</title>
</head>
<body>
<p>Wrong password. Try again!</p>
</body>
</html>
home/index.html
<?php
session_start();
if(!$_SESSION["login"]){
header("Location: ../login/fail");
exit();
}
?>
<html>
<head>
<title>
<?php echo $_SESSION["user"] ?> - Home
</title>
</head>
<body>
PRIVATE CONTENT!!!
</body>
</html>
includes/sql.php depends on your sql engine.
Note: In your register form you must save the password using password_hash()

php - Session Not Carrying Over but Variables Are

I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.
While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!
index.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
}
else{
}}
else{
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded" style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="user">Username</label>
<input type="text" class="form-control" id="email" name="user">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pass">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";
//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);
//Check Connection
if($conn->error){
die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
//echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";
$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;
//Execute
$result = $conn->query($sql);
if($conn->error){
echo "Load Error";
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($inputpass == $row["password"]){
echo '<div class="alert alert-success fade in">
x
Your credentials are correct
</div>';
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
$_SESSION["Auth"] = "yes";
$_SESSION["User"] = $inputuser;
}else{
echo '<div class="container-fluid"><div class="alert alert-danger fade in">
x
Your username or password is incorrect!
</div></div>';
$_SESSION["Auth"] =false;
//echo "Success";
}
} else {
//echo "Failed";
}
}
else{
//echo "Not Set";
}
?>
</body>
</html>
pihome.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
}
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] != "yes"){
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
echo "You are logged in as: ".$_SESSION["User"];
}else{
echo "Auth Passed";
$_SESSION["Auth"] = "yes";
}
}else{
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>
<script>
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
//document.write( response.controls[0].type );
document.getElementById("status").innerHTML = response.controls[0].type + " " + response.controls[0].state;
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'status.json' );
</script>
Logout
</div>
</body>
<html>
logout.php
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
session_unset();
}
else if($sessionstate == 2){
session_destroy();
echo "destroyed";
}
/*echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';*/
?>
I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

Categories

Resources