$_GET OR escape string being unpredictable. Please explain? - php

i simply pass 3 values to the URL and while testing i was trying to echo them back to the screen but it will only echo each value once even though i have set it to echo at various points. once i escape the value it wont let me echo it. Why is this?
<?php
session_start();
if (isset($_SESSION['SESSION_C']) && ($_SESSION['SESSION_C']==true))
{
$getyear = $_GET["Year"];
echo $getyear; (IT WILL ECHO AT THIS POINT)
$getyear = mysql_real_escape_string($getyear);
echo $getyear; (BUT WONT ECHO HERE)
$getsite = $_GET["Site"];
echo $getsite;
$getsite = mysql_real_escape_string($getsite);
echo $getsite;
$getsite = str_replace(' ', '', $getsite);
echo $getsite;
$getdoc = $_GET["Doc"];
echo $getdoc;
$getdoc = mysql_real_escape_string($getdoc);
echo $getdoc;
}
else
{
echo "sessionerror";
}
?>

mysql_real_escape_string() requires a open connection to mysql. Otherwise it will return false. I guess var_dump($getdoc); will give you boolean(false).
You'll have to call mysql_connect() before that code.

Related

Why the php 'if statement' does not give expected result?

I am designing a php application using AJAX and PHP.
But the if statement in my php file behaves unexpectedly.
The request method is 'POST';
Ajax code is
function fetchData(){
var recipename = document.getElementById("recipe").value;
var calorie = false;
createRequestObject();
//window.alert(calorie);
var url = "reciepinfo.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
window.alert(calorie);
xmlHttp.send("recipe="+recipename+"&calorie="+calorie);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState===4 && xmlHttp.status===200){
document.getElementById("target").innerHTML = xmlHttp.responseText;
}
}
}
And php code is:
<?php
$_SESSION['flag']=false;
if($_SESSION['flag']==false){
session_start();
$_SESSION['flag']=true;
}
$recipename = $_REQUEST['recipe'];
$calorie = $_REQUEST['calorie'];
echo $calorie;
$calorietemp = 0;
//echo $recipename;
$database = "nutrition";
$link = mysqli_connect('localhost','root','',$database);
$query = "select * from recipestb where name='$recipename'";
//$result = mysqli_query($link,$query);
//$obj = mysqli_fetch_object($result);;
if($link){
$result = mysqli_query($link,$query);
$obj = mysqli_fetch_object($result);
//$arr = mysqli_fetch_array($result);
//$names = "";
if(is_object($obj)){
echo "<i/>";
echo "<font size='5'>";
echo "Recipe name: ".$obj->name;
echo '<br/>';
echo "Carbohydrates : ".$obj->carbs." grams";
echo '<br/>';
echo "Proteins: ".$obj->protein." grams";
echo '<br/>';
echo "Fat: ".$obj->fat." grams";
echo '<br/>';
echo "Calories: ".$obj->calorie." cal";
$calorietemp = $obj->calorie;
echo '<br/>';
}else{
echo "non object";
}
}else{
echo "Connection failed";
}
if($calorie==true){
echo $calorie;
$_SESSION['caloriecount'] = $_SESSION['caloriecount'] + $calorietemp;
echo "Total calorie in diet :".$_SESSION['caloriecount'];
}
My session handling is weird i accept, but neglecting that, even the variable calorie is explicitly set to false, the if block executes.The echo $calorie statement also executes and it displays $calorie as false.
And i am not getting what is going wrong exactly.
Almost irritated with this.
Can anybody help?
EDIT1:
The php code is fine...
Ajax code has some problem...
When i set the $calorie to false in php code..
It behaved properly..
Leaving the session handling aside, the $calorie problem ...
You pass the data via AJAX as strings.
$calorie = 'false';
var_dump((true == $calorie));
You will get always bool(true). Using your AJAX example above, try this snippet instead (and use POST instead of REQUEST):
$calorie = ('true' == $_POST['calorie']);
var_dump($calorie);
// produces `bool(false)`
As a beginner i was unaware that the java-script variable with value false is passed as a string "false" to a server side script like PHP.
If we use a boolval(), in PHP this issue can be resolved.
PHP boolval()
I set the $calorie in my java-script to 0 or 1 as per my need.
When i wanted the false value to be sent to PHP script ,i set $calorie in java-script to 0 and the boolval() in corresponding PHP script evaluated it as false.
So the issue was resolved.

Passing a PHP Value from a link

I am new to PHP and learning. I'm trying to pass a value through a url link but it doesn't seem to work.
The link value I am passing is http://www.mysite.com/index.php?id=f
I want to run a js script if ID not F seen below but right now when I run it. It doesn't do anything:
<?php
$ShowDeskTop = $_GET['id'];
if (isset($ShowDeskTop)){
echo $ShowDeskTop;
if ($ShowDeskTop != "f"){
echo "ShowDeskTop Value is not F";
echo "<script type=\"text/javascript\">";
echo "if (screen.width<800)";
echo "{";
echo "window.location=\"../mobile/index.php\"";
echo "}";
echo "</script>";
};
};
?>
I know this is easy PHP 101 but I can't figure it out. I have tried everything from w3schools to other sites on Google for the answer and having no luck. Could someone please tell me what I am doing wrong?
Thank you!
$ShowDeskTop is not the same as $ShowDesktop variables names are case sensitive!
This is never gonna work since you set the variable AFTER checking if it exist..
The most easy way:
<?php
if (isset($_GET['id'])) {
echo $_GET['id'];
if ($_GET['id'] != 'f') {
?>
<script type="text/javascript">
if (screen.width < 800) {
window.location = "../mobile/index.php";
}
</script>
<?php
}
}
?>
I don't think <> is valid in PHP (it is in VB.NET ..) the is not operator is != or !== (strict/loose comparison).
Also you don't have to close if statements with a ;
This:
if (expr) {
}
Is valid and not this:
if (expr) {
};
I thought about writing != instead of <>.
You have a number of problems including bad variable case (i.e. variables not matching), checking for variables before they exist, etc. You can simply do something like this:
if (!empty($_GET['id'])) { // note I check for $_GET['id'] value here not $ShowDeskTop
$ShowDeskTop = $_GET['id'];
echo $ShowDeskTop; // note I change case here
if ($ShowDeskTop !== "f"){ // note the use of strict comparison operator here
echo "YES, the id doesn't = f";
echo "<script type=\"text/javascript\">";
echo "if (screen.width<800)";
echo "{";
echo "window.location=\"../mobile/index.php\"";
echo "}";
echo "</script>";
} // note the removal of semicolon here it is not needed and is bad coding practice in PHP - this is basically just an empty line of code
} // removed semicolon here as well
Fist thing, you need ; at the end of echo $ShowDesktop
And, what does f mean in if ($ShowDeskTop <> "f"){
use strcmp() instead of <> operator.
Try
if(!strcmp($ShowDeskTop, "f")){
echo "YES, the id doesn't = f";
}
<?php
$ShowDeskTop = $_GET['id']; // assign before checking
if (isset($ShowDeskTop)){
//echo $ShowDeskTop;
if ($ShowDeskTop !== "f"){
echo "YES, the id doesn't = f";
echo "<script type='text/javascript'>";
echo "if (screen.width<800)";
echo "{";
echo "window.location.replace('../mobile/index.php');"; // assuming your path is correct
echo "}";
echo "</script>";
}
}
?>

How to replace whitespace in jquery to pass to php?

I'm trying to make some auto suggest stuff for an app. But i'm having some problems. I wrote this jquery code to detect when there is a change in the input:
function soletsgo(){
$('#theinput').keyup(function(){
value = $('#theinput').val();
if ( value.length > 2 ){
word = $('#theinput').val();
word.replace(/\s/g, "&nbsp");
$("#autodatathing").load("../pages/searchy.php?word="+word+"");
} else {
} }); }
And there is a PHP file (searchy.php) that processes some stuff:
<?php
$now = htmlentities($_GET['word']);
echo "<p>";
echo $now;
echo "</p>";
?>
But, when i put in a 'space' (known as 'whitespace') in the 'input', there is no result!
Could someone help?
You should do escape(word) in javascript code, then rawurldecode($_GET['word']) in php. Also if you have issues with utf8 encoding (i had in my past experience) you might consider using this function instead of rawurldecode.
You can just use:
function soletsgo(){
$('#theinput').keyup(function(){
value = $('#theinput').val();
if ( value.length > 2 ){
word = $('#theinput').val();
word.replace(" ", " ");
$("#autodatathing").load("../pages/searchy.php?word="+word+"");
} else {
}
});
}
You could also do it on the server side using:
<?php
$now = str_replace(" ", " ", htmlentities($_GET['word']));
echo "<p>";
echo $now;
echo "</p>";
?>

Detect session/cookie variable in wordpress to prevent access to documents

Hey guys, I've gotten as far as my code below, but I am trying to create an AJAX search form that is 'safe' on my wordpress blog, by detecting the session variable or a cookie or something
<?php
#session_start();
If (!array_key_exists(‘authed’, $_SESSION))
{
include ‘not_authed.inc’;
exit();
}
// go about your business.
?>
and i'm trying to add that to this:
<?php
function checkValues($value)
{
// Use this function on all those values where you want to check for both sql injection and cross site scripting
//Trim the value
$value = trim($value);
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Convert all <, > etc. to normal html and then strip these
$value = strtr($value,array_flip(get_html_translation_table(HTML_ENTITIES)));
// Strip HTML Tags
$value = strip_tags($value);
// Quote the value
$value = mysql_real_escape_string($value);
return $value;
}
mysql_connect ("mysql.*****.com", "****","$*****") or die (mysql_error());
mysql_select_db ("***********");
$term = checkValues($_REQUEST['val']);
$term = mysql_real_escape_string($term);
$sql = mysql_query("select * FROM patient_db WHERE id_number = '$term'");
if($row = mysql_fetch_array($sql)) {
echo "<img src=\"******\" class='leftfloat' border=0>";
echo '<p>';
echo '<br /> ID Number: ' .$row['id_number'];
echo '<br /> Name: ' .$row['Name'];
echo '<br /> Exp. Date: ' .$row['exp_date'];
echo '<br /> DOB: ' .$row['dob'];
echo '</p>';
//echo "<a href='******' title='Printer Friendly Version' alt='Printer Friendly Version'><img src=\"*****\" class='rightfloat' border=0 height=33 width=33></a>";
} else {
echo "<img src=\"*****\" height=50 width=50 class='leftfloat' border=0>";
print "<h1>USER ID <br/>NOT FOUND</h1><br />";
print "<strong>OOPS!! THIS COULD BE AN ERROR</strong><br />";
print "<br />";
print "<div>*****</div>";
}
?>
The problem you are going to have is that the AJAX request is a separate session / cookie as it is a completely different process not tied into to the browser.
So how do you go about authenticating someone? A Token of sorts. So you would create a hash, which would need to be stored in the database for the user, which can be regenerated upon login etc. Then you would use this token to validate that user and allow the AJAX submission to work.
Hopefully that gets the ball rolling for you. So in your AJAX push script you would just appened a variable to the GET or POST data called token and then check it on the receiving PHP script. There are other ways of doing it, this is just one that I know of :)

Need help in display members name when logged in using PHP?

for some r.eason I cant display a logged in users name when they are logged in? the code is below
<?php
if (isset($_SESSION['user_id'])) {
echo '<?php if (isset($_SESSION[\'first_name\'])) { echo ", {$_SESSION[\'first_name\']}!"; } ?>';
if ($_SESSION['user_level'] == 1) {
echo 'something else';
}
} else { echo 'something';
}
?>
Thanks every one but i solved it.
Ack! Just look at your code. Do you know what this line is doing?
echo '<?php if (isset($_SESSION[\'first_name\'])) { echo ", {$_SESSION[\'first_name\']}!"; } ?>';
That's so wrong I don't even know where to begin. Just try
echo $_SESSION['first_name'];
And see if that gets you closer to what you want ;)
Make sure you're also calling session_start() before trying to access the variables.
Change your code to:
<?php
session_start();
if (isset($_SESSION['user_id'])) {
if (isset($_SESSION['first_name'])) {
echo ", " . $_SESSION['first_name']} . '!';
if ($_SESSION['user_level'] == 1) {
echo 'something else';
}
} else {
echo 'something';
}
?>
This is not a valid PHP code. Single quote "'" are not pair up. The block ('{' and '}') are also not pairing up.
The most importantly, the code to show the first name is in a string so it will not be shown.
I think the code you are trying to write is:
<?php
if (isset($_SESSION['user_id'])) {
if (isset($_SESSION['first_name'])) {
echo ", {$_SESSION['first_name']}!";
}
if ($_SESSION['user_level'] == 1) {
echo 'something else';
}
} else {
echo 'something';
}
?&gtl
Is it?
Here are the list of possibilities of the mistakes and make sure that you have corrected them
1) have you set the cookie "first_name" using setcookie method...?
2) Then have u called the session_start() function so that the session variables can be called in that page??
3) Try echo $_SESSION['first_name']... i don understand why you have put the flower brackets coz i never have used them even once in my 15 php projects..

Categories