PHP $_REQUEST server setting - php

I'm currently in the process of migrating servers.
My old server accepted GET/POST variables without defining them, for example:
$model_id = $model_id;
But on my new server, variables needs to be defined, eg:
$model_id = $_REQUEST['model_id'];
I'm trying to save time without having to rewrite all existing scripts, is there a quick solution?

Related

PHP Routing - "Clean" include

I have a PHP routing script, like this:
include_once('routing-functions.php');
// pathMatches was imported from routing-functions.php
if(pathMatches('/blog/*')){
include_once('actual-script.php');
}
The problem I have is the following: the functions and global variables from routing-functions.php could potentially conflict with the included file. Additionally, I don't want actual-script.php to have access to any of the variables of the router.
I am looking for a way to completely wipe the PHP context, so that the file is included as if it were directly requested, so doing the following is not an option because it changes the context/scope in which actual-script.php is executed:
if(pathMatches('/blog/*')){
function $sandbox(){
include_once('actual-script.php');
};
$sandbox();
}
Additionally, sending a local request to the file (e.g. with cURL) is also not an option, because it has a negative impact on performance and I want it to run as if it were under the /blog/ URL.
The problem is easy to solve with .htaccess, however, I need a dynamic solution that uses a PHP router.
If anyone has had a similar problem before or knows of a good solution it would be greatly appreciated.

Change server side cached variable from outside of website?

I'm playing with laravel/php and was using the Cache to store a specific cached variable. I wanted to avoid hitting the database for a property / setting I need all my users to rely on. This setting controls whether certain events can occur. This wasnt difficult as I could simply check if I have the cached variable and assign it otherwise get it from my backend (SQL Server):
if (Cache::has('myKey')){
$value = Cache::get('myKey');
} else {
$value = DB::table('myTable')->get();
Cache::put('myKey', $value);
}
//use cached value...
This cached value or db setting is caused by a certain action of an administrator he / she can turn this setting on (true) or off (false). However, we also have an outside process (not on the actual site but an actual sql job) that has to also set this setting. In the SQL job I can easily assign the db setting (true or false) but how do I write that setting to my cached value in laravel / php if I am inside of my sql job?
The short of this is how can I set a server side cached variable value from outside of my website?
So in that case I would either go with exposing a REST API (protected by authentication of course) that does this. Something like http://my-host/api/clear-cache.
Or ssh into the server directly and change the cache.

Define php variable at php initialization

I'm currently coding one of my first php applications.
The application has to connect to a LDAP server and change some user attributes in the directory.
That application has some parameters to read in a mySQL Database in order to run.
Some examples of these parameters could be:
-LDAP Address
-LDAP Service Account
-LDAP Password
there are much more parameters, which rule, for example, the way users authenticate to my application,...
Currently, the database is read at each user session initialization, but, it doesn't have any sense because parameters do not vary from a session to another.
So, i'm looking for a way to load these parameters from the database, only one time (for example, at the php service initialization), and access to these parameters in the "normal" php code through variables.
What would be the best way to do this?
Thank you in advance.
You are looking for a persistent cross-request storage. There are many options for this.
The simplest is APCu (which can be used in conjunction with Zend OpCache, or for PHP < 5.5, APC).
Simply:
if (apc_exists('mykey')) {
$data = apc_fetch('mykey');
} else {
// create it from scratch
apc_store('mike', $data);
}
$data can be most any PHP type, arrays, objects, or scalars.
You can even put this code in the auto_prepend_file INI setting so it is run automatically on every request.
However: this is per server (and per SAPI, so mod_php/php-fpm/cli don't share the cache) so you will have to create it once per server.
Alternatively, for a multi-server setup you can use something like memcached or redis. These are stand-alone daemons that will let you store arbitrary key/value pairs of string data (so you may need to serialize()/unserialize() on the values).
I personally prefer memcache, which has two extensions for PHP, pecl/memcached and pecl/memcache (I prefer pecl/memcached, it has more features).
Both of them are pretty simple.
pecl/memcached:
$memcache = new Memcached();
$memcache->addServer('localhost', '11211');
$data = $memcache->get('mykey');
if (empty($data)) {
// Create data
$memcache->set('mykey', $data);
}
pecl/memcache:
$memcache = new Memcache();
$memcache->connect(); // uses localhost:11211, the default memcache host/port
$data = $memcache->get('mykey');
if (empty($data)) {
// Create data
$memcache->set('mykey', $data);
}
Both extensions support storage of arrays and objects without serialization.
You can of course store multiple keys with any of these solutions and just pull them all, instead of using one, or one with an array/object.
You can use Memcache do cache database requests. See here how to use.
Another way is using Php Sessions.
<?php
session_start(); // need to be before any html code
$_SESSION['something'] = 'Something here...';
echo $_SESSION['something']; // will show "Something here..."
And you can remove using...
unset($_SESSION['something']);
You also can use cookies, using the function setcookie. See here.
And you can get cookies using...
echo $_COOKIE['something'];
Production mode
In a production mode, this will work as set_transient of Wordpress. You will do the first db request to get the value and will cache this value using cookies, sessions or memcache.
If you want to show this values inside of your page, you can use a standard caching library.
My understanding of the question is that you have some SQL data that is more or less constant and you don't want to have to read that in from the SQL connection on every request.
If that is the case you can use memcache to store the data:
http://php.net/manual/en/book.memcache.php
The data will still be persistent and you will only need to go to the database if the cached data isn't there or needs to be refreshed.
If the data is specific to a particular user you can just use a session.
http://php.net/manual/en/book.session.php
http://php.net/manual/en/session.examples.basic.php
If this is only to be used when starting up your server (so once and done) and you don't want to bother to with memcached/xcache (as they would be over kill) you can still use environment variables. See get_env

Get .php file locally using curl

I'm using curl in PHP to return the content of a PHP file. I want to do this locally because I will be accessing multiple PHP files during the same script, so it would be faster to open the file directly.
However, I want to be able to push parameters into the PHP files (treat them exactly as PHP files on the web, but grabbing them locally), as I want to push parameters into the scripts which will be generating additional dynamic content when I grab it.
Is this possible to do if I call the files locally? I've tried using the file:///, calling the file directly, but this won't run the PHP code found in these files.
Any ideas?
edit
Sorry for the confusion:
-This is currently running on a webserver, and I am currently calling http:// (and not file:///) so the PHP contained in those files can be executed. However, I find this to be slow because I'm generating multiple curl() calls that are essentially calling the server itself multiple times.
you can do trick like:
function php_to_string($php_file, $new_GET = false, $new_POST = false) {
// replacing $_GET, $_POST if necessary
if($new_GET) {
$old_GET = $_GET;
$_GET = $new_GET;
}
if($new_POST) {
$old_POST = $_POST;
$_POST = $new_POST;
}
ob_start();
include($php_file);
// restoring $_GET, $_POST if necessary
if(isset($old_GET)) {
$_GET = $old_GET;
}
if(isset($old_POST)) {
$_POST = $old_POST;
}
return ob_get_clean();
}
$content = php_to_string('my_file.php');
$content = php_to_string('my_file.php', Array('id'=>23)); // http://localhost/my_fie.php?id=23
But please mind it may overwrite your existing variables, causing bugs (for example duplicate defines) etc. so you may use sandbox solution
I believe you would want to set up a web server (e.g. Apache) on your local machine so you can go to http://localhost/script.php?param1=foo&param2=bar instead of file:///path/to/script.php. The difference is that when you do file:///, the files are just opened, but if you go through Apache, the scripts are actually executed.
As for passing arguments to your scripts, use the query string for that (e.g. ?param1=foo, etc.).
I don't know why you're doing what you're doing, but hopefully that helps you do it.

In PHP what is the right approach for loading configuration parameters into application variables?

I have a database where I keep my configuration parameters, I want to load the configuration parameters into my application variables only once (or upon specific request to reload the parameters), I also want these variables which holds the configuration parameters to be accessible from all php pages/scripts, the idea is to save hits on the database and improve the application response time.
What is the 'classic' php solution to this matter?
It seems to me that this is essentially the same as any other caching question. The fact that the content to be cached is configuration parameters rather than say the content of Web pages or user profile information is unimportant from a technical perspective.
So what you have to do is come up with some caching solution, whether it's memcached or just writing static files with the data you want to cache.
The trick here is that you're not caching HTML to be presented to the user but rather database query results, so you'll probably want to look at approaches like this one:
http://devzone.zend.com/article/1258
I like using the Zend_Config_Ini class. Creating separate sections that can extend others is easy, and with Zend_Cache with Zend_Cache_Frontend_File (to check for updates to the .ini file) and a backend (I use APC) that is particularly fast to access to avoid any overhead of re-parsing.
; Production site configuration data
[production]
webhost = www.example.com
database.adapter = pdo_mysql
database.params.host = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname = dbname
; Staging site configuration data inherits from production and
; overrides values as necessary
[staging : production]
; 'database.adapter' is inherited
; others are overridden
database.params.host = dev.example.com
database.params.username = devuser
database.params.password = devsecret
Make a page that sets constants (key word 'define') early in your routines. Just include it wherever needed.
Like Smandoli's answer, I use a single file that has my configuration.
However, my configuration is actually a multi-dimensional array - meaning I have much greater control over my config - I can change it on the fly if I need to, as well as breaking up the varialbes.
$config['error']['nologin'] = "You're not logged in";
$config['db']['host'] = "localhost";
$config['something']['else'] = "hello world";
Edit: I use a file for values that do not change too much. I do use variables from a database occasionally, but not too often.
My rule of thumb is "If the user doesn't need to change it, load from the file; if they need to change it, then it comes from a database".
I came from the world of C++ the paradigm there was to use a singleton which load the parameters on first (and only) instantiation and export an interface with relevant get'ters (like 'int GetVal(char* key,int &val)' ) the singletone was accessible from all parts of the application, is there anything like that in PHP?

Categories