I am sending data to a PHP script using an android app. The following is the PHP script.
telejoke.php:
<?php
include 'JokeValidation.php';
include 'DBConnect.php';
$username = $_POST['username'];
$joke = $_POST['joke'];
$dbname = 'Telejoke';
mysql_select_db($dbname);
if (validate()){
$query = "INSERT INTO jokes (username, joke) VALUES ('$username','$joke')";
mysql_query($query) or die('Error, insert query failed');
}
mysql_close($conn);
?>
jokevalidation.php:
<?php
include 'DBConnect.php';
$dbname = 'telejoke';
mysql_select_db($dbname);
function validate(){
if ($joke == null) return false;
else if($username == null) return false;
return true;
}
?>
For some reason, the PHP script will put the data into the database when I take out if ($joke == null) return false; and else if($username == null) return false;. But when I put these statements into the PHP code, it seems that validate returns false. This is weird because $username and $joke will go to my database when I take out these statements meaning they cannot be null!.
Help is appreciated. Thanks.
Your validate function needs to have access to the $joke and $username objects.
function validate($joke, $validate) {
if ($joke == null)
return false;
else if ($username == null)
return false;
return true;
}
You can also get access to these variables by using the following inside your validate method:
global $joke, $username
However, it is better to declare what you're validating rather than relying on those variables being declared and set elsewhere in your code. Using global might fail silently for other reasons.
Variables have function scope. The variables $joke and $username do not exist inside the function, because you have neither declared nor passed them into the function. Use function parameters:
function validate($joke, $username) {
...
}
if (validate($joke, $username)) {
...
}
function validate($joke,$username)
also, filter those postvars before inserting them into your db.
Related
Hey guys I have a question and I still consider myself pretty new at coding, so forgive me if I come off foolish.
I am studying in school as of now and we have a project to build a full stack recreation of craigslist. Any who the problem I am having deals with PHP. I have created an account page with text areas. I would like to echo out the user's information on their so the user can see what he put on and update as he likes. Since my navbar is included on every page, I added the code:
if(isset($_SESSION['logged_in_user'])){
var_dump($_SESSION['logged_in_user']);
$user = $_SESSION['logged_in_user'];
var_dump($user);
}
on my account page I figured I can echo it out as
<?= $attributes['first_name']?> within the placeholders. But I keep getting:
Undefined index: first_name
Also when I var_dump($user) I get an protected $attributes array.
In My Auth class is where I first defined $user as such:
public static function attempt($attemptedUsername, $attemptedPassword) {
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
and my findByUserName function is in the user class. the code is:
public static function findByUserName($user_name){
// Get connection to the database
self::dbConnect();
$stmt = self::$dbc->prepare('SELECT * FROM users WHERE user_name = :user_name');
$stmt->bindValue(':user_name', $user_name , PDO::PARAM_STR);
//execute gets its own line, t or false
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
// #TODO: Create select statement using prepared statements
// #TODO: Store the result in a variable named $result
// The following code will set the attributes on the calling object based on the result variable's contents
$instance = null;
if ($result) {
$instance = new static($result);
}
return $instance;
}
Your problem seems to be with not being able to access the variable $user outside of the static method attempt() this can be fixed by declaring the variable globally at the beginning of the method attempt() like this:
public static function attempt($attemptedUsername, $attemptedPassword) {
global $user;
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
More information can be found on this in the PHP documentation here.
I'm trying to learn about Object Oriented Programming and I want to turn this code into such. I've got some knowledge so far from google and here and in particular http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762.
The way I understand it is I need classes that contain a certain set of instructions that can be used with universal objects outside of those classes.
My idea so far has been to set up a User class where names are stored (coming from a HTML/PHP form).
class User {
public $nameStore, $fName, $lName, $email;
public function __construct ($fName, $lName, $email) {
$this->$fN = $fName;
$this->$lN = $lName;
$this->$eN = $email;
}
Like the above^. But I'm still confused about where other instructions of my code should go. That's where I need the most help. From what I've read, it hasn't helped me get the full grasp of what I need to do. If someone could help get me started in the right direction on how to make my code into an OOP type I would greatly appreciate it. Thanks!
Below is my procedural code that I want to convert to OOP.
<?php
session_start();
$formNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grantle.com';
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User-------------------------*/
function newUser($firstName,$lastName,$emailUser,$active,$conn){
//a function to insert a user into a database is here
}
//newUser function enters names in database
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors------------------------------*/
function errorCheck($formNames, $nameSplit, $fullname){
$isValid = false;
if (empty($fullname)) {
$_SESSION['error'][] = '<br><br> Error: Name Missing Here: '.$fullname.'<br><br>';
} elseif (empty($nameSplit[0])) {
$_SESSION['error'][] = '<br><br> Error: First Name Missing Here: '.$fullname.'<br><br>';
} elseif (empty($nameSplit[1])) {
$_SESSION['error'][] = '<br><br> Error: Last Name Missing Here: '.$fullname.'<br><br>';
} elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
$_SESSION['error'][] = '<br><br> Error: Illegal Character Found in: '.$fullname.'<br><br>';
} else {
$isValid = true;
}
return $isValid;
}
//errorCheck function tests for errors in names and stops them from being entered in the
//database if there are errors in the name. Allows good names to go through
/*-----------------------------End Function for Errors---------------------*/
/*--------------------------Function for Redirect--------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
//redirect function uses a javascript script to redirect user because headers have already been sent.
/*-----------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here//
// Initialize empty error array
$_SESSION['error'] = array();
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//I open the database here
//opens the database
if (errorCheck($formNames, $nameSplit, $fullname)) {
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);//do this BELOW only for names that have no errors
}//ends if of errorCheck
}//ends fullnames foreach
if (count($_SESSION['error']) == 0) {
redirect('viewAll.php');
} else {
redirect('form.php');
}
/*Redirects to viewAll page only once and as long as no errors have been found*/
Your
class User {
public $nameStore, $fName, $lName, $email;
public function __construct ($fName, $lName, $email) {
$this->$fN = $fName;
$this->$lN = $lName;
$this->$eN = $email;
}
I would break this up into more specific parts such as GET and SET for each value you are trying to store in the Class:
class User {
private $fName, $lName, $email;
public function set_firstname($fname){
$this->fName = $fname;
}
public function set_surname($lName){
$this->lName = $lName;
}
public function set_email($email){
$this->email = $email;
}
public function get_email(){
return $this->email;
}
public function get_fname(){
return $this->fName;
}
public function get_surname(){
return $this->lName;
}
Then when you create the class, you can add and return each value individually, rather than forcing yourself to do them all at once. This is more flexible. But you can also add the values at the creation of the class as well if you wish, using the __construct similar to what you had already:
public function __construct ($fName = null, $lName = null, $email = null) {
if(!empty($fName)){
$this->set_firstname($fName);
}
if(!empty($lName)){
$this->set_surname($lName);
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false){
$this->set_email($email);
}
}
What this does is for each non-empty value it runs the corresponding SET method. Also checking that the email value is valid before saving it. If no values are passed to the class then it doesn't save anything.
Your setting up of the class is incorrect, firstly you need to include the class file into the working PHP so at the top of your page add:
include "path/to/users.class.php";
And then initiate the class correctly:
$userClassInstance = new User($firstName,$lastName,$emailUser);
When the above line runs, you will then have a User object containing three variables referenced as $userClassInstance. you can do var_dump($userClassInstance);
Be careful as your code has newUser as one line and also has an incorrect number of variables in the construct statement. Generally all the functions in a page should be placed inside an appropriate class, so all your string management functions such as errorCheck() could be put into the Users class to check the values given before assigning them to the variables in the class.
Finally, to view the stored variables you would then do:
print $userClassInstance->get_fname(); //will outout the value of the class $fName
I'm trying to create a function in PHP that connects to SQL with the global $conn, and another which authenticates the user. However, referencing the SQL connection function in the second function isn't working.
Error:
Fatal error: Call to a member function query() on a non-object in /[...]/functions.php on line [see below]
SQLinfo.php contains valid database information, in the form of constants SQLurl, SQLuser, SQLpass & SQLdatabase.
Code:
function SQLconnect(){
require 'SQLinfo.php';
global $conn;
$conn = new mysqli(SQLurl,SQLuser,SQLpass,SQLdatabase);
if($conn->connect_error){
return $conn->connect_error;
}else{
return True;
}
}
function isauthenticated($username,$token){
if(empty($username) || empty($token)){
return False;
}else{
SQLconnect();
//error line:
$result = $conn->query("SELECT * FROM `userdata` WHERE `username` = '".$username."' AND `lastid` = '".$token."'");
if($result->num_rows == 1){
return True;
}else{
return False;
}
$result->free;
}
}
I tried looking at this answer, however since the mysql extension is deprecated and the global has been defined I couldn't figure it out. I'd appreciate any help.
hi I avec a php file (inc.db.php) which contains my config to connect to my db.
Into this file I have something like
$dbh = new PDO(DSN, USER, PASS);
In a other file I included inc.db.php and in one function I want to use the $dbh variable.
My function is :
function getPassword($utilisateur) {
$uid = addslashes( $utilisateur );
$sql = "SELECT password FROM cc_users WHERE uid='$uid'";
$sth = $dbh->query($sql);
$result = $sth->fetchAll();
if (count($result) == 1) {
return TRUE;
} else {
return FALSE;
}
}
I got an error
PHP Notice: Undefined variable: dbh in /....
How I can do to use the variale included in a external file?
From the PHP Manual:
Any variable used inside a function is by default limited to the local
function scope.
(...)
In PHP global variables must be declared global inside a function if
they are going to be used in that function.
(...)
A second way to access variables from the global scope is to use the
special PHP-defined $GLOBALS array.
You'll avoid the error changing the function to this:
function getPassword($utilisateur) {
global $dbh;
$uid = addslashes( $utilisateur );
$sql = "SELECT password FROM cc_users WHERE uid='$uid'";
$sth = $dbh->query($sql);
$result = $sth->fetchAll();
if (count($result) == 1) {
return TRUE;
} else {
return FALSE;
}
}
But the usage of global variables is considered a bad practice.
Also, using addslashes won't protect your query against SQL injection attacks.
Prepare the SQL statements or use the quote method.
Got an issue with a web app that I've inherited as a project and unfortunately I can't trace the error. It seems that the model isn't being loaded but I could be wrong. Any help would be great.
code is:
public function login()
{
//If request is post then user is trying to login, so process the login info
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//Run the model method ::login
$login_successful = $this->User->login();
// check login status
if($login_successful) {
// if YES, then move user to dashboard/index (btw this is a browser-redirection, not a rendered view!)
header('location: ' . URL . 'passwords/index');
} else {
echo "Incorrect user / pass combination entered. Please try again.";
}
}
}
and the model function is:
public function login() {
$username = $_POST['data']['User']['username'];
$password = $_POST['data']['User']['password'];
$bind = array(
":username" => "$username",
);
$result = $this->select("users", "username = :username", $bind);
//Check the password returned from the db against the password entered
if (Bcrypt::checkPassword($password, $result[0]['password']) == true) {
Session::init();
Session::set('user_logged_in', true);
Session::set('user_id', $result[0]['id']);
Session::set('user_name', $result[0]['username']);
Session::set('user_permission', $result[0]['permission']);
Session::set('user_role', $result[0]['role']);
return true;
} else {
return false;
}
}
also I've noticed that the controller and model both have a function called login.]
Thanks
The reason is $this->User is not a valid class instance.
Make sure that it is an object.
Try
var_dump($this->User);
die();
//Run the model method ::login
$login_successful = $this->User->login();
And you will see that there is no instance there.
What to do?
Find the place where you expect your model being initialized. Check, why it is not.