I have a php script that I got from another guy and for some reason the login function does not work unless it opens up in a new window. (??? no idea why but that's just how it is) Anyways when I execute the open up window javascript from my PHP file, it opens up a whole bunch of windows. I figured that it was somehow looping, so I put the javascript function inside of a for loop that should only execute once. When I click my button, it opens up windows continously until I feverishly close them all and it stops.
Here is the code that seems to be the issue:
if(basename($_SERVER['PHP_SELF'])==USRFILE && (isset($_REQUEST['usr']) || isset($_REQUEST['susr']) || isset($_GET['mp']) || isset($_REQUEST['rc'])))
{
if(ISAJAX === 0) include(USRTEMPL.'head.php'); // if not Ajax request, include head.php (from USRTEMPL)
include(USRINCLS.'class.UsersReg.php'); // include the class for Register (used also for Recovery data)
ob_start(); // start storing output in buffer
// if 'susr'=Register, create objet of UsersReg (for Register)
// if 'rc' or 'mp' (for Recover-Confirma), uses UsersRecov class
// if 'usr', create object of UserPage class (for user page data)
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
}
else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
include(USRINCLS.'class.UsersRecov.php'); //account recovery
$objRe = new UsersRecov($mysql);
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?rc=Recover');</script>";
}
}
Specifically this section:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
I tried looking up javascript opening up many windows but didn't find anything noteworthy. Same goes when I looked up php opening up a whole bunch of windows. It really makes no sense why it is looking, because it was looping before I put the for loop in. I put in the for loop to stop it, and it still loops.
If this code lives on or gets executed from users.php then that is your problem, because you would have an infinite loop.
The first line only runs this code on the users.php page (or it seems that way based on the constant name). The code goes on to say:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
I'm assuming that $lsite['users_logform']['register'] == 'Register'. Thus, when you visit users.php, this code runs. If the $_REQUEST['susr'] == 'Register' (because of the first page load that opened a new window to a url that matches users.php?susr=Regsiter), then you are instructing it to open ANOTHER instance of the page again, here:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
}
IMO, you need to tell the second request to users.php (generated by your javascript bit) that it is from javascript. Then ignore your entire code block if it is from javascript. Something like this should work:
if ( !isset($_GET['from_js']) && basename($_SERVER['PHP_SELF'])==USRFILE && ( isset($_REQUEST['usr']) || isset($_REQUEST['susr']) || isset($_GET['mp']) || isset($_REQUEST['rc']) ) )
{
if(ISAJAX === 0) include(USRTEMPL.'head.php'); // if not Ajax request, include head.php (from USRTEMPL)
include(USRINCLS.'class.UsersReg.php'); // include the class for Register (used also for Recovery data)
ob_start(); // start storing output in buffer
// if 'susr'=Register, create objet of UsersReg (for Register)
// if 'rc' or 'mp' (for Recover-Confirma), uses UsersRecov class
// if 'usr', create object of UserPage class (for user page data)
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
// there is no reason for the for loop. totally pointless
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register&from_js=1');</script>";
}
else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
include(USRINCLS.'class.UsersRecov.php'); //account recovery
$objRe = new UsersRecov($mysql);
// there is no reason for the for loop. totally pointless
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?rc=Recover&from_js=1');</script>";
}
}
Ok. I changed the first line to include a check for the $_GET['from_js'] variable. I removed the for loops, because they are totally pointless, since they only ever run once. To the urls that are opened in the new window, I added &from_js=1. With this, your code does not run on the subsequent new window openings. This will prevent the infinite popups.
Hopefully this helps.
Change
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
to:
header('Location: users.php?susr=Register');
Related
I have a javascript program that submits a form to a PHP page that collects data depending upon the form entries. I have verified that the data is returned correctly. In the following piece of the code, the success portion of the ajax call is shown:
success: function(msg){
var newWindow = window.open("_blank");
var result = $.parseJSON(msg);
var array =
newWindow.document.open();
newWindow.document.write("<!DOCTYPE html><html><head></head><body>");
for( var i=0; i<result.entries.length; i++ ) {
var obj = result.entries[i];
newWindow.document.write(unescape(obj));
}
newWindow.document.write("</body></html>");
newWindow.document.close();
newWindow.focus();
alert( "Printout complete" );
}
The tab is opened, and the entries[i] elements, which are strings, are written to the new tab. This is what is displayed on the browser window:
<h1>Age 1</h1><h2>Test</h2><br/>Test
The page source shows:
<html><head></head><body>"<h1>Age</h1><h2>Test</h2><br/>Test"</body></html>
The PHP page which filled the result obj contained:
...
if( $age != $last_age ) {
$last_age = $age;
array_push($items,"<h1>Age $age</h1>");
}
if( $age == $last_age && $event != $last_event ) {
$last_event = $event;
array_push($items,"<h2>$event</h2>");
}
array_push($items,"<br/>$data");
}
$result["entries"] = $items;
header("Content-type: application/json");
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($result);
It appears that putting the h1 etc. into the strings to be returned result in them being encoded as <h1> etc. They then show up in the source code for the page as '<', but the entire lines containing the entries[i] is enclosed in double quotes. If where I write unescape(obj), I substitute "<h1>Hello World</h1>", I get that rendered on the page.
How do I get the HTML to the page and have it rendered with the h1, h2, etc.?
Well, it was going around my elbow to get from my finger to my thumb, BUT, I got it to work. In the PHP I changed to store a JSON array as each element in items, viz.
$nameAttr = 'h1';
$item = array();
$item[$nameAttr] = "Age $age";
array_push($items,$item);
similarly for h2 element and straight text element.
In the index.html page where it is processed I replaced the newWindow.document.write(obj), with:
var objJSON = result.entries[i];
$.each(objJSON, function(key, value) {
if( key == 'h1' ) {
newWindow.document.write("<center><h1>"+value+"</h1></center>");
} else if (key == 'h2' ) {
newWindow.document.write("<center><h2>"+value+"</h2></center><br/>");
} else {
newWindow.document.write(value);
}
});
}
It rendered as I wished! This seems inordinately complex to do such a simple thing as one might have many types of entries on the page such as <tr>, etc. This method would require 'keys' for each html element and a subsequent handler for that key. If anyone has a clue how to include the html tags in the PHP code, it would be helpful!
I am having 2 portions of code (php and javascript).
In the PHP file, I use the function json_encode() to create a JSON data which will be sent to the Javascript file.
PHP FIle
<?php
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code])) {
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
if($total_items == 0){
unset($_SESSION["products"]);
}else{
//Calculate total of items in the cart
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
$product_price = $product["price"];
$product_quantity = $product["quantity"];
$subtotal = $product_price * $product_quantity;
$total += $subtotal;
}
}
die(json_encode(array('items'=>$total_items, 'total'=>$total)));
}
?>
Javascript File
<script>
$(document).ready(function(){
$(".contentwrapper .content").on('click', 'a.removebutton', function() {
var pcode = $(this).attr("data-code"); //get product code
$.getJSON( "phpfile.php", {"remove_code":pcode}, function(data) {
alert(data.items);// the total number of item
});
});
</script>
Anytime the query $.getJSON( "phpfile.php", {"remove_code":pcode}... is successful, an alert is displayed showing the data.items. The problem I am facing is that, when data.items is greater than or equal to 1 the alert is prompted, but when data.items is equal to 0, no alert is prompted.
Kindly help me solve this problem
Looks like a PHP error. $total variable is only declared inside the 'else' condition, so when ($total_items == 0) $total is undefined. But as you've called die(json_encode(array('items'=>$total_items, 'total'=>$total))); the server doesn't have a chance to complain (maybe returning no data and hence no alert). If you try declaring $total = 0 before your condition it should also fix the issue, without having to die early.
One possibility is that actually data variable is undefined/null e.t.c., see this for example, second alert is not shown. Instead an error is shown on the browser console.
var data = {items:0};
alert(data.items);
data = null;
alert(data.items);
Adding die(json_encode(array('items'=>$total_items))); at the end of the condition if($total_items == 0) and it solves the problem. But I really can't explain what is happening. Up to now I do not really know the origin of the problem. Any explanation will be welcomed
This question already exists:
Blocking a user from logging in with a certain permission level and then an alert displaying to let them know why
Closed 7 years ago.
I am trying to figure out how to deny a user access from signing in to my site unless they have been approved. I am making my site private to only those I allow to join. Anyone can register, but once they do they are given a permission/group level of 1 or 'bench'. Once I accept the user and change the permission level, then they are able to login.
As of now, I am stopping the level/group 1 users with a redirect back to the index page(where they sign in at). However, I want to not allow them to move forward to the next page at all. The reason being is I want to display some sort of pop up alert displaying a message that I created.
I'm not sure if I can do this with validation or the way I am trying to do it. I added on to my login code and am attempting to put my permission code I had on the signed in page to try to stop it from the start. Basically, in an attempt that if the user tries to log in, the script dies once it sees that the permission level is at the group 'bench'. Then a pop alert displays saying why.
I'm not having much success with it. My group/permission levels have a name and ID. I have tried putting both in this single quotatiob's like 'bench' and '1', but I get the same error with both.
Fatal error: Call to a member function hasPermission() on a non-object in /home4/pfarley1/public_html/example.com/index.php on line 12
I'm trying to log them in like this...
<?php
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
// added this line in
if($user->hasPermission('1')) {
die($permissionError);}
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('userIndex.php');
} else {
$tryagain = '<span class="signinpanel">' . "The information you entered did not match our records." . '</span>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
My permission code for users..
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return true;
}
}
return false;
}
What am I doing wrong this this or is there a better way to do this?
Edit:
The last question wasn't specific enough, so I added info and there has been modification to the code in how I was trying to do this.
What is $user on line 12?
if($user->hasPermission('1')) {
Error message is pretty explicit.
I have a bit of javascript that posts to a php, every second, which checks a schedule and basically returns "refresh" if the start time is met then returns refresh when the end time is met.
if "refresh" it reloads the page showing what its suppose to.
function checkSchedules(){
if(sch_timer)
clearInterval(sch_timer)
$.ajax({
url:'checkSchedule_test.php?mediaID='+mediaIDArray[schCount],
type:'GET',
complete: function (response) {
if(response.responseText == "refresh"){
location.reload(true);
}
},
error: function () {
alert('Sorry there was an error!');
},
})
sch_timer = setTimeout(checkSchedules,1000);
schCount = (schCount >= urlArray.length - 1)? -1 : schCount
++schCount
}
in the php
if ($current_date>=$startDate && $current_date<=$endDate){
if ($current_time >= $startTime && $current_time <= $endTime){
$timeout = $endTime - $current_time;
if ($current_time >= $startTime && $current_time <= ($startTime+3000)){
echo "refresh";
}
if($timeout<=3000){
echo "refresh";
}
}
}
when the start time is met it refreshes fine, works great.
then when the end time is met it refreshes but the contents the same.
if I hit refresh it works fine.
I've tried different methods of reload() (document.reload, etc...)
Has anyone got any ideas?
Cheers
use console to understand what is returning from server
use debug() or console.log() for understand what is returning from php ... reload script is correct issue will be during ajax
I have a list of files made by my PHP code
if ($handle = opendir($director))
{
$path="images/files/nou/";
if(Files::is_empty_dir($director))
{
echo "<p>There are no script available.</p>";
}
else
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$size=Files::getSize($director."/".$file);
$exts=Files::getExtension($file);
$filex = str_replace(".".$exts,"",$file);
if(strlen($filex)>10)
{
$filex=substr($filex,0,6);
}
echo "<div class='file' title='".$file."'>".$filex."</div>";
There are functions defined in my own class Files.
Good. I want that on mouseover to show file information with this code
function getInfo($file)
{
$info="<div class='info_public'><table border=0 cellpadding=2><tr>";
$info.="<td>File : </td><td>".$file."</td></tr>";
$info.="<tr><td>Extension : </td><td>".Files::getExtension($file)."</td></tr>";
$info.="<tr><td>Size : </td><td>".Files::getSize($file)."</td></tr>";
return $info;
}
I want to show info dynamically with JQuery. I wrote this
$(".file").mouseover(function()
{
data=$(this).attr("title");
alert(data);
});
It alerts always first filename not what I crossed with mouse. But if I disable mouseover JQuery function, the title appears correctly for each file in part. If I use mouseover function, the selected value from title doesn't appear correctly, it shows first filename in alert no matter what file I crossed with mouse.
I called the alert function to see results before implementing $.ajax function to avoid bad responses.
What's the problem in my script ?
Thank you
Your jquery code works, so check something else, may be you need to onload() that script ?
http://jsfiddle.net/oceog/hJyRm/