Strange error with an object declaration and url parameter - php

I meet a strange error when I'm coding my application, I would like to use a parameter in url to change the class declaration of an object in a function, I explain my point of view with code, I have product page :
/Product?Page=One
Then I do like that to declare an object in product.php :
public function product() {
$Pagenumber = $_GET['Page']
if(isset($Pagenumber) && trim($Pagenumber) == 'One'){
var_dump('test') // give me "test" , and that mean it's OK!
$object = new class1()
}
if(isset($Pagenumber) && trim($Pagenumber) == 'Two'){
$object = new class2()
}
//then in the first use of object I got an error
...
}
The error is :
Notice: Undefined variable: object
I tried a lot of possibilities but I got nothing , moreover, I got a strange thing when I do like that, it's works very fine :
$foo = "One"; // string
$Pagenumber = "One";
settype($foo, "string"); // $foo vaut maintenant 5 (integer)
settype($Pagenumber, "string");
if($Pagenumber == $foo){
$object = new class1()
}
$object // I can use the object with no error
...
and here I remark that the problem is with parameter in link only?
Someone have a better solution to change class declaration with value of parameter URL or any better solution of issue above?

From your url it looks like you are using url rewriting:
/Product?Page=One
opens:
product.php
If you use .htaccess for that, you need to make sure you add the QSA flag to insure that existing parameters get added to the rewritten url as well.
Apart from that you should make sure that $object is always set or add error handling when it does not match any of your conditions.

It would help you provide the line of code where the variable $object is generating the notice, but a guess would be that you wrote $$object instead of $object

Related

How to get a function name when I hooked it in a php extension

I tried to write a PHP module which is used to detect zend internal function which is called in a php cgi file. Liked code shown below,I want get its name -- 'printf' in my code.
<?php printf("Hello SO!");?>
Now I hooked this function with a function named 'zend_set_user_opcode_handler'.However,I am not able to get the function name which was hooked.(It is 'printf' in this example.) So, what should I do if I want achieve that 'printf' in Function hook_handler()?
Codes here.
int shellhook_handler(ZEND_OPCODE_HANDLER_ARGS){
/* What should I do to catch function name here*/
return ZEND_USER_OPCODE_DISPATCH;
}
PHP_MINIT_FUNCTION(shellhook)
{
REGISTER_INI_ENTRIES();
zend_set_user_opcode_handler(ZEND_DO_FCALL, hook_handler);
return SUCCESS;
}
Hey guys I have got the answer. There are two different methods to achieve hooked function's name.
First, if PHP5 is used, a defining of macro is necessary,because the method depend on the PHP minor version(less than 4 or not).
#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION < 4)
# define OP1_CONSTANT_PTR(n) (&(n)->op1.u.constant)
#else
# define OP1_CONSTANT_PTR(n) ((n)->op1.zv)
#endif
zend_op *opline = execute_data->opline;
zval *fname = OP1_CONSTANT_PTR(opline);
php_printf("FunctionName:%s\n",Z_STRVAL_P(fname));
Second, if PHP7 is used, parameters of shellhook() are not ZEND_OPCODE_HANDLER_ARGS any more. It is replaced by zend_execute_data *execute_data.
zend_execute_data *call = execute_data->call;
zend_function *fbc = call->func;
zend_string *fname = fbc->common.function_name;
php_printf("FunctionName:%s\n",ZSTR_VAL(fname));

Laravel: Can't set object values

I have a form in Laravel that when it submits, the function donorUpdate is going to be called, and it will save the data to the database. Here is the exact code of the function.
My aim is, the form contains the field name DonorPrefix that when it's empty, the default value should be Mx.. I have tried the code below, and it doesn't work.
public function donorUpdate(Request $request, Donor $donor){
if($request->has('DonorPrefix') == false || $request->DonorPrefix == '' || $request->DonorPrefix == null){
$request->DonorPrefix = 'Mx.';
}
$donor->update($request->all());
return redirect('/donor/'.$donor->DonorID);
}
This is where the weird part start: My debugging attempt is that I commented the return redirect('/donor/'.$donor->DonorID); line and replace with return $request->all(), the value for DonorPrefix is "" (Empty string).
However when I tried return $request->DonorPrefix, the prefix Mx. returned.
Why isn't the value of DonorPrefix is Mx. on $request->all(), but is Mx. on return $request->DonorPrefix?
Edit: I'm certain that other parts of code works like charm. Things are smooth untill I tried adding this 'default value' function.
You can't set request parameters like $request->DonorPrefix = '...'.
To set a parameter on the request you need to use offsetSet like this:
$request->offsetSet('DonorPrefix', 'Mx.');
Also, the has() method already ensures that it is a non-empty string so you can remove some of your checks, and simplify your code like this:
if(!$request->has('DonorPrefix')){
$request->offsetSet('DonorPrefix', 'Mx.');
}

Why Do I need an Assignment Operator in This Statement?

I'm playing around with some different design patterns to teach myself more about them, and started using DI Containers.
Main Code (index.php)
$container = new \League\Container\Container();
$container->add("config", function(){
return new Config(APP_ROOT . "/config.json");
});
$container->add("GoogleBooks", GoogleBooksProvider::class)
->withArgument( $container['config'] );
$container->add("books", BookRepository::class);
// empty array, as expected
var_dump($container['books']->getProviders());
// this line doesn't add the provider
$container['books']->addProvider( $container['GoogleBooks'] );
// empty array, should expect to have one entry, GoogleBooksProvider
var_dump($container['books']->getProviders());
BookRepository::addProvider
public function addProvider( iProvider $provider ) {
$this->_providers->push($provider);
return $this;
}
That doesn't work as expected, problem described in the code comments. However, if I swap
$container['books']->addProvider( $container['GoogleBooks'] );
with
$container['books'] = $container['books']->addProvider( $container['GoogleBooks'] );
it works correctly, by storing the GoogleBooksProvider in the BookRepository. Why do I need an assignment operator to make that work correctly?
If I do it without putting it in the container, it works as I expected, without the assignment operator.
$br = new BookRepository();
$br->addProvider( new GoogleBooksProvider($container['config']) );
// shows GoogleBooks is in the _providers array
var_dump($br->getProviders());
Since you are adding, but not sharing the service, you fetch a new instance of BookRepository every time you access the container:
var_dump($container['books'] === $container['books']); // false
If you want to share BookRepository, you need to use this:
$container->add("books", BookRepository::class, true);
or (shorter)
$container->singleton("books", BookRepository::class);

Zend Framework 1 pass parameters using get to the route

I hope the title does not sound too confusing, but I had no idea how to name my problem.
Brief intro:
I'm using Zend 1.1X.
At the moment I've been working with a search form sending few parameters via POST.
Now I have to change it to use GET, I have a route created looking similar to that:
"search/what/:what/shape/:shape"
and so on, I also have 2 optional parameters which takes null as default.
I'm trying to generate an URL (using Zend View Helper Url) at form's action, but it throws an exception:
Uncaught exception 'Zend_Controller_Router_Exception' with message what is not specified
I Now don't have idea what should I do. If I change my route to "search" only, it then sends the form correctly, but I end up with "search?what=XXXX&shape=YYYY" instead of "search/what/XXXX/shape/YYYY".
Is there any way that could be handled the way I like??? :>
#EDIT
I think this should also be mentioned - I have a different form, similar one, pointing to a route without parameters specified as well and the uri gets "translated" to the form of "key/value" pairs. The only difference between them is that the first one does not use Url helper, instead has the method part hard-coded and my form is being submitted programatically (button => jQuery stuff => submit). Would that make a difference here, as I believe it should not? :>
I hope any possible source of this behaviour will come up to you, because I'm really stuck at the moment and I simply can't find what's wrong..
Thanks in advance!
With the GET method a form generates an url like this: action?param1=val1&param2=val2&....
I see two solutions:
The first is to regenerate the URL by javacsript, we can imagine something like this:
<form method="get" id="id_form">
....
</form>
<script>
var objet_form = document.getElementById('id_form');
function gestionclic(event){
var url = objet_form.action;
for(var i = 0; i < objet_form.length; i++){
url += "/" + objet_form[i].name + "/" + objet_form[i].value;
}
objet_form.action = url;
}
if (objet_form.addEventListener){
objet_form.addEventListener("submit", gestionclic, false);
} else{
objet_form.attachEvent("onsubmit", gestionclic, false);
}
</script>
But I don't think this is a good solution.
The second is to manage it with a plugin:
For the plugin, it must be declared in the bootstrap.
For example:
public function _initPlugins(){
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PRoutage());
}
with this example, the application/plugins folder, create the PRoutage.php plugin like this:
class Application_Plugin_PRoutage extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
...
}
}
and with the variable $request you have access to your data as an array with $request->getParams().
We can imagine something like this:
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$param = $request->getParams();
$what = "";
$shape = "";
if (isset($param['what']) $what = $param['what'];
if (isset($param['shape']) $shape = $param['shape'];
if ($what == "XXXX" && $shape == "YYYY"){
$request->setControllerName('other_controler')
->setActionName('other_action')
->setDispatched(true) ;
}
}
I hope it will help you

Codeigniter issue with submitted variables as blank

I have a form :
<?php
$attr = array('id'=>'urlSubmit');
$urlInputAttr = array('name'=>'urlInput','value'=>'yourdomain.com','maxlength'=>'50','size'=>'25');
echo form_open('urlSubmission',$attr);
echo form_input($urlInputAttr);
#echo form_submit('urlInput', '');
echo form_close();
?>
a controller called urlsubmission
$this->load->model('domaincheckmodel');
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
and a function within a model(domaincheckmodel) which basically checks for duplicate records and inserts a new domain:
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
if($DupDomains->num_rows() > 0 ){
$this->load->view('err/domainexists'); ##domain already used
}
# else, no domain present, insert.
else{
#array of insert values:
$insertNewDomain = array('tld'=>$this->input->post('urlInput',TRUE));
$this->db->insert('ClientDomain', $insertNewDomain);
$this->load->view('success/domainfree'); ##domain is free and has been entered.
}
}
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
You're passing from the form to the controller to the model, are you sure the post variable is staying populated? Try the above, capture the post variable in the controller and pass it to the model instead of trying to read it in the model itself?
A little clarification on passing parameters to functions. You can do this via whatever is inside the brackets as follows.
Controller:
$myVariable = $this->someModel->someFunction($someParameter)
Model:
function someFunction($variableIWantToPopulateWithSomeParameter)
So someParameter gets passed from the controller to the function name in the model. There is one thing to be aware of though and that is that model function now EXPECTS a parameter and if you don't give it one, ie you call someFunction() you'll get an error. This can be avoided by giving it a default value like this:
function someFunction($myVariable = 1)
What that is going to do is say if I don't get a value passed to me I am going to make $myVariable equal to one, if I do I'll overwrite 1 with the new value. So if you send two calls to that function this is what you can expect:
//$myVariable is going to be 1, the default.
$this->someModel->someFunction();
//$myVariable is going to be 5, the value passed to it
$this->someModel->someFunction(5);

Categories