I have been trying to pass my phantomjs console output back to the php file that executed it, but I only get and empty array with this code. It also happens immediately, which makes me think its attempting to get the return before the phantomjs script has even run.
<?php
$user= 'dafjdh#kjsdf.com';
$pass='dumfmh';
$response = exec("/home/jef28/public_html/swipr/phantomjs /home/jef28/public_html/swipr/login.js $user $pass", $output);
echo $output;
?>
The last lines of my .js file are
console.log(document.querySelectorAll('html')[0].outerHTML);
return document.querySelectorAll('html')[0].outerHTML;
How can I pass the console output back to php?
I use this function and it works just fine .
function execute($script, $args = array(), $options = array(), $bin = 'F:/----/phantomjs-1.9.8-windows/phantomjs.exe', $debug = true) {
$option_str = '';
foreach ($options as $option => $value)
{
$option_str .= '--'.$option.'='.$value.' ';
}
// Escape
$cmd = escapeshellcmd("{$bin} {$option_str}{$script} " . implode(' ', $args));
if($debug) $cmd .= ' 2>&1';
// Execute
$result = shell_exec($cmd);
if($debug) return $result;
if($result === null) return false;
// Return
if(substr($result, 0, 1) !== '{') return $result; // not JSON
$json = json_decode($result, $as_array = true);
if($json === null) return false;
return $json;
}
Related
This is my PHP code
<?php
require_once 'd:\xampp\htdocs\bpr\pdo_db.php';
$sql = "Select ID,FULL_NAMe,AGE from TRIAL";
$csv = get_csv_string($dbh, $sql);
echo "<script> var_csv='" . $csv . "' </script>";
function get_csv_string($dbh, $sql)
{
try
{
$result = $dbh->query($sql);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == null) {
return "No Data";
}
$f = fopen('php://memory', 'r+');
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
//second query gets the data
$data = $dbh->query($sql);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $row) {
if (fputcsv($f, $row) === false) {
return false;
}
} // end record loop
rewind($f);
$csv = stream_get_contents($f);
return rtrim($csv);
} catch (PDOExepction $e) {
return $e->getMessage();
}
return $csv;
}
I am getting following error!
Instead of fputcsv(), I made my own code. But issue if found when I save the CSV to a javascript variable. Is there any other way to convert the data to CSV and pass it on to javascript?
I will convert this csv to JSON at Client side using javascript
You're trying to output a header row to CSV with the field names.
This code fails because you're looping through the $row array and attempting to write one field header at a time.
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
What you want is an array with the field names in it. You can use array_keys() for that, so your code becomes
if (fputcsv($f, array_keys($row)) === false) return false;
No loop required.
It seems like Instagram has changed certain things, because I have tried several codes on my html website to show the amount of Instagram followers on a button, but nothing works.
I tried this:
<?php
$account='XXX';
$instagramsource=file_get_contents('https://instagram.com/' . $account);
preg_match_all('/"userInteractionCount":"(.*?)"/', $instagramsource, $count);
$followcount=$count[1][0];
echo "$account instagram account has $followcount followers";
?>
Also this
<?php
$otherPage = 'XXX';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
if ($data !== null) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo $follows . ' and ' . $followedBy;
}
}
?>
And this ...
<?php
$url = "https://www.instagram.com/XXX";
$json = file_get_contents($url);
$obj = json_decode($json, true);
$content = $obj['query']['results']['script']['content'];
$content = str_replace("window._sharedData =", "", $content);
$content = str_replace(";", "", $content);
$content = trim($content);
$json = json_decode($content);
$instagram_follower_count = $json->entry_data->ProfilePage{0}->user->followed_by->count;
?>
And finally this:
<?php
$username = 'XXX';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo 'XXX follows:' . $follows . ' and is followed by: ' . $followedBy;
}
}
?>
None works.
Can anyone indicate what would work in 2021, please?
Thanks.
It's because the url https://www.instagram.com/$username/?__a=1 is redirecting to login page & giving u a html response
You can check it by echo $response
These posts will help you link1,link2
Instagram blocked access via __a=1 parameter since 2018-04-12. __a=1 must be replaced by JS and Ajax bypass. I've looked for an alternative solution. You can use javascript code inside php. For example:
async function instagramFollowers () {
const followers = []
try {
const userInfoSource = await Axios.get('https://www.instagram.com/123/')
const jsonObject = userInfoSource.data.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1)
const userInfo = JSON.parse(jsonObject)
const mediaArray = userInfo.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges.splice(0, 10)
for (let media of mediaArray) {
const node = media.node
followers.push(node.thumbnail_src)
}
} catch (e) {
console.error('Unable to retrieve Followers. Reason: ' + e.toString())
}
return followers
}
Other helpful links: how to write javascript code inside php
https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms-32494
I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);
What is wrong here:
function getoptions(){
echo "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions();
echo ($id . '***' . $options);
js
console.log(data);
Result:
<option value = 3>ABX</option>10***
I'm expecting 10***<option value = 3>ABX</option>
Any help?
If you need to use the same function to either echo or return the output you can pass a flag to the function. You can set a default value so the function performs as expected by other parts of your app.
// set default value of echo the output so it's non-breaking for other functions that require the output to be echoed
function getoptions($out = 'echo'){
if ($out == 'return') return "<option value = 3>ABX</option>";
echo "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions('return');
echo ($id . '***' . $options);
In function getoptions you are echoing, you need to return the value. Look at the corrected function below.
function getoptions(){
return "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions();
echo ($id . '***' . $options);
im using checkfile to upload file by Month & Year .
If success it will load the data to database.
IF checkfile = false
I want to display an alert message ("import Fail")
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
echo "Import $value successfully! <br>" ;
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
unset($value);
?>
I tried to have echo alert('Import Fail ');
but it give me multiple alert every single file from the folder .
Way1 : Manage the flow with flag as below. If any of the file successfully imported then change the flag and then make a condition on the flag to display alert.
$flag = 0;
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
$flag = 1;
echo "Import $value successfully! <br>" ;
// $query1 =
// "Delete FROM hklcanet_pha.psr this
// WHERE year(psr.ReportDate) = $input3
// AND month(psr.ReportDate) = $input2";
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
into table hklcanet_pha.psr fields terminated by ','
optionally enclosed by '\"'
lines terminated by '\n'
ignore 1 lines
(`ReportDate`, #dummy, #dummy, `Team_refno`,`Name/Description`,`Status`,`PIC`,`RequestDate`,`TargetEndDate`,`ActualEndDate`,`PlanStartDate`,`ActualStartDate`,`PlanUATDate`,`ActualUATDate`,`PlanImplement`,`ActualImplement` )";
//echo "Import $value successfully! <br>" ;
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
if($flag == 1){
echo "<script>alert('Import Fail ');</script>";
}
unset($value);
?>
Way 2: Get the name of successfully imported file names and make conditions on it.
$flag = [];
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
//Store successful file names in array
$flag[] = $value;
echo "Import $value successfully! <br>" ;
// $query1 =
// "Delete FROM hklcanet_pha.psr this
// WHERE year(psr.ReportDate) = $input3
// AND month(psr.ReportDate) = $input2";
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
into table hklcanet_pha.psr fields terminated by ','
optionally enclosed by '\"'
lines terminated by '\n'
ignore 1 lines
(`ReportDate`, #dummy, #dummy, `Team_refno`,`Name/Description`,`Status`,`PIC`,`RequestDate`,`TargetEndDate`,`ActualEndDate`,`PlanStartDate`,`ActualStartDate`,`PlanUATDate`,`ActualUATDate`,`PlanImplement`,`ActualImplement` )";
//echo "Import $value successfully! <br>" ;
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
if(sizeof($flag) == 0){
//Display all the file names in alert
$failedFiles = implode(",",$flag);
echo "<script>alert('Import Failed for files : ".$failedFiles."');</script>";
}
unset($value);
?>