I'm looking for option to make install.php where user puts all needed data e.g. db host, db username, db pwd etc. Script must put it to php class called config.
public function __construct(){
$this->site_address = '';
$this->db_prefix = '';
$this->site_desc = '';
$this->site_title = '';
$this->hash = '';
$this->sidebar = false;
$this->db_host = '';
$this->db_name = '';
$this->db_pass = '';
$this->db_user = '';
$this->db_port = 3306;
$this->folder = NULL;
$this->mailserver = '';
$this->mailport = '';
$this->mailuser = '';
$this->mailpassword ='';
}
How to put data from form on install.php page to this class constructor?
I was thinking about getting content->find $this->db_host = and replace '' for '.$_POST['db_host'].' from form and then put content to file and save, but I don't know how exactly do that. Please help.
Simply add variable to your __construct()
public function __construct($site_address='',$db_prefix='',$site_desc='',$site_title='',$hash='',$sidebar=false){
$this->site_address = $site_address;
$this->db_prefix = $db_prefix;
$this->site_desc = $site_desc;
$this->site_title = $site_title;
$this->hash = $hash;
$this->sidebar = $sidebar;
// And so on
}
Then from your form you do a new yourAwesomeClassName('http://hello','$_POST['db_prefix']',...)
Don't forget few things:
Never trust user input
Sanitize/check all your data/inputed format before using them
Don't save passwords in plain text, at least hash them, better would be using a salt in addition to that of course.
Update according to comment
(The following may not be a good practice but I'm open to suggestions as this is part of my current work)
If you need to save your data I suggest you to have a generic file for example ...
Generic file
Source
class Database
{
/**
* Database host
* #var string Default: 'your-database-host'
*/
const DB_HOST = 'your-database-host';
/**
* Database name
* #var string Default: 'your-database-name'
*/
const DB_NAME = 'your-database-name';
// And so on
}
Then you need a function that writes your data
Write default data
Source
public static function writeDatabaseConfig($data)
{
if (is_array($data)) {
$root = static::getRoot();
$databaseFile = $root . 'App' . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . 'Database.php';
$currentFile = file_get_contents($databaseFile);
if (strpos($currentFile, 'your') !== false) {
$oldToNew = array(
'host' => 'your-database-host',
'name' => 'your-database-name',
);
foreach ($oldToNew as $key => $value) {
if (isset($data[$key])) {
$currentFile = str_replace($value, $data[$key], $currentFile);
}
}
if (file_put_contents($databaseFile, $currentFile)) {
return true;
}
return false;
}
return false;
}
return false;
}
At the end in your __construct() you only need to call writeDatabaseConfig() to write your data. Once done you can get your information by calling ConfigClass::DB_HOST for example ...
Related
Something may be wrong with my logic or the hosting server because when I tried it locally it works flawlessly!! however, when I upload it always execute the second statement no matter what the value of applicant_email_activated is??
It is driving me crazy please help!
<?php
// Santize the provided inputs
$applicant_email = filter_var(stripAndCleanHTML($_GET['applicant_email']), FILTER_SANITIZE_EMAIL); # santize the email
$applicant_token = stripAndCleanHTML($_GET['applicant_token']); # santize the token
/**************** Find the applicant that has the same email *******************/
$database_connection = Database::database_connect();
$find_email_query = $database_connection->prepare('SELECT * FROM applicants WHERE applicant_email = :applicant_email && applicant_token = :applicant_token LIMIT 1');
$find_email_query->execute(['applicant_email' => $applicant_email, 'applicant_token' => $applicant_token]);
if ($find_email_query->errorCode() > 0) {
if (DEBUG === true) {
echo 'There was an issue in searching for the email Big Boss: <br>';
print_r($find_email_query->errorInfo());
die();
} else {
header('location:../404.shtml', true, 404);
die();
}
}
$applicants = $find_email_query->fetchAll();
foreach ($applicants as $applicant) {
$applicant_username = (string) stripAndCleanHTML($applicant['applicant_username']);
$applicant_password = (string) stripAndCleanHTML($applicant['applicant_password']);
$applicant_name = (string) stripAndCleanHTML($applicant['applicant_name']);
$applicant_phone = (string) stripAndCleanHTML($applicant['applicant_phone']);
$applicant_birthdate = (string) stripAndCleanHTML($applicant['applicant_birthdate']);
$applicant_city = (string) stripAndCleanHTML($applicant['applicant_city']);
$applicant_country = (string) stripAndCleanHTML($applicant['applicant_country']);
$applicant_major = (string) stripAndCleanHTML($applicant['applicant_major']);
$applicant_major_type = (string) stripAndCleanHTML($applicant['applicant_major_type']);
$applicant_exp_years = (string) stripAndCleanHTML($applicant['applicant_exp_years']);
$applicant_cv = (string) stripAndCleanHTML($applicant['applicant_cv']);
$applicant_email_activated = (int) stripAndCleanHTML($applicant['applicant_email_activated']);
}
if ($applicant_email_activated === 1) {
include '../../includes/job_app/email_has_been_activated.inc.php';
} elseif ($applicant_email_activated === 0) {
include '../../includes/job_app/email_confirmed.php';
}
?>
this is the function I used to clean the value:
function stripAndCleanHTML($to_clean)
{
return htmlspecialchars(strip_tags(stripslashes(trim($to_clean))));
}
and this is the Database class:
class Database
{
private const DB_HOST = 'domain.com';
private const DB_NAME = 'ats';
private const DB_CHARSET = 'utf8';
private const DB_USER = 'public_user';
private const DB_PASS = '1F#kaH$!q5r2as';
public static function database_connect()
{
try {
// setting DSN (Data Source Name)
$dsn = 'mysql:host=' . Database::DB_HOST . ';' . 'dbname=' . Database::DB_NAME . ';' . 'charset=' . Database::DB_CHARSET;
// creating a PDO (PHP Data Object) instance
$pdo = new PDO($dsn, Database::DB_USER, Database::DB_PASS);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
} catch (Exception $e) {
if (DEBUG === true) {
echo $e->getMessage().'<br>';
die();
} else {
die();
}
}
return $db_info;
}
}
It did work after I removed the (int) and put the compersion numbers into single quotes!! crazy right!!?
I guess the server on the hosting company handles PHP in a peculiar manner!! or maybe I have pumped up the app with a lot of stripping non-sense as some of you would agree, nonetheless, I have done it and I could go home and sleep knowing my baby app is safe and sound!
A huge thank you for the tips and mentoring, have a good day! and do not forget to be awesome.
I have a PHP class that highlights names mentioned in a text as links.It can search for #character in a given text and check the names that follow that character.
Theproblem is that the return value from class does not get printed out when I echo the method (public function process_text ($text_txt){}) that is responsible for processing the text. But when I change the return language construct to print or echo, then the parsing is successful and the processed string is printed out. I need to return and not print so as to be able to store the return string in a comments table of my CMS.
Kindly see full code below and advise:
class mentions {
public $print_content = '';
private $m_names = array();
private $m_denied_chars = array(
"#",
"#",
"?",
"¿"
);
private $m_link = "http://example.com/"; // + name of the username, link or whatever
/*
* this class can also be used for specific links
* start editing from here
* */
public function add_name ($name) {
array_push($this->m_names, $name);
}
public function process_text ($text_txt) {
$expl_text = explode(" ", $text_txt);
/*
* a character will be ignores which can be specified next this comment
* :)
* */
$sp_sign = "#"; // this is what you can change freely...
for ($i = 0; $i < count($expl_text); ++$i) {
$spec_w = $expl_text[$i];
$print_link = false;
$name_link = "";
if ($spec_w[0] == $sp_sign) { // then can be a mention...
$name = "";
$break_b = false;
for ($x = 1; $x < strlen($spec_w); ++$x) {
if ($spec_w[$x] == '.' || $spec_w[$x] == ",") {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
break;
}
}
if (in_array($spec_w[$x], $this->m_denied_chars)) {
$break_b = true;
break;
}
$name .= $spec_w[$x];
}
if ($break_b == true) {
$print_link = false;
break;
} else {
if (in_array($name, $this->m_names)) {
$print_link = true;
$name_link = $name;
}
}
}
if ($print_link == true) {
$this->print_content = "".$spec_w."";
if ($i < count($expl_text)) $this->print_content .= " ";
} else {
$this->print_content = $spec_w;
if ($i < count($expl_text)) $this->print_content .= " ";
}
return $this->print_content;
}
}
}
###### create new class object and process raw data ######
$mentions = new mentions;
$raw_data = 'Hello, #Angelina. I am #Bob_Marley.';
$expr = '#(?:^|\W)#([\w-]+)#i';
preg_match_all($expr, $raw_data, $results);
if( !empty($results[1]) ) {
foreach( $results[1] as $user ) {
$mentions->add_name($user);
}
/*
------------------------------------
*/
$commenData = $mentions->process_text($raw_data);
echo $commenData;
}
answer by #Terminus. If you have a return inside of a loop, the loop (and the entire function) will be interrupted and the value being returned will immediately be returned. That's just how it works. Was trying to write that as a good answer but couldn't. Did end up rewriting your class a bit. ideone.com/vaV0d2 note that i left in a test var_dump and that the output provided by ideone doesn't allow link tags to be displayed as html but if you run it from a server, it'll be correct
I'm trying to figure out why the code below won't persist my $_SESSION['objSession'] object across pages unless i keep the serialize/unserialize in place below. I get tired of manually serializing/unserializing to make object changes in the session and people keep saying i shouldn't have to do it but i do see other complaints about session objects not persisting without it on the web including here on stack... PHP 5.3 Apache 2.2 Windows 2008.
<?php require_once("/php/php_clsSession.php");?>
<?php session_start(); ?>
<?php
// Session Object Create/Log
$objSession = new clsSession;
if ( !(isset($_SESSION['objSession']) )) {
// This line will populate some properties in the obj
// like Session_ID and Create_dt
$objSession->CreateSession(session_id(),$_SERVER);
}
else {
// this code will only run if the session is already
// set
$objSession = unserialize($_SESSION['objSession']);
$objSession->UpdateSession(session_id(),$_SERVER);
}
// Update Session Object
$_SESSION['objSession'] = serialize($objSession);
unset($objSession);
?>
---- clsSession Below this line... you can ignore the db include as the code has the same problem without using the db functionality and i have the db function temporarily commented anyhow....
<?php
// -----------------------------------------------------------------
// Program Type: Class
// Program Name: clsSession
// Program Date: 01/08/2012 Programmer: Tim Wiley
// Description: Standard class for session creation/update
// -----------------------------------------------------------------
class clsSession {
// Properties
public $Session_Id = null;
public $Creation_Dt = null;
public $Action_Dt = null;
public $Session_IP_Address = null;
public $Browser_Type = null;
public $Display_Resolution = null;
public $Is_Https_Ind = null;
public $Is_Logged_In_Ind = 0;
public $User_Key = null;
public $User_Id = null;
public $Email_Address = null;
public $Request_Method = null;
public $Page_Requested = null;
public $Page_Request_Params = null;
public $Page_Action = null;
public $Login_Attempts = 0;
public $Max_Login_Attempts = 3;
private function UpdateSessionClassData (&$xSessionId = null, &$xSessionObj = null, &$xPageAction = "N/A" ) {
$this->Session_Id = &$xSessionId;
$this->Action_Dt = date( 'Y-m-d H:i:s', time( ));
$this->Session_IP_Address = substr(trim(&$xSessionObj['REMOTE_ADDR']),0,24);
$this->Browser_Type = substr(trim(&$xSessionObj['HTTP_USER_AGENT']),0,140);
$this->Request_Method = substr(trim(&$xSessionObj['REQUEST_METHOD']),0,24);
$this->Page_Requested = substr(trim(&$xSessionObj['SCRIPT_NAME']),0,140);
$this->Page_Request_Params = substr(trim(&$xSessionObj['QUERY_STRING']),0,140);
$this->Is_Https_Ind = &$xSessionObj['SERVER_PORT'] == 443 ? 1 : 0;
if (is_null($this->Display_Resolution)) {
require_once('/javascript/js_SaveScreenResolutionInCookie.js');
$this->Display_Resolution = !( IS_NULL( $_COOKIE['users_resolution'] )) ? substr(trim($_COOKIE['users_resolution']),0,16) : "N/A";
}
$this->Page_Action = substr(trim(&$xPageAction),0,32);
}
// Initialize Session objSession for $_SESSION
public function CreateSession($xSessionId = null, &$xSessionObj = null ) {
$this->Creation_Dt = date( 'Y-m-d H:i:s', time( ));
$this->UpdateSessionClassData(&$xSessionId, &$xSessionObj);
// $this->WriteSessionToDb();
}
// Update Session objSession for $_SESSION
public function UpdateSession($xSessionId = null, &$xSessionObj = null, $xPageAction = "N/A" ) {
$this->UpdateSessionClassData(&$xSessionId, &$xSessionObj, &$xPageAction);
// $this->WriteSessionActivityToDb();
}
// Writes the session data to database
public function WriteSessionToDb($xUserType = "Web") {
$objConnect = new clsDb;
$objDb = $objConnect->GetDbConnection($xUserType);
//$objDb = $this->GetDbConnection($xUserType);
$_InsertSQL = new PDOStatement;
$_InsertSQL = $objDb->prepare("INSERT INTO T_SESSION_STATS(" .
"F_ACTION_DT, F_SESSION_ID, F_SESSION_IP_ADDRESS, F_BROWSER_TYPE," .
"F_DISPLAY_RESOLUTION, F_PAGE_REQUESTED, F_PAGE_REQUEST_PARAMS," .
"F_REQUEST_METHOD, F_IS_HTTPS_IND, F_IS_LOGGED_IN_IND, F_USER_KEY)" .
"Values (?,?,?,?,?,?,?,?,?,?,?)");
$_InsertSQL->bindParam(1, $this->Action_Dt );
$_InsertSQL->bindParam(2, $this->Session_Id );
$_InsertSQL->bindParam(3, $this->Session_IP_Address );
$_InsertSQL->bindParam(4, $this->Browser_Type );
$_InsertSQL->bindParam(5, $this->Display_Resolution );
$_InsertSQL->bindParam(6, $this->Page_Requested );
$_InsertSQL->bindParam(7, $this->Page_Request_Params );
$_InsertSQL->bindParam(8, $this->Request_Method );
$_InsertSQL->bindParam(9, $this->Is_Https_Ind );
$_InsertSQL->bindParam(10, $this->Is_Logged_In_Ind );
$_InsertSQL->bindParam(11, $this->User_Key );
try {
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$objDb->beginTransaction();
$_InsertSQL->execute();
$objDb->commit();
unset($objDb);
} catch (Exception $e) {
$objDb->rollBack();
echo "Failed: " . $e->getMessage();
unset($objDb);
unset($objConnect);
}
}
// Writes the session data to database
public function WriteSessionActivityToDb($xUserType = "Web",$xPageAction = "N/A") {
$objConnect = new clsDb;
$objDb = $objConnect->GetDbConnection($xUserType);
//$objDb = $this->GetDbConnection($xUserType);
$_InsertSQL = new PDOStatement;
$_InsertSQL = $objDb->prepare("INSERT INTO T_SESSION_ACTIVITIES(" .
"F_ACTION_DT, F_SESSION_ID, F_SESSION_IP_ADDRESS, " .
"F_PAGE_REQUESTED, F_PAGE_REQUEST_PARAMS," .
"F_REQUEST_METHOD, F_PAGE_ACTION, F_IS_HTTPS_IND, F_IS_LOGGED_IN_IND, F_USER_KEY)" .
"Values (?,?,?,?,?,?,?,?,?,?)");
$_InsertSQL->bindParam(1, $this->Action_Dt );
$_InsertSQL->bindParam(2, $this->Session_Id );
$_InsertSQL->bindParam(3, $this->Session_IP_Address );
$_InsertSQL->bindParam(4, $this->Page_Requested );
$_InsertSQL->bindParam(5, $this->Page_Request_Params );
$_InsertSQL->bindParam(6, $this->Request_Method );
$_InsertSQL->bindParam(7, substr(trim($xPageAction),0,32));
$_InsertSQL->bindParam(8, $this->Is_Https_Ind );
$_InsertSQL->bindParam(9, $this->Is_Logged_In_Ind );
$_InsertSQL->bindParam(10, $this->User_Key );
try {
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$objDb->beginTransaction();
$_InsertSQL->execute();
$objDb->commit();
unset($objDb);
unset($objConnect);
} catch (Exception $e) {
$objDb->rollBack();
unset($objDb);
echo "Failed: " . $e->getMessage();
}
}
}
?>
The issue seems to be in your clsSession class. This is using &. Since the session object is serialized these references aren't stored correctly. Try removing these (i.e. change UpdateSessionClassData and UpdateSession to remove the & from parameters) and see if this sorts the issue.
to start, put session_start(); before require_once and add var_dump($_SESSION) for debug.
I have an extension that displays a basic user profile derived from the Yii widget class. My extension is defined as follows:
class BasicProfile extends CWidget
{
public $user_id;
private $userinfo = array();
private $userdetail = array();
private $availibility = array();
private $availabletime = array();
private $usereducation = array();
private $userlanguages = array();
private $userlivingplace = array();
public function init()
{
$this->userinfo = $users = Users::model()->findByPk($this->user_id);
$this->userdetail = $users->profile;
$this->availibility = $users->user_availibility;
$this->availabletime = $users->user_availabletime;
$this->usereducation = $users->user_education;
$this->userlanguages = $users->user_languagues;
$this->userlivingplace = $users->user_livingplaces;
}
public function run() {
$this->getUserDetail();
}
public function getUserDetail(){
$basic = $this->userinfo;
$detail = $this->userdetail;
$availibility = $this->availibility;
$availabletime = $this->availabletime;
$usereducation = $this->usereducation;
$userlanguages = $this->userlanguages;
$userlivingplaces = $this->userlivingplace;
$age = getAge(strtotime($detail['date_of_birth']));
$is_smoker = isSmoker($detail['is_smoker']);
$education = '';
foreach ($usereducation as $ue)
{
$e = $ue->educ;
$education .= $e['edu_name']. ', ';
}
$education = substr($education, 0, -2);
$languages = '';
foreach ($userlanguages as $ul)
{
$l = $ul->lang;
$languages .= $l['language_title']. ', ';
}
$languages = substr($languages, 0, -2);
$condition = array('where_condition'=>'up.user_id=:id AND up.is_currently_own=:own', 'where_data'=>array(':id'=>(int)$this->user_id, ':own'=>'Yes'));
$user_pets = Users::model()->getUserPets($condition);
$profile_images = UserProfileImages::model()->getProfileImages( array('select'=>'all'), $this->user_id );
foreach( $profile_images as $profile_img ) {
$images[] = $profile_img->profile_image;
}
$image = '';
if( $images ){
$main_image = HTTP_HOST . PROFILE_IMAGES_THUMB . $images[0];
$image = '<img src="'. $main_image .'" />';
}
$address1 = $basic['address1'];
if($basic['address2'] != "")
$address1 .= ", ".$basic['address2'];
$address2 = $basic['city']." ".$basic['state'].", ". $basic['zip'];
$editprofile = url('/users/account');
$editimglink = url('/images/icons/Modify.png');
}
}
My goal is to simply call this extension in my view as follwos:
$this->widget('ext.UserProfile.BasicProfile',array('user_id'=>$user_id));
However, I'm wondering if my extension is the proper place to encapsulate the image rotator? Should the rotator be included in the extension, or as part of the view? Should a generic JQuery image rotator be used, or is there one that plays well with Yii Framework?
I like to use JQuery.Cycle as my image rotator. I suggest that you build an extension with assets to keep the code in one place. you can however put your css in your theme folder and build a basic css in your extension to keep it clean like the basic pager of yii.
You could call your widget like this:
$this->widget("application.extensions.rotator", array("images" => array("/path/to/image/1", "/path/to/image/2"), "prevBtn" => "/path/to/prev/button");
Class to display different views for my blog.
class SB_Display {
public function __contruct() {
include_once('settings/db.settings.php');
$mysqli = new mysqli($SB_dbsettings['host'],$SB_dbsettings['user'],$SB_dbsettings['pass'],$SB_dbsettings['dbname']);
}
private function List_Display() {
$VIEW = '';
include_once('views/list.html.view.php');
$sql = "SELECT * FROM sb_posts ORDER BY ID DESC LIMIT '$SETTINGS->maxposts'";
$sql = $mysqli->real_escape_string($sql);
$res = $mysqli->mysqli_query($sql);
if($res->numrows > 0) {
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
foreach($row as $key => $value) {
$BLOG->$key = $value;
$VIEW .= $HTML;
}
}
} else {
$VIEW .= 'No Posts To Display';
}
return $VIEW;
}
private function Single_Display($id) {
$VIEW = '';
include_once('views/single.html.view.php');
$sql = "SELECT * FROM sb_posts WHERE BID = '$id'";
$sql = $mysqli->real_escape_string($sql);
$res = $mysqli->mysqli_query($sql);
$row = $res->fetch_assoc();
foreach($row as $key => $value) {
$BLOG->$key = $value;
}
$VIEW .= $HTML;
return $VIEW;
}
private function Create_Display() {
include_once('views/create.html.view.php');
return $HTML;
}
private function Edit_Display($id) {
$VIEW = '';
$sql = "SELECT * FROM sb_posts WHERE BID = '$id'";
$sql = $mysqli->real_escape_string($sql);
$res = $mysqli->mysqli_query($sql);
$row = $res->fetch_assoc();
foreach($row as $key => $value) {
$BLOG->$key = $value;
}
$BLOG->id = $id;
$VIEW .= $HTML;
return $VIEW;
}
public function SB_Get_Display($type,$id) {
switch($type) {
case 'list':
$this->content = List_Display();
return $this;
break;
case 'single':
$this->content = Single_Display($id);
return $this;
break;
case 'create':
$this->content = Create_Display();
return $this;
break;
case 'edit':
$this->content = Edit_display($id);
return $this;
break;
}
}
}
When using this class in the following manner ..
$BODY = new SB_Display();
$BODY->SB_Get_Display('list','');
I get this error:
Fatal error: Call to undefined function List_Display()
I can't figure out why. Any help would be greatly appreciated.
You need to use $this->function() instead of function() to call a method.
On a side-note, your constructor function name is incorrect. It's __contruct() but needs to be __construct() to be used as a constructor. Besides that, your indentation is horrible and makes the code hard to read.
I agree with #Corbin, that's a very bad idea. Also, personally, I love the autoload classes approach.
Some might say it's sloppy and the easy way out, but it forces you to really think about your classnames and directories, plus you avoid problems when you're renaming files/ classes. In your case you'd have to search for all files trying to include it and rename everything manually.
"my" approach: create a inc.php or something in the root of your site, and put this in it:
PHP
//autoload classes
function __autoload($class_name){
set_include_path(get_include_path().PATH_SEPARATOR.'/usr/share/file/'); //also
//include magic file location
// put the path to your class files here
$path = $_SERVER['DOCUMENT_ROOT'].'/lib/classes/';
// tell PHP to scan the default include path AND your include path
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
// name your classes and filenames with underscores, i.e., Net_Whois stored in
//Net_Whois.php
$classfile = str_replace("_", DIRECTORY_SEPARATOR, $class_name) . ".php";
require_once($classfile);
}
just initialise your db connections in the inc.php file as well and you can access them pretty much anywhere.
now just include the inc.php file in every new class you create, and you never have to look back again( depending on the project ofcourse)