I have file users.php and i want to display user's information when is set for example users.php?id=5
my "users.php" file is:
<?php
$page_title = "Administrace - Uživatelé";
require_once($_SERVER['DOCUMENT_ROOT']."/core/main.php");
if(!Admin::is_admin() or !User::is_logged()) // check if user is logged and is admin
{
redirect($url."index.php"); //get out of here
}
$user = new User();
if(isset($_GET["id"]))
{
$id = test_input($_GET["id"]); // = htmlspecialchars() & trim() & stripslashes()
$is_valid = ctype_digit($id);
if($is_valid && $user->check_user_available($id)) // check if $id is number AND if user with the $id is in database
{
// show user's information
} else {
// get out of here
redirect($url."admin/");
}
} else {
?>
<i>...toto je random text...</i>
<section>
<div class="content">
<h1>Administrace -> Uživatelé</h1>
<p>
<?php
echo ($user->get_all_users()); // get all users (User)
?>
</p>
</div>
</section>
<aside>
<?php
$login = new Panel("login");
$partneri = new Panel("partners");
?>
</aside>
<?php } require_once($_SERVER['DOCUMENT_ROOT']."/template/footer.php");?>
my check_user_availabe() function:
<?php
public function check_user_available($id)
{
$id = trim($id);
$id = stripslashes($id);
$id = htmlspecialchars($id);
if(ctype_digit($id))
{
$query = Database::dotaz('SELECT * FROM `users` WHERE `id`=?', array($id));
if($query > 0)
{
return true;
} else {
return false;
}
}
}
?>
I'm also using PDO prepared statements.. Here is my class database and function dotaz() (dotaz = query)
<?php
class Database {
// Databázové spojení
private static $connection;
// Výchozí nastavení ovladače
private static $nastaveni = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_EMULATE_PREPARES => false,
);
// Připojí se k databázi pomocí daných údajů
public static function connect($host, $username, $password, $dbname) {
if (!isset(self::$connection)) {
self::$connection = #new PDO(
"mysql:host=$host;dbname=$dbname",
$username,
$password,
self::$nastaveni
);
}
}
public static function dotaz($dotaz, $parametry = array()) {
$navrat = self::$connection->prepare($dotaz);
$navrat->execute($parametry);
return $navrat->rowCount();
}?>
Could you say me if the $_GET part is well-secured or help me to secure it better ? Thank you all
Related
I'm using Eliza Witkowska's Ajax Auto Refresh code: http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii
I've altered the code so I can pass variables from the url. It all works great except for one line of code. The line of code is part of a database query that checks for new records. When I try to pass my variables into the query the auto refresh stops working (all other functionality continues to work). If I use static values it works fine.
static values (this works)
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID=3 AND UserID=25');
with variables (this doesn't work)
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
There are no problems passing variables into another function in the same script. So I'm stuck and have been for a few days. Any help with be appreciated.
db.php
class db{
/**
* db
*
* #var $ public $db;
*/
public $db;
function __construct(){
$this->db_connect('###SERVER###','###USERNAME###','###PASSWORD###','###DATABASE###'); //my database information
}
function db_connect($host,$user,$pass,$database){
$this->db = new mysqli($host, $user, $pass, $database);
if($this->db->connect_errno > 0){
die('Unable to connect to database [' . $this->db->connect_error . ']');
}
}
//////////////////////////////
//This is the function that is having an issue when I pass it variables
//////////////////////////////
function check_changes(){
global $UserID; //Declaring my variable
global $AgentID; //Declaring my variable
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
if($result = $result->fetch_object()){
return $result->counting;
}
return 0;
}
//////////////////////////////
//This function has no problem, even when I pass it variables
//////////////////////////////
function get_news(){
global $UserID;
global $AgentID;
if($result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
if ($r->ChatType==1) { //ChatType is a field in the table that distinguishes Agent texts from User Texts
$return .= ''.htmlspecialchars($r->title).'';
} else {
$return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
}
}
return $return;
}
}
}
Here are the other files:
index.php
<?php
$AgentID = $_REQUEST["AgentID"]; //Grabing AgentID from the URL
$UserID = $_REQUEST["UserID"]; //Grabing UserID from the URL
require('common.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin</title>
<script src="jquery-1.10.2.min.js"></script>
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php?AgentID=<? echo $AgentID; ?>&UserID=<? echo $UserID; ?>', //This line has been updated by passing parameters
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* update counter */
$('#message-list').data('counter',response.current);
/* check if with response we got a new update */
if(response.update==true){
$('#message-list').html(response.news);
var audio = new Audio('img/solemn.mp3');
audio.play();
}
});
}
//Every 2 sec check if there is new update
setInterval(check,2000);
</script>
<style>
body {
margin:0px;
padding:0px;
vertical-align:top;
}
</style>
</head>
<body>
<?php /* Our message container. data-counter should contain initial value of counter from database */ ?>
<br>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
<?php echo $db->get_news();?>
</div>
</body>
</html>
checker.php
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
$AgentID = $_REQUEST["AgentID"]; //passing my variable to db.php
$UserID = $_REQUEST["UserID"]; //passing my variable to db.php
$data['news'] = $db->get_news();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
?>
common.php
<?php
require_once ('db.php'); //get our database class
$db = new db();
/* end of file common.php */
?>
I think the problem was that the variables were not available at the time of including the database connection in checker.php ~ declare the variables and then include the db connection.
Also, I'd suggest that instead of using the global expression to define the variables within your db class methods that you pass them as parameters instead. I hope the following might be of use - it's not tested though. There are, or should be, concerns with this method of using variables within sql - it is vulnerable to the dreaded sql injection ~ better would be to use prepared statements within the db class and bind the $agentID and $UserID with the bind_param() method.
<?php
/* common.php */
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpwd = 'xxx';
$dbname = 'xxx';
require_once 'db.php';
$db = new db( $dbhost, $dbuser, $dbpwd, $dbname );
?>
<?php
/* database class: db.php */
class db{
private $db;
public function __construct( $dbhost, $dbuser, $dbpwd, $dbname ){
$this->db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
if( $this->db->connect_errno > 0 ) exit('Unable to connect to database [' . $this->db->connect_error . ']');
}
public function check_changes( $AgentID=false, $UserID=false ){
if( $AgentID && $UserID ){
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
if($result = $result->fetch_object()){
return $result->counting;
}
}
return 0;
}
public function get_news( $AgentID, $UserID ){
$return = '';
if( $AgentID && $UserID ){
if( $result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50' ) ){
while( $r = $result->fetch_object() ){
if ($r->ChatType==1) {
$return .= ''.htmlspecialchars($r->title).'';
} else {
$return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
}
}
}
return $return;
}
}
}
?>
<?php
/* Checker.php */
$AgentID = isset( $_REQUEST["AgentID"] ) ? $_REQUEST["AgentID"] : false;
$UserID = isset( $_REQUEST["UserID"] ) ? $_REQUEST["UserID"] : false;
if( $AgentID && $UserID ){
/* Do SOME filtering of user supplied data */
$AgentID=filter_var( $AgentID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
$UserID=filter_var( $UserID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
require 'common.php';
$data['current'] = (int)$db->check_changes( $AgentID, $UserID );
$data['update'] = false;
if( isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current'] ){
$data['news'] = $db->get_news( $AgentID, $UserID );
$data['update'] = true;
}
echo json_encode($data);
}
?>
<?php
$AgentID = isset( $_REQUEST["AgentID"] ) ? $_REQUEST["AgentID"] : false;
$UserID = isset( $_REQUEST["UserID"] ) ? $_REQUEST["UserID"] : false;
$AgentID=filter_var( $AgentID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
$UserID=filter_var( $UserID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
require 'common.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin</title>
<script src="jquery-1.10.2.min.js"></script>
<script>
<?php
echo "
var aid={$AgentID};
var uid={$UserID};";
?>
function check(){
$.ajax({
type:'POST',
url:'checker.php?AgentID='+aid+'&UserID='+uid,
dataType:'json',
data:{ counter:$('#message-list').data('counter') }
}).done( function( response ) {
/* update counter */
$('#message-list').data('counter',response.current);
/* check if with response we got a new update */
if(response.update==true){
$('#message-list').html(response.news);
var audio = new Audio('img/solemn.mp3');
audio.play();
}
});
}
setInterval(check,2000);
</script>
<style>
body {
margin:0px;
padding:0px;
vertical-align:top;
}
</style>
</head>
<body>
<br>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes($AgentID, $UserID); ?>">
<?php echo $db->get_news($AgentID, $UserID);?>
</div>
</body>
</html>
I have problem in using SoapClient in php. Considering that it is my fist try in authenticating user credentials so I might have some basic mistakes in my code as well.
I have a simple html tags that takes user credentials(on client side) and sends them to a processing page (works in backend) and sends soap message to server page using __soapCall. Here is the code.
Please help with your suggestions
Client.php
<html>
<body>
<form method='POST' action='middle_client.php'>
<lable>User Name</lable><input type='text' name= 'user' id='user'>
<br>
<lable>Password</lable><input type='password' name= 'pass'>
<br>
<lable>Insurance Name</lable><input type='text' name= 'insurance'>
<br>
<input type='submit' name= 'submit'>
</form>
<body>
</html>
Middle_client.php
<?php
use \SoapClient;
if(isset($_POST['submit'])){
$name= $_POST['user'];
$password= $_POST['pass'];
$insurance= $_POST['insurance'];
$con=mysql_connect("localhost","root","");
// Check connection
if (!$con) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db($insurance, $con);
if (!$db_selected) {
die('Invalid query: ' . mysql_error());
}
if ($db_selected=='insurance'){
//header('Location:server.php');
}
}
class client{
function __construct(){
$parameters = array('location' => 'http://localhost/XXX/server.php',
"uri" => 'urn://localhost/XXX/',
'trace' => 1,
);
$this->instance = new SoapClient(NULL,$parameters);
$auth_parameter = new stdClass();
$auth_parameter->name = "ABC";
$auth_parameter->password = "root";
$header_param = new SoapVar($auth_parameter, SOAP_ENC_OBJECT);
$header = new SoapHeader('XXX', 'authenticate', $header_param, false);
$this->instance->__setSoapHeaders(array($header));
}
public function getname($array){
return $this->instance->__soapCall('testing', $array);
}
}
$client = new client();
$array = array ('P_name'=> 'Foo');
echo $result = $client->getname($array);
var_dump($client);
?>
and Server.php
<?php
class server{
private $con;
public function authenticate($header_param){
if ($header_param->name == 'ABC' && $header_param->password == 'root' ){
return true;
}
else throw new SOAPFault("Wrong Name/Password", 401);
}
public function __construct(){
$this->con = (is_null($this->con)) ? self::connect() : $this->con;
}
static function connect(){
$con=mysql_connect("localhost","root","insurance");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db = mysql_select_db("user", $con);
return $con;
}
public function testing($array){
$usernme = $array['P_name'];
$sql = "SELECT * from user where P_name=".$usernme;
$qry= mysql_query($sql,$this->con);
$result = mysql_fetch_array($qry);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
/return $returned_name= $result["P_name"];
}
}
$parameter = array("uri" => 'localhost/XXX/server.php');
$server = new SoapServer(NULL, $parameter);
$server-> setClass('server');
$server-> handle();
I have a MVC like store.
I wish to make a list of the most bought items (in this case prints, because it's a print store).
I'm finding it very hard specially because I'm very new to php / mysql and specially to this MVC structure... I hope this isn't a bad question.
I have a model.php like this :
<?php
class model {
private $conn;
function __construct() {
$server = "localhost";
$login = "root";
$pass = "";
$db = "printstore";
$conn = new mysqli($server, $login, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$this->conn = $conn;
}
}
function __destruct() {
$this->conn->close();
}
function buildArr($result) {
$arr = array();
while ($row = $result->fetch_assoc()) {
array_push($arr, $row);
}
return $arr;
}
}
a controller.php:
<?php
include 'model.php';
class Controller {
private $model;
function __construct() {
$this->model = new model();
}
function home() {
include 'views/home.php';
}
}
a index.php:
<?php
session_start();
include 'controller.php';
define("BASE_URL", 'http://' . $_SERVER['SERVER_NAME'] . '/printstore2/index.php/');
define("MAIN_BASE_URL", 'http://' . $_SERVER['SERVER_NAME'] . '/printstore2/');
$controller = new controller();
include 'views/templates/header.php';
if (isset($_SERVER['PATH_INFO'])) {
$url = explode("/", $_SERVER['PATH_INFO']);
$function_name = $url[1];
if (isset($url[1]) && $url[1] !== "") {
if (isset($url[2])) {
$controller->$function_name($url[2]);
} else {
$controller->$function_name();
}
} else {
$controller->home();
}
} else {
include 'views/home.php';
}
include 'views/templates/footer.php';
And the view where I want to post the "Best Selling Prints":
<div>
<h2>Top Prints</h2>
<ol>
<li>1st print most bought</li>
<li>2nd</li>
<li>3rd</li>
</ul>
Now, my database has a table called "print_for_sale" which has the print_id and the sale_id, where I can see how many of each prints has been bought.
How can I do this? I'm so lost!
I'm sorry for the long post.
Use COUNT and GROUP BY
to get a list of all prints vs their sale count:
SELECT fk_print_id as printId, COUNT(print_for_sale_id) as saleCount
FROM print_for_sale
GROUP BY fk_print_id
ORDER BY saleCount DESC
that is, if i understood your table right.
I've created a login class for my web app and it does work, but now I've created that infamous "keep me logged in" - checkbox and don't get it to work. Here's my class for login:
<?php
error_reporting(E_ALL ^ E_NOTICE);
class Login {
private $error;
private $connect;
private $email;
private $password;
public $row;
public function __construct(PDO $connect) {
$this->connect = $connect;
$this->error = array();
$this->row = $row;
}
public function doLogin() {
$this->email = htmlspecialchars($_POST['email']);
$this->password = htmlspecialchars($_POST['password']);
$this->rememberme = $_POST['rememberme'];
if($this->validateData()) {
$this->fetchInfo();
}
return count($this->error) ? 0 : 1;
}
public function validateData() {
if(empty($this->email) || empty($this->password)) {
$this->error[] = "Täyttämättömiä kenttiä";
} else {
return count($this->error) ? 0 : 1;
}
}
public function fetchInfo() {
$query = "SELECT * FROM users WHERE email = :email AND activation_token IS NULL";
$stmt = $this->connect->prepare($query);
$stmt->execute(array(
':email' => $this->email,
));
if($stmt->rowCount() == 0) {
$this->error[] = "Väärä käyttäjätunnus tai salasana";
return 0;
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['name'];
$_SESSION['profilepic'] = $row['profilepic'];
if(isset($this->rememberme)) {
setcookie("loggedin", "yes", time() + 25200);
}
}
if (Register::cryptPass($this->password) != $row['password']) {
$this->error[] = "Virheelliset kirjautumistiedot";
} else {
return true;
}
return count($this->error) ? 0 : 1;
}
public function displayErrors() {
if(!count($this->error)) return;
echo "<div class='login_error'>";
foreach($this->error as $key=>$value) {
echo "<p>".$value."</p>";
}
echo "</div>";
}
public function doLogout() {
session_destroy();
}
}
?>
And here's a small part of my code from my another file where I'm checking if the session or cookie is set:
<?php
if (isset($_SESSION['email']) || isset($_COOKIE['loggedin'])) {
?>
<div id="header_container_isloggedin">
<div class="container_12">
<header id="header">
<div class="grid-12">
<ul id="menu">
<li class="profile-name">
<a href="profile.php?id=<?php echo $_SESSION['user_id']; ?>">
<span class="header_username">
<img src="images/thumbnails/<?php echo $_SESSION['profilepic']; ?>"
class="profile_evensmaller"/>
<span class="header_name"><?php echo $_SESSION['name']; ?></span></span></a>
</li>
</ul>
<?php } ?>
The problem is that everytime the cookie is set, it doesn't display my profile picture or name since they've saved inside of $_SESSION variable. So how should I approach this and get this to work. I know that right now it's not the safest method, since I'm not generating any hashes for that cookie, but right now the only thing I'm interested in, is to get this one to work.
For some reason the return doesn't work when the check_em() succeeds. I'm new to php, so I'm at a loss here.
<?php
//Class to handle mysql
class db_handler {
private $db_host = 'localhost';
private $db_name = 'project';
private $db_user = 'project';
private $db_pass = 'dbpassword';
private $db_con_mysql = '';
private $db_con_db = '';
public function check_em($username, $password) {
$db_query = "SELECT password FROM user WHERE name='".$username."' LIMIT 1;";
if($this->db_con_mysql!='') {
$db_query_response = mysql_query($db_query) or die('Query failed: '.mysql_error());
$db_query_return = mysql_fetch_row($db_query_response);
$db_sha1_hash = $db_query_return[0];
echo $db_sha1_hash."<br>";
echo sha1($password)."<br>";
if(sha1($password)==$db_sha1_hash) {
return 'user valid'; //THIS DOESN'T WORK!?!?!?
} else {
return 'no good';
}
} else {
$this->db_connect();
$this->check_em($username, $password);
}
}
//Connect to mysql, then database
private function db_connect() {
$this->db_con_mysql = mysql_connect($this->db_host, $this->db_user, $this->db_pass) || die('Connection failed: '.mysql_error());
$this->db_con_db = mysql_select_db($this->db_name) || die('Could not use'.$this->db_name.'. '.mysql_error());
return;
}
//Disconnect from database and reset vars used to track connection.
private function db_disconnect() {
if($this->db_con_mysql!='') {
mysql_close();
$this->db_con_mysql = '';
$this->db_con_db = '';
return;
}
}
public function fake($some_val) {
if($some_val<6) {
return TRUE;
} else {
return FALSE;
}
}
}
$db_obj = new db_handler();
$val1 = $db_obj->check_em('someuser','password'); //should return 'user valid'
echo "val1:".$val1."<br>";
echo "<br><br>";
$val2 = $db_obj->check_em('someuser','passw0rd'); //should return 'no good'
echo "val2:".$val2."<br>";
echo "<br><br>";
echo "test<br>";
echo $db_obj->fake(4)."<br>";
?>
Results:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
val1:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
7c6a61c68ef8b9b6b061b28c348bc1ed7921cb53
val2:no good
test
1
This line needs a return:
return $this->check_em($username, $password);
But a more sensible solution would be to connect to the database inside the if when the connection is null. Really, the whole thing could be better written, but I'll leave it at that.
...
else {
$this->db_connect();
return $this->check_em($username, $password);
}
...
You want to add the return, so that if it fails, then it goes one level deeper and finds another. If that level deeper succeeds, it passes the value up to the level above, which can pass it up and up until it reaches the original function call.