PHP - Help Setting Up Path Constants
I am following a book and need help setting up Path Constants.
Here is the script I need to adjust... // Constants define('BASE_URI', '/path/to/Web/parent/folder/'); define('BASE_URL', 'www.example.com'); define('MYSQL', '/path/to/mysql.inc.php'); Since I am working in NetBeans, I do not have access above my Project Folder which serves as my "Web Root". So if my Project Folder is called "MyProjectFolder", and I want both BASE_URI and BASE_URL to point to that directory on my laptop, what should I put? I'm thinking something like this... // Constants define('BASE_URI', '/'); define('BASE_URL', '/'); define('MYSQL', '/includes/mysql.inc.php'); TomTees Similar TutorialsHi! So I'm working for someone, and they want me to fix this error in a PHP file.. Here is the code: <?php include_once('config.php'); $online = mysql_query("SELECT * FROM bots WHERE status LIKE 'Online'"); $offline = mysql_query("SELECT * FROM bots WHERE status LIKE 'Offline'"); $dead = mysql_query("SELECT * FROM bots WHERE status LIKE 'Dead'"); $admintrue = mysql_query("SELECT * FROM bots WHERE admin LIKE 'True'"); $adminfalse = mysql_query("SELECT * FROM bots WHERE admin LIKE 'False'"); $windows8 = mysql_query("SELECT * FROM bots WHERE so LIKE '%8%'"); $windows7 = mysql_query("SELECT * FROM bots WHERE so LIKE '%7%'"); $windowsvista = mysql_query("SELECT * FROM bots WHERE so LIKE '%vista%'"); $windowsxp = mysql_query("SELECT * FROM bots WHERE so LIKE '%xp%'"); $unknown = mysql_query("SELECT * FROM bots WHERE so LIKE 'Unknown'"); $totalbots = mysql_num_rows(mysql_query("SELECT * FROM bots")); $onlinecount = 0; $offlinecount = 0; $deadcount = 0; $admintruecount = 0; $adminfalsecount = 0; $windows8count = 0; $windows7count = 0; $windowsvistacount = 0; $windowsxpcount = 0; $unknowncount = 0; while($row = mysql_fetch_array($online)){ $onlinecount++; } while($row = mysql_fetch_array($offline)){ $offlinecount++; } while($row = mysql_fetch_array($dead)){ $deadcount++; } while($row = mysql_fetch_array($admintrue)){ $admintruecount++; } while($row = mysql_fetch_array($adminfalse)){ $adminfalsecount++; } while($row = mysql_fetch_array($windows8)){ $windows8count++; } while($row = mysql_fetch_array($windows7)){ $windows7count++; } while($row = mysql_fetch_array($windowsvista)){ $windowsvistacount++; } while($row = mysql_fetch_array($windowsxp)){ $windowsxpcount++; } while($row = mysql_fetch_array($unknown)){ $unknowncount++; } $statustotal = $onlinecount + $offlinecount + $deadcount; $admintotal = $admintruecount + $adminfalsecount; $sototal = $windows7count + $windowsvistacount + $windowsxpcount + $unknowncount; ?> Can anyone tell me the error here, can how to fix it? Hey all, Another OOP question from me Is using constants in a class a bad idea? For example I have a config file and have this in a class: header("Location: ".LOGIN_LOCATION); Also is it OK to define $_SERVER variables in a construct? For example I have: class whatever { private $_remote_addr; private $_user_agent; function __construct() { $this->_remote_addr = $_SERVER['REMOTE_ADDR']; $this->_user_agent = $_SERVER['HTTP_USER_AGENT']; } .. or is it OK just to use $_SERVER for example in a mysql query? Thanks for all the help so far. Getting there! I would like to define two constants to switch where my "Web Root" is located so I can go between my laptop and web host. I created a "config.inc.php" Code: [Select] <?php // Constants for Web Roots. define('DEV_ROOT', '/00_MyWebsite/'); define('PROD_ROOT', 'w w w.MyWebsite.com/'); ?> and then in my "checkout.php" page I have... Code: [Select] <body> <!-- Access Web Root Constants --> <?php require_once "../config.inc.php"; echo 'DEV _ROOT = ' . DEV_ROOT; echo 'PROD _ROOT = ' . PROD_ROOT; ?> But that doesn't seem to work so far. I know what I'm trying to do, but am getting stuck on how to do it?! Can someone help straighten me out?? Thanks, Debbie Hi, I have a small CMS I coded and developped on my local WAMP server and everything worked fine but when I decided to export everything to my hostgator server I realized that the constants I define in some of my includes are not being defined.. Here is one of the errors I get : Code: [Select] Fatal error: require_once() [function.require]: Failed opening required 'LIB_PATHDSdatabase.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/nethox/public_html/photo_gallery/includes/photograph.php on line 2 You can see that LIB_PATH is not defined and even the .DS. is not working.. Here is a sample of the code I made : Code: [Select] <?php // Defining core paths // Defining them as absolute paths to make sure that require_once works as expected // DIRECTORY_SEPARATOR is a PHP pre-defined constant // (will do \ for Windows, / for Unix) defined('DS') ? null : define('DS', '/'); defined('SITE_ROOT') ? null : define('SITE_ROOT', 'http://www.lemontree-designs.com'.DS.'photo_gallery'); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.'/includes'); defined('LOG_PATH') ? null : define('LOG_PATH', SITE_ROOT.DS.'logs'); defined('PUBLIC_AREA') ? null : define('PUBLIC_AREA', 'http://www.lemontree-designs.com'.DS.'photo_gallery'.DS.'public'); // Load config file first require_once(LIB_PATH."/config.php"); // Load basic functions next so that everything after can use them require_once(LIB_PATH.DS."functions.php"); // Load core objects require_once(LIB_PATH.DS."session.php"); require_once(LIB_PATH.DS."database.php"); require_once(LIB_PATH.DS."pagination.php"); // Load database-related classes require_once(LIB_PATH.DS."user.php"); require_once(LIB_PATH.DS."photograph.php"); require_once(LIB_PATH.DS."comment.php"); ?> Any help is appreciated! EDIT : For the sake of debugging, I've changed the defined value of DS to '/' instead of DIRECTORY_SEPARATOR to see if it's what caused an issue.. Often in the very beginning of index.php, I will define a bunch of constants. To make sure I can quickly identify them as being one of my defined constants, I will often include some sort of prefix.
define ('xzy_somecontant',123); define ('xzy_anothercontant',321);Sometimes I have a bunch of constants that are related; define ('xzy_id_for_page1',123); define ('xzy_id_for_page2',231); define ('xzy_id_for_page3',312);It would be nice to somehow group them into say "xzy_page_ids", and then access them by some index such as "page1" or "1" (or whatever makes sense for the given naming structure). Is this possible? Is there another defacto way of doing so such as a static class or something? Thanks Code: [Select] <?php class constantTest { const HELLOWORLD = 'maybe not'; function __construct() { echo HELLOWORLD; // Output: HELLOWORLD echo constant('HELLOWORLD'); // Output: Warning: constant() [function.constant]: Couldn't find constant HELLOWORLD echo self::HELLOWORLD . "\n"; // Output: maybe not } } $bob = new constantTest(); I have read through the manual but as far as I can see all three methods should output the constant rather than just the last one. Question: Why? Does anyone know how to echo a defined constant without using concatenation? something like Code: (php) [Select] <?php define("CONST", "VALUE"); echo <<<END Some html and my Const = CONST END; ?> This works but I want the var to be const Code: (php) [Select] <?php $CONST = "VALUE"; echo <<<END Some html and my Const = $CONST END; ?> Thanks for your replies I've been working on a registration form and it seems like the better I get at solving more complex issues the smaller issues plague me the most. I've got the following function: //process database actions function process_database($post) { global $table; //connect to database $connect_db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); //check database connection if ($connect_db->connect_error) { return false; } else { if ($stmt = $connect_db->prepare( "INSERT INTO $table (firstname, lastname, username, email, password) VALUES ( ?, ?, ?, ?, ? )" ) ) { $stmt->bind_param(NULL, $firstname, $lastname, $username, $email, $password); $firstname = $post['firstname']; $lastname = $post['lastname']; $username = $post['username']; $email = $post['email']; $password = $post['password']; if (!$stmt->execute()) { return false; } } } return true; } This is in a functions.php file. The issue is in the $connect_db assignment that has the constants from the config.php file in it. That file looks like this: <?php ob_start(); session_start(); $timezone = date_default_timezone_set("America/xxxxxxx"); $whitelist = array('username', 'email', 'email2', 'password', 'password2'); //TODO here I've removed firstname and lastname from the whitelist as they're optional //may add them back and try to iterate around them in the future $table = 'users'; define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'means'); $conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if($conn->connect_errno) { printf("Connect Failed: %s\n", $conn->connect_error); exit(); } ob_end_flush(); ?> The constants defined in config.php are not being recognized in functions.php. I understand that constants are global and available throughout a script. I've connected to two files with the following line: //require config file require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php'); as I have the config/config.php outside htdocs. I know this works because of a db query to check uniqueness of username that works properly. Why are these constants coming back as undefined in the process_database().function.php? Nothing I've tried works and I've run out of ideas. TIA Some questions about PHP Constants... 1.) What make a Constant "come to life"? 2.) What is the life of a Constant? 3.) Can you define a Constant in "file_1.php" and use the Constant in "file_2.php" and "file_3.php"?? Debbie This is probs. an easy one but I have in my database some values, these values are defined constants in my php code. How do I display the value of the constant not the text (constant name)? Hey guys Anyone know the correct syntax to put a constant inside a header? this is driving me crazy with RPATH being my constant header("Location: ".RPATH."admin/monitor.php"); Can you echo class constants? This does not work for me. echo “here is a class constant: self::CLASS_CONSTANT”; // using double quotesInstead I *must* concatenate it: echo ‘here is a class constant: ‘ . self::CLASS_CONSTANT;But of course I do not have to do this with a normal variable, which will echo a variable fine: echo “my name is $name_variable”;Am I doing something wrong or is this normal behavior? Edited by E_Leeder, 30 October 2014 - 11:04 AM. I have defined my database connection data as constants in a separate file for security reasons. How can I simply access the data stored in those constants. I have to call the file to get the value of the constants. If I inadvertently call the file twice in a script using an include or require statement, I get an error that I am trying to define the constants again. Can I somehow just call the constants without including the file where they are defined? --Kenoli I sometime pass configuration settings as an associate array... public function __construct(JsonValidatorMethods $methods, array $options) { foreach($options as $option) { //validate whether valid and if so set $this->$option. Options not provided will default to their private $strictMode=true value } } $validator=new JsonValidator($methods, ['sanitize'=>true, 'strictMode'=>true, 'setDefault'=>false]); And other times pass them as individual arguments... public function __construct(JsonValidatorMethods $methods, bool $sanitize=false, bool $strictMode=false, bool $setDefault=true) {} $validator=new JsonValidator($methods, true, true, false); I have a class which I was doing the later and also which I wish to allow them to be first set in the constructor but also specified when calling some of the public methods. It became a pain to pass all the individual flags to each private method, so I thought I would give bitmask constants a try as shown below. I recognize that this approach only allows booleans to be passed, but I am okay with this. The part I am not sure about is how best have default values. For instance, maybe the default is $this->options=0b0110, 0b1100 is passed to the constructor, and 0b1 (aka 0b0001) is passed is passed to the public method. The high three bits in 0b0001 just are not provided, but how can I not interpret them as explicitly false? Also, a little off topic, but am I implementing this bitmask approach correctly, and any strong options whether one of these three approaches or some totally other approach is best? Thanks class JsonValidator { //Use provided options const SANITIZE = 0b0001; //Whether to sanitize (i.e. 'false' is changed to false) const STRICTMODE = 0b0010; //Currently only enfources that boolean is true/false (instead of 1/0 or "true"/"false") const SETDEFAULT = 0b0100; //If true, type double and value "nan" will be converted to 0, etc. private $methods, $options; static public function create(int $options=0):self { return new self(new JsonValidatorMethods, $options); } static public function getOption(array $options):int { $o=0; foreach($options as $option) { if(!defined("self::$option")){ throw new JsonValidatorErrorException((is_string($option)?$option:'given constant').' is not valid'); } $o=$o|constant("self::$option"); } return $o; } public function __construct(JsonValidatorMethods $methods, int $options=0) { $this->methods=$methods; $this->options=$options; } public function validate(array $input, array $rules, int $options=0){ $options=$options|$this->options; if($options & self::SANITIZE) { $value=$this->sanitize($input, $rules, $options); } } private function sanitize(array $input, array $rules, int $options=0){} } $validator=new JsonValidator($methods, JsonValidator::SANITIZE|JsonValidator::SETDEFAULT); Edited June 27, 2019 by NotionCommotion Nevermind => Maybe I should start my constants with high bit set such as const SANITIZE = 0b1000; What is the best practice for using site-wide constants in a class? E.g. COMPANY_NAME is set in a config file and used on many pages. How would it be best to use this in a class. I'm guessing just calling COMPANY_NAME anywhere in the class would not be considered best practice. Thanks. Well hello there, I want to create a script that writes a few PHP constants to a file called config.php. It does not work however, with the way I wrote it as below: Code: [Select] $configdata = "<?php //Configuration File \define("DBHOST", $dbhost); //DB Hostname \define("DBUSER", $dbuser); //DB Username \define("DBPASS", $dbpass); //DB Password \define("DBNAME", $dbname); //Your database name \define("DOMAIN", $domain); //Your domain name (No http, www or . ) \define("SCRIPTPATH", $scriptpath); //The folder you installed this script in \define("PREFIX", $prefix); ?>"; $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); I am getting this error 'syntax error, unexpected T_STRING in ...', and I have no idea how to fix it. Strangely the below codes using PHP variables work flawlessly: Code: [Select] $configdata = "<?php //Configuration File \$dbhost = '{$dbhost}'; //DB Hostname \$dbuser = '{$dbuser}'; //DB User \$dbpass = '{$dbpass}'; //DB Password \$dbname = '{$dbname}'; //Your database name \$domain = '{$domain}'; //Your domain name (No http, www or . ) \$scriptpath = '{$scriptpath}'; //The folder you installed this script in \$prefix = '{$prefix}'; ?>"; //Write the config.php file... $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); This confuses me, all I did was to change the string to output from a list of variables to a list of constants, and it gives weird errors that I have absolutely no idea how to fix. Can anyone please lemme know what I did wrong? Thanks. Hi guys, Happy New Year http://www.phpfreaks.com/forums/php-coding-help/?action=post How can i get the path http://www.phpfreaks.com/forums thanks, Hey Everyone, I have these 3 scripts to upload an image but I'm having an issue because the images uploaded are going to the same directory as the pages. What do I need to change to make the uploaded images go to a folder path called "pictures". Thanks in advance for the help. Script 1 <form name="form1" method="post" action="adminpicturebrowse.php"> <p align="center">How many pictures for this dog? Max is 9</p> <p align="center"> <input name="uploadNeed" type="text" id="uploadNeed" maxlength="1"> <input type="submit" name="Submit" value="Submit"> </p> </form> Script 2 <form name="form1" enctype="multipart/form-data" method="post" action="adminaddupload.php"> <p align="center"> <? // start of dynamic form $uploadNeed = $_POST['uploadNeed']; for($x=0;$x<$uploadNeed;$x++){ ?> <input name="uploadFile<? echo $x;?>" type="file" id="uploadFile<? echo $x;?>"> </p> <div align="center"> <? // end of for loop } ?> </div> <p align="center"><input name="uploadNeed" type="hidden" value="<? echo $uploadNeed;?>"> <input type="submit" name="Submit" value="Submit"> </p> </form> Script 3 <? $uploadNeed = $_POST['uploadNeed']; // start for loop for($x=0;$x<$uploadNeed;$x++){ $file_name = $_FILES['uploadFile'. $x]['name']; // strip file_name of slashes $file_name = stripslashes($file_name); $file_name = str_replace("'","",$file_name); $copy = copy($_FILES['uploadFile'. $x]['tmp_name'],$file_name); // check if successfully copied if($copy){ echo "$file_name<br>"; }else{ echo "$file_name<br>"; } } // end of loop ?> I have the folder structure like:
root
application
system
assets
uploads
folder assets contains all css, img, and js.
uploads contains user uploaded file.
I set a "helper/assets_helper.php" file to define:
define ('ASSETS_PATH', base_url().'assets/'); define ('UPLOAD_URL', base_url().'uploads/');For all the css, img, and js, it works well like href="<?php echo ASSETS_PATH; ?>css/mycss.css"But when I display the uploaded images, it couldn't display image with <a href="<?php echo UPLOAD_URL;?>images/myupload01.jpg" ><img src="<?php echo UPLOAD_URL;?>images/myupload01.jpg" /></a>This uploaded image actually works fine with my localhost with the link like: http://localhost:900.../myupload01.jpg. But it couldn't display on my hosting server with like: http://users.mywebsi.../myupload01.jpg Can anyone shed some light on it. Thanks! Edited by TFT2012, 20 October 2014 - 10:43 AM. Hello, I would like to know how to include a root file in a 4 deep folder using dots. Is it good : include "../../../config.php" or i can simple include "./config.php" ? How does this works? Is it better to write all the path? Thank you |