php: Execute php file from another php file with parameters - php

Details: I have a php file that runs some sql and retrieve a list of information. I run through a loop of that information and want to call another php page and pass it some parameters from the data I am looping through.
Question: How do I execute another php page from within my php?
What I Have Tried: This is the php code that should be calling the second php page (the while loop should be calling the simplepush.php page for each result I get):
<?php
require_once "../database/config.php";
header("Content-type: application/json");
$sql = "SELECT user_ip_address FROM ft_users";
$res = mssql_query($sql);
if (mssql_num_rows($res)) {
while ($op = mssql_fetch_assoc($res)) {
exec('simplepush.php?token = ' . $op . '');
$arr[] = $op;
}
echo json_encode($arr);
//$op = mssql_fetch_assoc($res);
//$op['response'] = 200;
} else {
http_response_code(420);
$op = array(
'response' => 420
);
echo json_encode($op);
}
mssql_close();
?>
I have tried the following:
include ('simplepush.php?token = '.$op.'');
exec ('simplepush.php?token = '.$op.'');
require ('simplepush.php?token = '.$op.'');
shell_exec ('simplepush.php?token = '.$op.'');

Just do:
include ('simplepush.php');
Now $op will be available in simplepush.php. Consider this example:
//index.php
while ($op = mssql_fetch_assoc($res)) {
include ('simplepush.php');
$arr[] = $op;
}
//simplepush.php
print_r($op);
The contents of $op will be output each time through the loop.

Related

Multiple CSV File Creation in PHP

I have a code below
<?php
/* Error display */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
/* Requires */
require 'conn.php';
/* Parameters (DIM) */
$param_customer = $_POST['param_customer'];
$param_user = $_POST['param_user'];
/* Others */
$param_email = $_POST['email'];
$file_dump_area = "../general_sync/";
/* Array */
$jsonData = array();
$arr_result = array();
/******************************** Download customer *********************************/
$cur_filename = $file_dump_area . removeCharEmail($param_email) . "_" . $param_customer . ".csv";
$cur_file = fopen($cur_filename, "w");
$cur_sql = "CALL android_getCustomer('" .$param_email. "')";
$cur_result = mysqli_query($con,$cur_sql);
if ($cur_file && $cur_result) {
while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
fputcsv($cur_file, array_values($row));
}
array_push($arr_result, array('done_process' => "done_cus"));
}
fclose($cur_file);
/******************************** Download user *********************************/
$cur_filename = $file_dump_area . removeCharEmail($param_email) . "_" . $param_customer . "1.csv";
$cur_file = fopen($cur_filename, "w");
$cur_sql = "CALL android_getCustomer('" .$param_email. "')";
$cur_result = mysqli_query($con,$cur_sql);
if ($cur_file && $cur_result) {
while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
fputcsv($cur_file, array_values($row));
}
array_push($arr_result, array('done_process' => "done_user"));
}
fclose($cur_file);
$jsonData = array("received"=>$arr_result);
echo json_encode($jsonData,JSON_PRETTY_PRINT);
function removeCharEmail($val) {
$new_val1 = str_replace(".", "", $val);
$new_val2 = str_replace("#", "", $new_val1);
return $new_val2;
}
?>
The target output of that code is to create 2 csv which is it does but the problem is the 2nd csv has no data although the query shows some it does not write. I tried to copy the 1st line of codes. it does create the file but it didnt write
Whats the problem?
Updated with help of Mr. Barmar
i got this error Commands out of sync; you can't run this command now
The stored procedure is apparently returning two result sets. You need to fetch the next result set before you can start another query. Add:
$cur_result->close();
$con->next_result();
After each loop that fetches the results. See https://stackoverflow.com/a/14561639/1491895 for more details.

How to create php file using php

I'm trying to create multiple .php files using php itself.
I want to put some code into a file; most of code is the same but only one or two variables that I wanted to be dynamic. I mean every file that I make are exactly like each other the only difference between theme is one variable.
My function is this:
function generate_corn_files()
{
$C = $GLOBALS['C'];
$db = $GLOBALS['db'];
//delete all contents of folder
RemoveDir($C->INCPATH.'cron/feed/', false);
$res = $db->query('SELECT id FROM category ');
while($cat = $db->fetch_object($res)) {
$id = $cat->id;
$open_output = <<<'PHP'
<?php
$outter_id = $id;
if($example = true){
echo 'test';
echo $C->INCPATH;
}
?>
PHP;
$fp=fopen($C->INCPATH.'cron/feed/filename_'.$id.'.php','w');
fwrite($fp, $open_output);
fclose($fp);
}
}
I tried to put content of file using heredoc but I want to $id in $outter_id = $id; be equal to $id = $cat->id;
it's a variable outside of heredoc I can't make it work inside of it !
Are there any other solutions to make it work ?
You aren't using HEREDOC syntax but rather NOWDOC syntax. If you use HEREDOC, all variables inside will be evaluated, so you will have to escape with \$ the variables you don't want evaluated.
$open_output = <<<PHP
<?php
\$outter_id = $id;
if(\$example = true){
echo 'test';
echo \$C->INCPATH;
}
?>
PHP;
Or, you can stick with NOWDOC, use a placeholder, and replace it afterwards.
$open_output = <<<'PHP'
<?php
$outter_id = %%%id%%%;
if($example = true){
echo 'test';
echo $C->INCPATH;
}
?>
PHP;
str_replace("%%%id%%%", $id, $open_output);
Maybe this could inspire you
function generate_corn_files()
{
$C = $GLOBALS['C'];
$db = $GLOBALS['db'];
//delete all contents of folder
RemoveDir($C->INCPATH.'cron/feed/', false);
$res = $db->query('SELECT id FROM category ');
while($cat = $db->fetch_object($res)) {
$id = $cat->id;
$open_output = <<<'PHP'
<?php
$outter_id = $id;
if($example = true){
echo 'test';
echo $C->INCPATH;
}
?>
PHP;
$php_var_name_pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
$open_output = preg_replace_callback(
$php_var_name_pattern,
function($matches) {
if(isset($GLOBALS[$matches[1]])) {
if(is_string($GLOBALS[$matches[1]])) {
return '\''.$GLOBALS[$matches[1]].'\'';
} else {
return $GLOBALS[$matches[1]];
}
} else {
return $matches[0];
}
},
$open_output);
$fp=fopen($C->INCPATH.'cron/feed/filename_'.$id.'.php','w');
fwrite($fp, $open_output);
fclose($fp);
}
}

PHP - Icecast info being updated on page

I'm using a script from this site. This script works fine for me and it does what its need to do but I have one problem. When a track finishes on my Icecast server it doesn't get updates on the site. So if my song is 'Stole the show' than it says 'Stole the show' the page but when the song finished and e.g. 'Thinking out loud' starts the page still says 'Stole the show' on a refresh it will update. But how to make it so the page auto updates itself so the users doesn't have to refresh manually?
PHP
<?php
// include the class file
include( 'icecast.php' );
// instantiate class
$stream = new IceCast();
// set server and mount
$server = 'http://radio.finioxfm.com:8000';
$file = '/status.xsl';
// set the url
$stream->setUrl($server,$file);
// get status info
$radio = $stream->getStatus();
// assign array to variables
extract($radio);
// echo the status
echo $status.'<br/>';
// display more stats if ON AIR
if ($status=='ON AIR') :
echo $listeners.' listeners<br/>';
echo $title.'<br/>';
echo $genre.'<br/>';
for ($i=0; $i < 1; $i++) {
echo $now_playing['artist'].'<br/>';
echo $now_playing['track'].'<br/>';
}
endif;
?>
icecast.php script
<?php
class IceCast {
var $server = "http://radio.finioxfm.com:8000";
var $stats_file = "/status.xsl";
var $radio_info=array();
function __construct() {
// build array to store our Icecast stats
$this->radio_info['server'] = $this->server;
$this->radio_info['title'] = '';
$this->radio_info['description'] = '';
$this->radio_info['content_type'] = '';
$this->radio_info['mount_start'] = '';
$this->radio_info['bit_rate'] = '';
$this->radio_info['listeners'] = '';
$this->radio_info['most_listeners'] = '';
$this->radio_info['genre'] = '';
$this->radio_info['url'] = '';
$this->radio_info['now_playing'] = array();
$this->radio_info['now_playing']['artist'] = 'Unknown';
$this->radio_info['now_playing']['track'] = 'Unknown';
$this->radio_info['status'] = 'OFF AIR';
}
function setUrl($url,$file) {
$this->server=$url;
$this->stats_file=$file;
$this->radio_info['server'] = $this->server;
}
private function fetch() {
// create a new curl resource
$ch = curl_init();
// set the url
curl_setopt($ch,CURLOPT_URL,$this->server.$this->stats_file);
// return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// $output = the status.xsl file
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
return $output;
}
function getStatus() {
$output=$this->fetch();
// loop through $output and sort arrays
$temp_array = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($temp_array,$to_push);
}
}
if(count($temp_array)) {
//sort our temp array into our ral array
$this->radio_info['title'] = $temp_array[0];
$this->radio_info['description'] = $temp_array[1];
$this->radio_info['content_type'] = $temp_array[2];
$this->radio_info['mount_start'] = $temp_array[3];
$this->radio_info['bit_rate'] = $temp_array[4];
$this->radio_info['listeners'] = $temp_array[5];
$this->radio_info['most_listeners'] = $temp_array[6];
$this->radio_info['genre'] = $temp_array[7];
$this->radio_info['url'] = $temp_array[8];
if(isset($temp_array[9])) {
$x = explode(" - ",$temp_array[9]);
$this->radio_info['now_playing']['artist'] = $x[0];
$this->radio_info['now_playing']['track'] = $x[1];
}
$this->radio_info['status'] = 'ON AIR';
}
return $this->radio_info;
}
}
?>
First of all, I have to point out that you shouldn't use this script. It works by parsing the Icecast Status page, which we highly discourage, as it may change. For example in Icecast 2.4 we re-made the complete web interface, so chances are that this script breaks.
You should actually parse the XML Icecast provides at http://icecast.tld:8000/admin/stats. It contains everything you need. If you can't access Icecast's Admin page for some reason, you can use the JSON at http://icecast.tld:8000/status-json.xsl, which is there since Icecast 2.4 exactly for the purpose you describe.
To get the site display new metadata information without refreshing, you need to use an AJAX call which either loads directly the status-json.xsl and extracts the metadata and updates it on the page, or if you use the admin XML you need to write a PHP script which returns json, that you can fetch via AJAX and update accordingly.
A lot of people in the past have spoken about setting up node.js (if you have a server doing your streaming).
Personally I have gone with a jquery solution; which just compares the last fetched data with the live data every 10 seconds. That way it loads in almost 'real time'.
You can find my solution here broken down here http://www.radiodj.ro/community/index.php?topic=7471.0

file copy progress session data is null

am trying to get progress of all the files being copied.
$qryStr = explode(",",$_POST['data']);
$timestamp=$_POST['timestamp'];
$size=sizeof($qryStr);
//echo $size;
$offset=100/$size;
$progress=0;
$_SESSION[$timestamp]=$progress;
session_start();
foreach($qryStr as $value) {
$src = $value;
$dest = "../home/tmp/";
$cmd = 'scp '.$src.' '.$dest.'';
sleep(1);
$progress+=$offset;
$_SESSION[$timestamp] = ceil($progress);
var_dump($_SESSION[$timestamp]);
$result = shell_exec($cmd);
}
code to get progress stored in session
session_start();
var_dump($_SESSION['timestamp']);
getProgress($_GET['timestamp']);
function getProgress($timestamp) {
if (isset($_SESSION[$timestamp])) {
echo json_encode(array("progress" => $_SESSION[$timestamp]));
} else {
echo json_encode(array("progress" => -1));
}
}
when i try to accesss the session data , am getting it as null. any problem in my script.
You have used $timestamp in the following line,
$_SESSION[$timestamp] = ceil($progress);
Instead, use
$_SESSION['timestamp'] = ceil($progress);
Only then it will be available in $_SESSION['timestamp'], else will be in $_SESSION['2013-10-28 14:33:00'], something like that which is non-generic.

My iMacro script(s) doesnt run inside my PHP script. Why?

I am learning how to run iMacros from my php scripts so that PHP script calls an iMacros browser session and passes any variables that I have (url and macro name for example). The iMacros session then runs the iMacro, after the macro is done running it passes the resulting html page back to the PHP script and closes itself. In an ideal world, anyway.
Here is the iMacros calling script:
<?php
require 'src/iimfx.class.php';
$iim = new imacros();
$vars = array();
$iim->play($vars,'grab_data.iim');
?>
But when i run this script from cmd.exe [command line] on WAMP, I get this:
New imacros session started!
Using Proxy: MY_PROXY_IP:MY_PROXY_PORT
-runner -fx -fxProfile default
--------------------------------------------------------
Setting Value IP => MY_PROXY_IP
Setting Value port => MY_PROXY_PORT
Playing Macro proxy.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
--------------------------------------------------------
Playing Macro grab_google.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
P.S. MY_PROXY_IP and MY_PROXY_PORT are replaced with actual numbers both in error messages above and iimfx.class.php.
And here is code for the iimfx.class.php :
<?php
class imacros {
function __construct($proxyip = 'MY_PROXY_IP', $proxyport = 'MY_PROXY_PORT', $silent = false, $noexit = false) {
echo "--------------------------------------\nNew imacros session started!\nUsing Proxy: $proxyip:$proxyport\n";
$this->proxyip = $proxyip;
$this->proxyport = $proxyport;
if (empty ( $this->proxyip ))
echo "NO PROXY!!\n";
$this->noexit = $noexit;
$this->fso = new COM ( 'Scripting.FileSystemObject' );
$this->fso = NULL;
$this->iim = new COM ( "imacros" );
$toexec = "-runner -fx -fxProfile default";
if ($silent === true)
$toexec .= " -silent";
if ($noexit === true)
$toexec .= " -noexit";
echo $toexec . "\n";
$this->iim->iimInit ( $toexec );
if (! empty ( $this->proxyip )) {
$dvars ['IP'] = $this->proxyip;
$dvars ['port'] = $this->proxyport;
$this->play ( $dvars, 'proxy.iim' );
}
}
function __destruct() {
if ($this->noexit === false)
$this->iim->iimExit ();
}
function play($immvars = '', $macro) {
echo "--------------------------------------------------------\n";
if (is_array ( $immvars )) {
foreach ( $immvars as $key => $value ) {
echo "Setting Value $key => $value\n";
$this->iim->iimSet ( "-var_" . $key, $value );
}
}
echo "Playing Macro $macro\n";
$s = $this->iim->iimPlay ( $macro );
if($s>0){
echo "Macro successfully played!\n";
}else{
echo "--------MACRO ERROR!-------------------\n ERROR: " . $this->getLastError() . "\n";
}
return $s;
}
// This function retrieves extracts in your iMacros script if you have any.
function getLastExtract($num) {
return $this->iim->iimGetLastExtract ( $num );
}
// Returns the last error :)
function getLastError(){
return $this->iim->iimGetLastError();
}
// Enables/disables images
function setImages($images = 1) { // 1 = on 2 = off
$dvars ['images'] = $images;
$this->play ( $dvars, 'images.iim' );
}
// Enables or disables adblockplus
function enableABP($status = true){
$dvars['status'] = $status;
$this->play ( $dvars, 'abp.iim' );
}
}
?>
Is there something I am missing here?
I have iimRunner.exe running during all of this [started manually before running the script] and I have iMacros Browser V8+.
Also, my grab_data.iim and all other required .iim are in the same place as the php script that is trying to call them and execute them.
Any kind of help and/or steer towards the right direction would be greatly appreciated!!
Thanks in advance.
U must by start the immrunner, before start the script =)
http://wiki.imacros.net/iimRunner

Categories