PHP How to validate URL with id ungiven parameter? - php

I have a website where I can show a single post with view_post.php?id=1 but when I try to show a post with for example view_post.php?id= or view_post.php?id it shows nothing.
Then I tried to Log the Database Query like this:
$query = "SELECT * FROM posts WHERE id='$postIdFromUrl'";
$stmt = $db->query($query);
if (!$stmt) {
$_SESSION["test"] = $stmt;
redirect_to("Blog.php");
}
It doesnt show anything as the query is valid.
So my question is how to validate that. I tried a lot of things with e.g. URL Validation... nothing worked.
I would be very happy if someone could send me a code that can check for that.
Thanks very much in advance!

just check if id exists or its empty before u do anything
if (isset($_GET['id']) && !empty($_GET['id'])) {
//do your original code
} else {
redirect_to("Blog.php");
}

Related

I have a trouble in the Log-in procedure of my website

I having a difficulty on Log-in procedure. The username & password are both correct based on the database. The name of the fields on the database are also correct. I'm using PDO. When I click the log-in, I'm always redirecting to the else bracket. Please help me,thank you.
<?php
session_start();
include 'config.php';
if ($_POST) {
$user = $_POST['user'];
$pass = md5($_POST['pass']);
$query = "SELECT * FROM useraccounts WHERE USER_NAME=? AND USER_PASSWORD=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$user);
$stmt -> bindParam(2,$pass);
$stmt -> execute();
$num = $stmt->rowCount();
if ($num>0) {
session_start();
$_SESSION['user']=$user;
$_SESSION['active']=true;
header('location:frontpage.php'); //Must be the destination
echo "SUCCESS";
}
else{
header('location:login.php'); // <-- I'm always directing here
echo "FAILED";
}
}
else{
header('location:login.php');
echo "FAILED";
}
If you are getting redirected to the login.php page, please keep in mind the following:
1) Unless you access that page with a POST request, you will always get the login.page. You have an if statement that looks like this:
if ($_POST) {
So if you access the page directly from the browser, you are redirected straight to the login.php page.
2) If you are getting redirected from the second else statement like you stated with your comment "<-- I'm always directing here" then your query is not returning any result. Your query looks fine. So check the credentials you are passing. Make sure it matches that of the database.
Is your html form using POST or GET in the method attribute. it should be using POST otherwise your database checking code will not be run

i want to code if data allready exist in my database

i Just want code for if veriable $absolute_url value is already exist in mysql then show me a message i just want this Thank you..
$_SESSION['varname'] = $absolute_url;
$mailingwork = mysql_connect("localhost","root","");
mysql_select_db("inbox",$mailingwork);
if(isset($absolute_url) && !empty($absolute_url))
{
mysql_query("Insert Into deliveredinbox(mailerss) value('$absolute_url')");
}
I think you just want to check if the $absolute_url already exists in the deliveredinbox table. If so, you can do a select query as follows to count the number of rows where the absolute url is equal to the url that you want to enter to the table.
if(isset($absolute_url) && !empty($absolute_url)){
$count=mysql_query("SELECT count(*) from deliveredinbox where mailerss='$absolute_url'");
mysqli_fetch_array($count);
if($count[0]>0){
//already exists
echo "The url already exists";
}
else{
mysql_query("Insert Into deliveredinbox(mailerss) value('$absolute_url')");
}
}
Try if (isset($absolute_url)) { your code here; }. It's not precisely the right tool, but I think that it will do the trick for you.
http://php.net/manual/en/function.isset.php.
Others are absolutely right about transitioning from old mysql calls in PHP. mysqli calls are more secure. PDO will save you time in coding and are even more secure.

Can't seem to get query to work?

<?php
error_reporting(E_ALL);
session_start();
include ('connect.php');
if(!empty($_POST['budgetbox']))
{
$budgetboxvar = $_POST['budgetbox'];
$sql="INSERT INTO users WHERE username = '".$_SESSION['usernamebox']."'(budget) VALUES ('$budgetboxvar')";
mysqli_query($db,$sql);
}
?>
Does anyone have an idea why the code above doesn't work ? It seems like the code works if I leave the code below out. I'm sorry but I can't seem to figure out how this is not correct ? I'm not getting any error messages either.
When I take out the WHEN username is SESSION usernamebox part out.. the query does input into my database, only not in the field of a logged in user..
I tried to echo something if the query succeeded but it doesn't show anything either.. Which means the query can't be executed (I think). Can't figure out why though(it's hard being a noob sometimes)
Thank you in advance, hope you can help !
If I understand you correctly, something like this:
$sql = "UPDATE users SET budget='".$budgetboxvar."' WHERE username = '".$_SESSION['usernamebox'];
if(!empty($_POST['budgetbox']))
{
$query = $db->prepare("UPDATE users SET budget=? WHERE username=?"); ///statements voorbereiden
$budgetboxvar = $_POST['budgetbox'];
$name = $_SESSION['usernamebox']; //var toekennen
$query->bind_param("ss", $budgetboxvar, $name);
$query->execute();
echo"Thank you for entering your budget!";
}
And.. i changed the database column "budget" to VARCHAR64

Check for username availability php

<?php
$con = mysqli_connect('localhost','root','[mypassword]','dbhwsource');
if(isset($_GET['username'])){
$username = $con->real_escape_string($_GET['username']);
$test = $con->query("SELECT username FROM users WHERE username='$username'");
if($test!=false) die("usererror");
}
if(isset($_GET['email'])){
$email = $con->real_escape_string($_GET['email']);
$test = $con->query("select * from users where email='$email'");
if($test!=false) die("emailerror");
}
$con->close();
echo "ok";
?>
So I'm just trying to check to see if the username / email is available or not, but all i get is "usererror" no matter what the input username is! I'm just frustrated and have searched for sample code everywhere and the code looks like there's nothing wrong with it. What am I doing wrong?
EDIT:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
This worked!
Since your query returns true, this line if($test!=false) die("usererror"); gets executed,
should be something like
$test = $con->query("SELECT username FROM users WHERE username='$username'");
$row_cnt = $test->num_rows;
if( $row_cnt > 0 ) {
//you already have user with this name, do something
}
$con->query returns a result object if the query was successful. This doesn't say anything about how many rows where found or whether the query matched anything, it just means the query executed successfully. Therefore your $test!=false test always succeeds; only in the case of a database error would it fail.
Do the query as SELECT COUNT(*) FROM ..., then fetch the first row of the result and see if the count is > 0.
I recently did something like this for an android app. you should really check this site out. It helped me tremendously. This is a detailed example of having a PHP API for an aplication. Specifically logging in.
To be specific though, here is a snippet from the page for the PHP
/*
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
This worked for me:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
Your code is really not secure not optimized anybody can login with sql injection in your code.
and your code is right as you are checking thar (test != false) it means it is true that's why your code og usererror is executing
here is some tips and always use this style for security and optimization
do same for $email
third after running the query do not check if it is true or false but check again after query
if($test->username === $_GET['username']) { do something }
check sql injections on Google why i did this

FaceBook Registration Plugin Async Validate form (to check Username availbility)

Ok, So I have Google the hell out of this problem and the FB Advanced Registration documentation also did not help. I want to have a Facebook Registration where a user can choose(& Check availability of) his username like this:
(Screenshot of what I plan to do but have failed to do, since I cant post picturesin this question directly)
A link to Screenshot of what I wanted!
I plan to check the availability of the username from my DB in mysql using PHP, but I am stuck with this weird JSON callback thing which I have failed to understand.
My Registration Plugin looks something like this
<fb:registration
fields='[{"name":"name"},{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"
redirect-uri="http://mysite.com/loginFB.php"
fb_only="false"
width="530">
</fb:registration>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function validate_async(form, cb) {
// $.getJSON('https://graph.facebook.com/' + form.username + '?callback=?',//CODE obtained from FB documentation
$.getJSON('https://mysite.com/checkUsername.php?username=' + form.username + '?callback=?',
function(response) {
if (response.error== "false") {
// Username isn't taken, let the form submit
cb();
}
cb({username: 'That username is taken, Sorry!'});
});
}
</script>
I wanted to know WHAT EXACTLY do I write the in the checkUsername.php.
Right now I have come up with the following code for checkUsername.php which does NOT work:
<?php
$conn = dbconnect(GLOBAL_Db);
$username = $_GET['username'];
$data = array();
$table = mysql_real_escape_string(GLOBAL_Db. "." . GLOBAL_Users);
$sqlCommand = "SELECT * FROM ".$table." WHERE username='$username'";
$query = mysql_query($sqlCommand) or die (mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows>0){
$data['error'] = "true";
} else {
$data['error'] = "false";
}
echo json_encode($data);
?>
This code does not give me that that "The username is taken, Sorry" Message , WHY???
I would really appreciate it if anyone could actually help me out with this getJSON function in the script , AND Also help me out with the checkUsername.php since I have a very crude knowledge of JSON, (JSONP) etc. !
Would be glad to put in more effort to explaain my problem coz this is bugging me for like a Week now!
Happy to accept some valuable help from you guys!
$username = $_GET('username');
$_GET is not a function … maybe you should familiarize yourself with some PHP basics first?
Besides that, your script logic looks a bit weird …
if($num_rows>0){
$data['error'] = "true";
} else {
$data['username'] = $row['username'];
}
If now rows are found, then you want to access the username field in a row that’s not there?
(And you’re not even quoting the username you get as a GET parameter, OMG …)
Set error to true or false depending on if there are rows or none.
And then, in your JS function, give the „username is taken”-message if error=true.

Categories