I wanna get just $_SESSION["yetki"] value when I call users function actually I am getting value but always getting "manager" value even if user equal student .
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>
}
else ()
{
<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>
}
}
</script>
What you are doing is completly wrong, you are mixing both client side and server side code, javascript is client side code and php is server side language. In your if else condition you need to send request to server to set that session variable. For sending request to server you can use ajax.
Actually, you got all your fundamental understanding of Php and JavaScript wrong. By the time that this script is already running in the client's web browser, the Php scripts would have been processed/executed already and echoed into the document body.
Here's how it works. When you ask for a Php "page", the server would execute every Php script in that page and generate a response. That response would be the one that your web browser would execute.
for example, if you do this:
<script>
if (<?Php echo "true"; ?>) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
The one you'll see in your web browser is:
<script>
if (true) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
What Php does is to create dynamic contents for the webpage and send it back to the client. The client's web browser would then execute the result of that generated content. The Php codes would all be executed as soon as you requested for the web page - the process all happens in the server. JavaScript, on the other hand, would execute AFTER the client receives the web page.
In fact, "echo" is a pretty descriptive term of what Php does. When you type a web address in your browser's address bar and press enter, you are sending a request to the server. Once it "hits" the server, it will "echo" a response in the form of HTML. That HTML would then be read by your web browser and that would include everything from Javascript to CSS. And yes, you can even echo a whole mix of HTML elements and Javascript content. You can even echo the whole document body.
for example:
<?Php
echo
<<<YOURCONTENT
<HTML>
<HEAD></HEAD>
<BODY>You're gonna love my body.</BODY>
</HTML>
YOURCONTENT;
?>
WHAT YOU SHOULD DO FIRST is to validate what the contents of $_SESSION["yetki"] would be.
<?Php
if(your conditions here)
$_SESSION["yetki"]="student";
else
$_SESSION["yetki"]="manager";
?>
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
alert('<?php echo $_SESSION["yetki"]; ?>');
}
else
{ // I DON'T KNOW WHAT YOU'RE TRYING HERE, BUT LET'S DO AN ALERT.
alert('<?php echo $_SESSION["yetki"]; ?>');
}
}
</script>
possible conditions for Php if statement:
$_POST['yourFormInputName'] == 'yourRogueValue'
or
$_GET['yourURLVariableName'] == 'yourRogueValue'
or
$_SESSION['perhapsAnotherStoredSession'] == 'yourRogueValue'
you can do with something like this.. but don't know is this a good answer
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
var aa = "<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>"
}
else
{
var aa = "<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>"
}
alert(aa);
}
</script>
Related
I have been developing a social network. I have noticed some security issues where the user can change the variables in javascript/jquery to other user_id's, text content, and other information that has been loaded into the scripts. And this is all done via the inspect tool or other software that can edit the languages. They can even rewrite the functions.
I load data onto the page via php and sql after sending the url_id to a php function.
I have javascript and jquery scripts that in return use this data to perform ajax, post, and get requests and to perform functions.
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
These scripts are included in the php pages or in php scripts that are loaded via ajax.
How can I stop this? Can you give me an easy explanation? I have been searching for months on how to stop this. I still don't understand how to stop the user from doing so. If there is another way could to do this? Can you provide me with true 100% examples? What are the other options I have?
Here are some snippets of my code
<? if (login_check($mysqli) == true) : ?>
<script>
$.post("auto/online.php?q=<? echo $id ?>");
function o() {
setTimeout(function() {
$.post("auto/online.php?q=<? echo $id ?>");
o();
}, 6e4);
}
</script>
<? endif; ?>
<?php echo '<div class="post-btn" onclick="ajaxPost(postenter.value,\''.$name.'\',\''.$id.'\');" title="Post">Post</div>'; ?>
function ajaxPost(content,name,id) {
var ip = '<?php echo $ip ?>';
content = content.replace(/<br\s*\/?>/mg,"\n");
var postArray = [content, id, ip];
postArray = JSON.stringify(postArray);
alert(postArray);
if (content.length == 0) {
alert('Oops it looks like your post is empty.');
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("postenter").innerHTML = "";
var html = xmlhttp.responseText;
alert(html);
$(html).hide().insertAfter("#wrapper").fadeIn(500);
document.getElementById("postenter").value = "";
}
}
xmlhttp.open("POST", "auto/post.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send('data=' + postArray);
}
}
<? if ($id == $user) : ?>
<div class="modalSetPro" onclick="setProImage(<? echo $picID; ?>,<? echo $uid; ?>)">Set Profile</div>
<div class="modalSetBac" onclick="setProCover(<? echo $picID; ?>,<? echo $uid; ?>)">Set Background</div>
<div class="modalDelImg" onclick="delItemPre(<? echo $picID; ?>, 1, <? echo $uid; ?>)">Delete</div>
<? endif; ?>
function delItemPre(itemID, type, user) {
var modArr = [itemID, type, user];
modArr = JSON.stringify(modArr);
$("#LoadMe").load('modals/del_modal.php?p=' + modArr);
}
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
You can't.
Your server side code should evaluate the user's privileges and decide whether or not they can do the action. JavaScript validation is more for the user experience - guiding and preventing mistakes.
You are not able to prevent this, which is why server-side validation is required.
Here is a stackoverflow discussing it: Why do we need both client side and server side validation?
There is some good information here:
http://www.w3schools.com/php/php_form_validation.asp
Basically, you want to put your validations in the PHP page that you are posting your ajax to.
Store and check all insecure data on server side, not client. This way user can't change it.
First of all when you are working on client side you have no control how user interact with you jquery or javascript code. So thumb rule is that never expose sensitive data in html or java script.
More over If you are curious about security you have not required to load User id in hidden field or any other client side code(html). In you case like when user is replying to any post you have to crosscheck at server side whether current logged in user is authorized to perform this task or not. also cross check whether this post is relate to current logged in user.
I have no knowledge about php but in asp.net we can create a session at server side and when user post data get the User id from session not from html content posted by user.
If this was in asks, sorry for that, but I want to speed help, thanks!
Do you have suggestions for result this ? Because when I do this it show last $name, it doesn't work.
JavaScript:
var name = 'Test';
if(name === 'Test'){
<?php $name = "Test"; ?>
} else {
<?php $name = "Error"; ?>
}
I have click function and when I click I check ID of object, but after this I want check this id is good e.g. (if(id === 'content')) and show good alert, when i checked it.
This is your server-side code, which will execute exactly once when the page is requested:
$name = "Test";
$name = "Error";
After this code executes, $name will be "Error". Every time.
This is your client-side code, which will execute exactly once when the page renders in the browser:
var name = 'Test';
if(name === 'Test'){
} else {
}
After this code executes, name will be 'Test'. Every time.
You're trying to mix server-side code and client-side code. They don't mix like that. They execute on two completely different platforms at two completely different times in two completely different contexts. Whatever you're trying to do (which we don't know), this isn't how you do it.
The way you wrote it isn't going to work. First of all PHP is executed before the JavaScript is parsed. In your code you set a variable inside PHP, so nothing actually happens. If you want something written on the page use echo or print.
What I think you want is to send a variable to PHP. For this you need a form or an Ajax-call.
If you want it the other way around, set a JavaScript variable based upon a PHP value you need to use JSON notification.
The only way I could even think of doing this would be:
<script>
var name = 'Test';
if(name === 'Test'){
</script>
<?php $name = "Test"; ?>
<script>
} else {
</script>
<?php $name = "Error"; ?>
<script>
}
</script>
i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?
I want to call function deleteUser() after JavaScript confirmation. Here is my code. Please help me.
<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
echo '
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
deleteUser();
}
</script>';
function deleteUser(){
$sql_DeleteUser="UPDATE login
SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
<script type="text/javascript">
alert("User '.$Name.' Successfully deleted.");
window.location.href = "../pages/DeleteUser.php";
</script>';
}
?>
You have a few mistaken theories in your initial question. Although JavaScript is a client-side language, PHP is not. You will get an undefined function error with your current code, since it is not defined in javascript.
In order for JavaScript to execute a PHP function, it would be highly recommended to learn and use AJAX. AJAX can be used to dynamically execute PHP code when a user does a certain action. Many websites use this to query the database without reloading a page.
JavaScript will send a request to a PHP page, where the function will be executed. Refer to this page for a more in-depth example: Call PHP function from javascript
You can do it by to ways :
1/ Synchronously by redirecting to a php script by sending informations thanks to GET (for example):
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
window.location.href = ("myScript.php?user="+userName); //var userName should be defined before
}
</script>';
and myScript.php:
<?php
if isset($_GET['user']){
$name = $_GET['user'];
}
//some stuff
deleteUser($name); //Here you call your function
header('Location: myPage.php'); //You return to your first script
?>
2/ Asynchronously by calling an AJAX request to myScript.php
Use this code:
<?php
session_start();
include_once("DataSourceController.php");
$DeletedBy = $_SESSION['ID'];
$Name = $_GET['uname'];
function deleteUser(){
$sql_DeleteUser="UPDATE login
SET Deleted=1,DeletedAt= now(),DeletedBy=".$DeletedBy."
Where User='".$Name."';";
mysql_query($sql_DeleteUser);
echo'
<script type="text/javascript">
alert("User '.$Name.' Successfully deleted.");
window.location.href = "../pages/DeleteUser.php";
</script>';
}
//first, we check whether the user has confirmed or not
if(!isset($_GET['confirmed'])) { //if they haven't, we display the confirmation message
?>
<script type="text/javascript">
var responce=confirm("Are you sure you want to delete this user?");
if (!(responce==true)){
//if confirmed, reload the page with added 'confirmed' parameter
window.location.href="<?php echo $_SERVER['PHP_SELF'].$_SERVER['REQUEST_URI'] ?>?confirmed=1"
}
</script>
<?php
}
elseif($_GET['confirmed'] == 1) {
deleteUser();
}
?>
I have a session['password']. I would like to get the session value and use it to validate against user's input.
if(opw != $_session['password']){
errors[errors.length] = "Sorry, password does not match.";
}
This is what I have been trying, however if I input this they do not read the session. And ignore this conditions. How do I actually insert session value into Javascript?
As the other answers have suggested, you have to embed your PHP session value into the javascript when the page is generator. But the others have forgotten one important thing - you have to generate VALID javascript or your entire script will get killed with a syntax error.
if (opw != <?php echo json_encode($_SESSION['password']) ?>) {
Note the call to json_encode - it's not just enough to output the password string. You have to make sure that the password becomes a VALID javascript string, which json_encode ensures.
Your inline JavaScript code:
var session = <?php print $_SESSION['password']; ?>;
Is that what you're looking for?
You need to surround the $_SESSION in <?php echo ?>. This causes the PHP variable to be printed into the Javascript on the page.
if(opw != <?php echo $_SESSION['password']; ?> ){
However, this is a deeply insecure method of checking a password and I advise against using it. If not transferred over SSL, the password will be sent in plain text on every page view. Furthermore, it is likely to be cached by the web browser where anyone with access to the computer may read it.
You'll have to actually echo out the errors manually:
// do all of your validation and add all of the errors to an array.
if($opw != $_session['password']){
$errors[] = "Sorry, password does not match.";
}
echo "<script type=\"text/javascript\">var errors = ".
json_encode( $errors ).";</script>";
Then, later:
<script type="text/javascript">alert(errors)</script>
Please note that PHP is totally different from JS. PHP is a server side coding-language, meaning it get's executed when your server is rendering the requested page. In that page (which contains some HTML) there can also be JS. However, JS cannot connect to PHP in the way you think it does. For this you could use Ajax or something (but that's way too complicated for the goal you're trying to achieve).
You probably want something like this
// eg. index.php or something
...
<?php
session_start();
if ($_POST['password'] == 'somePassYouDefined') {
echo 'Authenticated';
}else if (isset($_POST['password'])) {
echo 'Couldn\'t authenticate ...';
}else {
?>
<form method='post'>
<input type='password' name='password' placeholder='Password' />
<input type='submit' />
</form>
<?php
}
?>
ASP version:
if(opw != '<%=Session("password")%>' ){
I added quotes because a password is usually a string.
When the user runs this script, the html page that is downloaded to their computer will display the password IN PLAIN TEXT, ie:
if(opw != 'BOBSPASSWORD' ){
So, if they don't know or have a password, they can view/source and find it.