Trying to change from alert to popup window [duplicate] - javascript

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I'm trying to switch the "success/fail" notifications to my webpage. I've been successful doing this in several parts of my test website, but I'm running into a bit of a problem on my login page. My original way of doing this used an alert popup, which works okay, but doesn't provide the style I'm looking for. I decided to use the template that has been working for me in other parts of the website, but the login is unique since it's here where I establish my session for a user.
Here is my original login code which works as intended but uses a generic alert window...
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
}
}
mysqli_close($link);
?>
Here is the code I'm trying to get to work but comes up with
Parse error: syntax error, unexpected end of file on line 38.... which is my ?> to close out the php.
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
}
mysqli_close($link);
?>
I'm pretty sure this has to do with the quotes but I've tried several different combinations and I still get the error.
The window.open code works great on my other pages if I can keep all the if, else statements within the javascript. In these pages I just use the PHP tags to grab the parameters outside the javascript where needed.
However when I attempt to do with this with the $_Session, it doesn't work.
If this is a quotes problem, I'd appreciate it if someone could point me in the right direction. If this is related to the session, I could use some help formatting the javascript so I call the ?_Session properly.

There are so many quote issues with your code, try to put script separately or use heredoc, nowdoc.
PHP can read multiple lines with heredoc/nowdoc.
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Use delimiters and indentation correctly and you can put actual JS code in between.
Example as per your use case.
echo <<<SCRIPT
<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor="#EFEFEF"/>');
no.document.write('</br>');
no.document.write('<p style="text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px">Your credentials could not be verified</p></br>');
no.document.write('<div style="text-align:center"><button style="width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica" value="Close" onclick="window.close()"">OK</button></div>');
window.location.href = '../default.html';
</script>
SCRIPT;
Remember you can not use same kind of quote in between without escaping properly but you can also double between single and vice-versa.

I think your problem is using ' inside another '
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>...
You need to escape this char like this:
no.document.write('<p style=\'text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px\'>...

Related

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

How can i show a webpage only for logged in users? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Currently I'm working on a little project for login page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users. i am using php and sql for this. i want also a logout and senf to the index but i can't find te solution. Here is my code.
<?php
require ('sql_connect.php');
if (isset($_POST['submit'])){
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
if (!$_POST['uname'] | !$_POST['pass'])
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You did not complete all of the required fields')
window.location.href='index.html'
</SCRIPT>");
exit();
}
$sql= mysql_query("SELECT * FROM `login_users` WHERE `username` = '$username' AND `password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully!.')
window.location.href='homepage.html'
</SCRIPT>");
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Wrong username password combination.Please re-enter.')
window.location.href='index.html'
</SCRIPT>");
exit();
}
}
else{
}
?>
this is my control for the correct user and pass.
And here is the page i want to go if the user has logged in.
homepage.index:
<html>
<head>
</head>
<body>
<center><h1>Welcome user!</h1></center>
here some text and other stuff.
<h3>logout here<h3>
</body>
But now i can write www.mysite/homepage.index and i can go to this page without logging in. Can someone explain this?
Thank you.
Your question is part of many many available tutorials, did you try to google it first?
do not use mysql extension (using mysqli in example)
do not redirect via javascript, if you can do it via php
do not redirect to html files, when you need to work with php
do not store password as plain text (using php5.5+ function to crypt it in example)
do not select *
do not echo html code
use isset before getting value from $_POST, $_GET
Feel free to google everything to know the reasons.
<?php
class Connection //not sure what you have in sql_connect.php, I made this so the example is complete
{
static function getConnection(){
if(self::$connection === null)
self::$connection = new mysqli('127.0.0.1', 'root', '', 'so');
return self::$connection;
}
/** #var mysqli */
private static $connection;
}
<?php
class UserAuthenticator
{
function __construct(){
session_start(); //you need to start session when working with $_SESSION
}
function checkLogin(){
if(isset($_POST['submit'])){
$username = $this->getPostEscaped('uname');
$password = $this->getPost('pass'); //no need to escape through mysqli, we do not use it in query
if($username && $password){
$userData = Connection::getConnection()->query("SELECT password FROM login_users
WHERE username = '$username'")->fetch_assoc();
if($this->verifyPassword($password, $userData['password'])){
$this->login($username); //storing username for simplicity, but I do recommend to store id or some generated hash even better
$this->flash('Login succesfull.');
$this->redirect('homepage.php');
}else $this->flash('Wrong username / password combination. Please re-enter.');
}else $this->flash('You did not complete all of the required fields.');
$this->redirect('index.php');
}
}
function isLogged(){ //actual answer to the question - how to check the logged user
return isset($_SESSION['logged']);
}
function verifyPassword($password, $passwordHash){ //public so you can use it elsewhere
return password_verify($password, $passwordHash);
}
function getPasswordHash($password){ //public so you can use it elsewhere
return password_hash($password, PASSWORD_DEFAULT);
}
function showFlashMessages(){
if($flashMessages = $this->getFlashes()): ?>
<script language="JavaScript">
<?php foreach($flashMessages as $message): ?>
alert('<?= $message ?>');
<?php endforeach ?>
</script> <?php
endif;
unset($_SESSION['flashmessage']); //we need to remove messages, so they do not persist
}
function redirect($to = ''){ //you need to ensure you are not echoing any content before redirecting (that's a proper common way - learn it)
$url = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header('Location: ' . $url .'/'. $to, true, 302);
header('Connection: close');
exit;
}
private function login($userId){ //actual answer to the question - how to store the logged user
$_SESSION['logged'] = $userId;
}
private function flash($message){ //do not repeat yourself
if(!isset($_SESSION['flashmessage']))
$_SESSION['flashmessage'] = array();
$_SESSION['flashmessage'][] = $message;
}
private function getFlashes(){
return isset($_SESSION['flashmessage'])? $_SESSION['flashmessage']: [];
}
private function getPost($name, $default = null){ //do not repeat yourself
return isset($_POST[$name])? $_POST[$name]: $default;
}
private function getPostEscaped($name, $default = null){ //do not repeat yourself
return ($value = $this->getPost($name))?
Connection::getConnection()->real_escape_string($value): $default;
}
}
$ua = new UserAuthenticator();
$ua->checkLogin();
$ua->showFlashMessages();
you need to store passwords with
$ua = new UserAuthenticator();
$password = $ua->getPasswordHash($plainTextPassword); //store this to database
in homepage.php you can check logged status with
$ua = new UserAuthenticator();
if(!$ua->isLogged()){ $ua->redirect('index.php'); } //redirect to login page if not logged in
not tested anything of this, so typo is possible - sorry :)
Lets say your login was succesfull. All you have to do is this:
Session_start();
$_SESSION['id']= $row['id']; (make sure you changed mysql_num_rows to fetch assoc aswell)
Then on your index page at the top you add an if statement that checks wether or not the session has been set. For that you first need to call another session_start()
Hope this steers you in the right direction if not ill update my answer

Popup alert script in a php file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>

how to make the result appear in popup widow?

I want to make the result comes out in a popup window.
Code:
<?php
$con=mysqli_connect("localhost","root","1234","fyp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT password FROM admin WHERE email = '$_POST[email]' AND Admin = '$_POST[admin]'");
while($row = mysqli_fetch_array($result))
echo "your password is : " . " $row['password']" ;
mysqli_close($con);
?>
Is it possible to make it echoed in popup window like javascript alert messages ??
I have tried this but still not working
echo "<script> alert ("<?php echo 'your password is: ' . '$row['password']'?>")</script>";
I found a maybe strange solution for this a while back.
echo "<style onload=\"jsfunc($row['password']);\"></style>";
//in your html or javascript add this function
<script type='text/javascript'>
function jsfunc(data){
alert(data);
}
</script>
the style tag is invisible and will run the function onload, so when its gets echoed. Also I use the style tag because its one of the few tags where the onload works when you echo it like this.
Its a strange solution but it works.
There are some serious flaws in your code, including it being open to SQL Injection. I'd recommend changing it to look more like this:
$con = new MySQLi("localhost","root","1234","fyp");
if($con->connect_errorno) {
echo "Failed to connect to MySQL: ".$sql->connect_error;
}
$email = $sql->real_escape_string($_POST['email']);
$admin = $sql->real_escape_string($_POST['admin']);
$query = "SELECT password FROM admin WHERE email = '$email' AND Admin = '$admin'";
$result = $sql->query($query);
if($result) {
$row = mysqli_fetch_assoc($result);
$pass = $row['password'];
echo '<script> alert("Your password is '.$pass.'");</script>';
} else {
//do some error handling
}
//the closing of a mysqli connection is not required but
mysqli_close($con);
Real escape string is not 100% proof against injection but is a good place to start with sanitising your inputs. Additionally I would strongly advise against storing your passwords in plain text. Please take a look at the PHP sha1() function or the SQL equivalent when storing the passwords initially.
Use this code
<?php
$alert='your password is: '.$row['password'];
?>
<script>
alert("<?php echo $alert; ?>");
</script>
It will work for sure.

Javascript and PHP scan for nudity

I am trying to not allow the uploading of files that have nudity to my server. I found javascript online that will scan a photo for nudity. It comes with demo pics and an html file and js files. I am using PHP to upload the file and I am having trouble not allowing if the scan find that the pic has nudity.
Here is my code sample:
$q= "insert into $table values('', '$email', '$aim', '$icq', '$yahoo', '$homepage', '0', '0', '0', '0', '0', '0', '', now(),'$myip','$email2','$password','$title','$download','$approved','$allowdelete','$author','$facebook','$piclink','$domain','$option3','$secret')";
$result = mysql_query($q) or die("Failed: $sql - ".mysql_error());
$q = "select max(id) from $table";
$result = mysql_query($q);
$resrow = mysql_fetch_row($result);
$id = $resrow[0];
$file = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], "pics/".$id.".".$picext);
$picfile=$id.".".$picext;
echo '<script type="text/javascript" <src="nude.js">';
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
echo '</script>';
if ($nude === false) {
$q = "update $table set picfile = '".$id.".".$picext."' where id='$id'";
$result = mysql_query($q);
Header("Location: index.php?id=$id");
} else{
echo '<script type="text/javascript">';
echo 'alert("Nudity found. Please try again.")';
echo '</script>';
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
Header("Location: new2.php");
}
The code uploads the file and then it's supposed to check the file for nudity and delete it and tell the user to try again if nudity is found. If nudity is not found the user is brought to the main page of the site.(This is the add new photo page). All of the PHP is working fine, but since the javascript doesn't seem to be running the file i uploaded and then since $nude isn't set it goes into the else of the if statement and again the js doesnt run(no alert box), and then the file is deleted. How can I make the javascript run to scan my uploaded pic for nudity? What am I doing wrong here?
Any help is greatly appreciated!
P.S.
For those that would like to see the js file that is doing the scanning: http://pastebin.com/MpG7HntQ
The problem is that this line:
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
Doesn't do what you think it does.
When you output JavaScript via echo(), that code runs on the browser or client side and doesn't run until after the PHP script has finished.
You'll either need to port the code to PHP or use an AJAX call to report the validity of the images.

Categories

Resources