How to automatically send GET data from a php script - php

I've got a php script and I want to call another php script from within it which logs data.
Problem is I need to send variables and include ('log.php?log=a&dob=fromtest'); is not working as it's saying the script is not found. If I take the variables out then the script is found no problem.
What's the proper way to do this?

You could define the variable in your code.
$_GET['log'] = 'a';
$_GET['dob'] = 'fromtest';
include('log.php');
But the proper way to do it is to write a class for it.
Should look like this:
logManager.class.php
class logManager {
public function addLog($log, $dob) {
/* do you logging */
}
// example for get log items
public function getLog($log, $limit) {
/* do your get log item thing */
}
}
LogThis.php
require_once('logManager.class.php');
$log = new LogManager();
$log->addLog('a', 'fromtest');

If you include a file i would recommend you to make a function and then call the function with parameters like this:
log.php:
<?php
function xy($log, $dob) {
//do something
}
?>
in your script:
<?php
require_once("log.php");
xy("a", "fromtest");
?>
Or you use the header(); function like this:
header("Location: log.php?log=a&dob=fromtest");

The parser will interpret that (log.php?log=a&dob=fromtest) as a file name which is very wrong because no such script file exists.I suggest you consider using the header function to access a script sending variables at the same time . Take for example this site when you 're trying to login, the url will be like.
http://so/login/?return_url=http://mycurrentpage/

Related

PHP - Get class by included url

I want to getting class by included url between two hosts , I had to called class , there is a point which i have to creating an API , like a library to calling whatever. or it must be do by another way ?!
call.php
<?php
class call{
public function Call_Name($c = "") {
$c = "Called";
return $c;
}
}
?>
index.php
<?php
include 'http://example.com/new/call.php';
$call = new call();
echo $call->Call_Name();
?>
(allow_url_fopen , allow_url_include) is already on.
What you are looking for just isn't safe.
Instead of attempting to execute remote code, consider using a package manager such as Composer/Packagist. You can write your general classes once as a "library" and share them among your "packages".
Take a look here: https://getcomposer.org/ for how to get started.

How to run a file in controller continuously in CodeIgniter framework

I'm working on CI framework,where I need to run one file in controller continuously to check the data in the database.
I have tried that by refreshing the page for every 2 seconds in PHP. But it doesn't seems like best approach to do that to load the entire page for every 2 seconds. So I'm trying to run that file through ajax call.
Normally in php I can able to do run the file continuously. I tried the same in this framework, but I'm getting some error like 'Fatal error: Class 'CI_Controller' not found in system/expressionengine/controllers/popup.php because of class in controller.
Is there any way to run the file in controller continuously through AJAX call.
Here is my code
<?php
class Popup extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('popup_model');
}
public function popup1()
{
$page = $_SERVER['PHP_SELF'];
$sec = "2";
header("Refresh: $sec; url=$page");
$data['popup'] = $this->popup_model->get_events();
$data['title'] = 'Pop Up';
if (empty($data['popup']))
{
}
else
{
$this->load->view('popup/popup1',$data);
$this->load->view('popup/eve',$data);
}
}
}
Write a ajax call into the one function and on document ready pass that function to the javascript function as setInterval(functionname, interval_delay);
Every 2 Seconds one AJAX call is not good and may overload your server with too many requests. There are other alternatives like PHPWebsockets and NodeJS to achieve this.

Is there any way to instantiate CodeIgniter and call a function inside a controller from an outside class?

I am creating a cron job that will run every few minutes and it will read from database data to see which function needs to be called and act accordingly to the data but half the crons are written in codeigniter and the other half in native php.
Is there any way to do this? I have been googling but the anwser. I came up with is that it is impossible. I tried changing directory and than including or requiring index.php from the codeigniter, in which the function is that i need to call.
while doing this if my class is written in native php, It returns some errors that don't make sense and if I correct those errors, I would say that half the system function from codeigniter would be gone. It would still be a question if it will work even then.
If my class is written in codeigniter, when I include index.php, it just breaks. No errors no response or it says that the "ENVIRONMENT" variables are already defined. Thus I have been looking for a way to undefine those variables from config file or overwrite them to null or empty string but nothing works.
If you have any ideas it would be much appreciated.
I saw a question question link about some cron jobs in php where the user #michal kralik gave an answer about what i am doing in general with database and one cron class that will call other crons (coould use help for that too).
btw forgot to mention that using curl and exec will not work, because on our servers they sometimes just stop working for no reason.
UPDATE 1:
this is my class currently after so many tries:
class Unicron extends MY_Controller {
public $config;
function __construct() {
parent::__construct();
}
public function init(){
$config['base_url'] = "http://localhost/test";
define('EXT_CALL', true); // Added EXT_CALL constant to mark external calls
$_GET['controller/method'] = ''; // add pair to $_GET with call route as key
$current = getcwd(); // Save current directory path
chdir('C:/inetpub/wwwroot/test/'); // change directory to CI_INSTALLATION
include_once 'index.php'; // Add index.php (CI) to script
define('BASEPATH', 'C:/inetpub/wwwroot/test/system/');
$this->load->library("../../application/controllers/controller.php");
$job = new $this->controller->Class();
$isDone = $job->exportExcel(somekey);
echo $isDone;
$CI =& get_instance(); // Get instance of CI
$CI->exportExcel('baseparts', 'exportExcel');
// FOR STATIC CALLING!!
//$CI->method('controller','method');
//replace controller and method with call route
// eg: $CI->list('welcome','list'); If calling welcome/list route.
//$OUT->_display(); // to display output. (quick one)
// Or if you need output in variable,
//$output = $CI->load->view('VIEW_NAME',array(),TRUE);
//To call any specific view file (bit slow)
// You can pass variables in array. View file will pick those as it works in CI
chdir($current); // Change back to current directory
echo $current;
}
where i try to define BASEPATH it does not define it nor override the previous value.
In the index.php of other codeigniter i put:
if(!defined('ENVIRONMENT'))
define('ENVIRONMENT', 'development');
this way i resolved my issue with ENVIRONMENT already being set error.
this is a few things i found and combined together, hoping it could work but still when i call it via command line it shows nothing (even tried echo anything everywhere and nothing).
This may be a long comment rather than a answer as the code supplied requires a lot of work to make it useful.
Running multiple instances of 'codeigniter' - executed from codeigniter.
Using the 'execute programs via the shell' from PHP. Each instance runs in its own environment.
There are some excellent answers already available:
By default the PHP commands 'shell' wait for the command to complete...
732832/php-exec-vs-system-vs-passthru.
However, we want to 'fire and forget' quite often so this answer is quite useful...
1019867/is-there-a-way-to-use-shell-exec-without-waiting-for-the-command-to-complete
All i did was use this show an example of how to use 'codeigniter' to do this. The example was the 'Hello World' cli example from user manual. The version of ci is 2.1.14. I haven't used 'ci' before.
It is tested and works on 'PHP 5.3.18' on windows xp.
As well as the usual 'Hello World' example, i used an example of a a command that uses 'sleep' for a total of 20 seconds so that we can easily see that the 'ci' instances are separate from each other while executing.
Examples:
<?php
class Tools extends CI_Controller {
// the usual 'hello world' program
public function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}
// so you can see that the processes are independant and 'standalone'
// run for 20 seconds and show progress every second.
public function waitMessage($to = 'World')
{
$countDown = 20;
while ($countDown >= 0) {
echo "Hello {$to}! - ending in {$countDown} seconds".PHP_EOL;
sleep(1);
$countDown--;
}
}
}
'ci' code to run 'ci' code...
<?php
class Runtools extends CI_Controller {
/*
* Executing background processes from PHP on Windows
* http://www.somacon.com/p395.php
*/
// spawn a process and do not wait for it to complete
public function runci_nowait($controller, $method, $param)
{
$runit = "php index.php {$controller} {$method} {$param}" ;
pclose(popen("start \"{$controller} {$method}\" {$runit}", "r"));
return;
}
// spawn a process and wait for the output.
public function runci_wait($controller, $method, $param)
{
$runit = "php index.php {$controller} {$method} {$param}";
$output = exec("{$runit}");
echo $output;
}
}
How to run them from the cli...
To run the 'ci' 'nowait' routine then do:
php index.php runtools runci_nowait <controller> <method> <param>
where the parameters are the ci controller you want to run. Chnge to 'runci_wait' for the other one.
'Hello World: 'wait for output' - (ci: tools message )
codeigniter>php index.php runtools runci_wait tools message ryan3
Hello ryan3!
The waitMessage - 'do not wait for output' - (ci : tools waitMessage )
codeigniter>php index.php runtools runci_nowait tools waitMessage ryan1
codeigniter>php index.php runtools runci_nowait tools waitMessage ryan2
These will start and run two separate 'ci' processes.

When a PHP function is called and something is RETURNED, does it stop running the code below it?

I am just studying other user's PHP code right now to understand and learn better. In the code below, it is part of a user class. When I code using if/else blocks I format them like this...
if(!$this->isLoggedIn()){
//do stuff
}
But in the code below it is more like this
if (! $this->isLoggedIn())
return false;
Also in the function below you can see that there is a couple times that there can be a RETURN value. SO my question here, when RETURN is called, does it not run any code after that? Like does it end the script for that function there?
In this case if this is ran...
if (! $this->isLoggedIn())
return false;
Does it continue to run the code below that?
Here is the function
<?PHP
private function logout($redir=true)
{
if (! $this->isLoggedIn())
return false;
$this->obj->session->sess_destroy();
if ($this->isCookieLoggedIn())
{
setcookie('user','', time()-36000, '/');
setcookie('pass','', time()-36000, '/');
}
if (! $redir)
return;
header('location: '.$this->homePageUrl);
die;
}
?>
Yes.
When PHP sees a return command, it stops executing and returns it to whatever called it. This includes includes, function executions, method execution, etc.
In the following, 'Test' will never echo:
$test = "test";
return;
echo $test;
If you are in an included file, return will stop its execution, and the file that included it will finish executing.
One of the use cases is similar to what you described:
public function echoString($string)
{
if(!is_string($string))
{
return;
}
echo $string;
}
Start by reading the manual:
http://us2.php.net/return
As a side-note...
Even though the return keyword can be used like this, many would consider using it in the manner it is used in your example function to be a very bad practice. It can mess with the "flow" of the code, making it less readable. (Similar to using the goto statement, though admittedly not as bad.)
I would argue that the code you posted would be better structured like this:
<?php
function logout($redir=true)
{
if ($this->isLoggedIn())
{
$this->obj->session->sess_destroy();
if ($this->isCookieLoggedIn()) {
setcookie('user','', time()-36000, '/');
setcookie('pass','', time()-36000, '/');
}
if ($redir) {
header('location: '.$this->homePageUrl);
die;
}
}
}
?>
Nowhere in this version does the code "break" out of a block early. There is never any doubt as to whether the following lines should be executed or not.
I think we need to distinguish between return used within a function and return used globally.
As the PHP Function Reference says, script execution is only stopped in the second case.
#jason, you seemed to be asking about its use in a function.

Zend: Is it possible to send view variables after a redirect?

How could I send additional view parameters after I have done a redirect (e.g. $this->_redirect->gotoSimple();)?
For example, let's say I have an Edit action which will redirect the user to an Error action handler and I would like to be able to send custom, detailed error messages to its view. To illustrate it clearer, the flow would be:
At the Edit view (say, http://localhost/product/edit), the user submits something nasty
At editAction(), a fail check triggers a redirect to my Error view/action handler (so that my URL would read like http://localhost/error/index)
The Error/index.phtml takes a "errorMessage" view variable to display the custom error message, and editAction() needs a means to pass in some value to that "errorMessage" view variable
A quick code snippet would probably look like:
public function editAction() {
//DO THINGS...
// Upon failure
if($fail) {
$this->_redirector->gotoUrl('/error/index');
//TODO: I need to be able to do something like
// $errorView->errorMessage = "Generic error";
}
}
Any solutions, or even other better ways of achieving this, is greatly appreciated.
Don't use gotoURL() for internal redirects. Use gotoSimple(). I takes up to 4 parameters:
gotoSimple($action,
$controller = null,
$module = null,
array $params = array())
In your case it's going to be:
$this->_redirector->gotoSimple('index',
'error',
null,
array('errorMessage'=>$errMsg));
See Redirector Zend_Controller_Action_Helper for details.
I have not seen anywhere that an action (editAction) accesses another action's view (errorView). for the special case of error handling, my idea is using Exceptions. you throw different exceptions for different bad situations, and in your error handler action, you can decide what to show to user based on the exception type:
// file: ProductContorller.php
public function editAction() {
// some code
if ($badThing) {
throw new Exception('describe the bad thing',$errorCode);
}
if ($badThing2) {
throw new Exception('describe the other bad thing',$errorCode2);
}
}
// file: ErrorController.php
public function errorAction() {
$error = $this->_getParam('error_handler');
$exception = $error->exception; // the original Exception object thrown by some code
$code = $exception->getCode();
switch ($code ) {
// decide different things for different errors
}
}
for more information about error handling, the Zend Framework quick start is a great tutorial.
for other situations, you can use some messaging mechanism to communicate between these 2 actions. using flashMessenger action helper is the first thing comes into my mind:
// file: ProductContorller.php
public function editAction() {
// some code
if ($badThing) {
$this->_helper->flashMessenger->addMessage('error1');
$this->_redirect('error');
}
if ($badThing2) {
$this->_helper->flashMessenger->addMessage('error2');
$this->_redirect('error');
}
}
// file: ErrorController.php
public function errorAction() {
$errors = $this->_helper->flashmessenger->getMessages();
if ( in_array('error1',$errors) ) {
// do something
} // elseif ( ...
}
although remember that flashMessenger uses sessions, so sessions and most likely cookies are going to be involved in this messaging process.
The standard way of doing this is with a session-based store of a message you wish to display. It's common enough that there is a view-based helper, FlashMessenger.
The FlashMessenger helper allows you
to pass messages that the user may
need to see on the next request. To
accomplish this, FlashMessenger uses
Zend_Session_Namespace to store
messages for future or next request
retrieval. It is generally a good idea
that if you plan on using Zend_Session
or Zend_Session_Namespace, that you
initialize with Zend_Session::start()
in your bootstrap file. (See the
Zend_Session documentation for more
details on its usage.)
go through this link.. it explains how can we set view variables before _redirect
http://www.rmauger.co.uk/2009/06/creating-simple-extendible-crud-using-zend-framework/
I'll add this to give some more info on how the FlashMessenger class works ( I had some issues figuring it out).
I read somewhere that a session should be started in Bootstrap.php using
Zend_Session::start();
..but my code worked without that, so I suspect sessions are already started.
We're in a controller-object and an action-method is being called. Then something happens, like an insert or an edit into the database, anything really.
We now set one or more messages. I use the following syntax.
$this->_helper->FlashMessenger("Message in a bottle.");
Which is exactly the same as using
$this->_helper->FlashMessenger->addMessage("Message in a bottle.");
This sets a message in the session, you can check that directly by calling
print_r($this->_helper->FlashMessenger->getMessages());
die();
Now there's a redirect to a new url (so a new request basically), inside the controller+action that is handling the request we'll add the messages to the view like so:
$this->view->flashMessages = $this->_helper->FlashMessenger->getMessages();
We now have a choice of where to output these messages. We can do this inside a view that "belongs to" a certain controller, so that could be
views/scripts/index/index.phtml
The drawback here is that you'd have to add the code outputting the messages to every viewscript that uses it. That's not very DRY.
In my eyes a superior solution is the following. Output these messages at in the file where you define the basic layout of your application. That's probably
layouts/scripts/index.phtml
I wrote the following code there.
<?php if( isset($this->flashMessages) && !empty($this->flashMessages) ){ ?>
<ul id="messages">
<?php foreach( $this->flashMessages as $message ){?>
<li>
<?php echo $message;?>
</li>
<?php } ?>
</ul>
<?php } ?>

Categories