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);
Related
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
Hi I have a php file which is reading all the image files in a directory as so:
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
and I want to get the resulting array in javascript. This code is not working. Any idea why?
<script type = "text/javascript">
$(function() {
$.getJSON('fileNames.php', function(data) {
console.log('yaa');
$(data).each(function(key, value) {
console.log(value);
});
});
});
</script>
getJson performs an ajax call, which will read the contents of the file as its written/displayed, so your echo "filename:" . $file . "<br>"; is becoming part of that meaning your json is becoming invalid
comment out that line and you should be fine
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
//echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
The method wants nothing but valid json to be echo'd/displayed
I have decoded a json in php code, so with my code I will have a php array.
How to include this array in my main html file ?
This is my php code:
<?php
require_once("../main.html");
$x=$_POST["x"];
$y=$_POST["y"];
$z=$_POST=["z"];
$string=file_get_contents("............");
$json_a = json_decode($string, true);
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($json_a,
RecursiveIteratorIterator::SELF_FIRST);
foreach($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
?>
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;
}
I need to plot d3.js histogram and i have troube in plotting the data from database.
php code is as follows.
<?php
// Create connection
$con=mysqli_connect("localhost","","","a");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `b` FROM `h` LIMIT 1");
while($row = mysqli_fetch_array($result))
{
$s1[] = $row['b'];
$length=count($s1);
for($i=0;$i<$length;$i++)
{
$a = array(preg_replace("([c]+)", "",$s1[$i] ));
$b=(str_replace(array( '(', ')') , '', $a));
print_r($b);
$p=implode(" ",$b);
print_r($p);
$co=array_map('strval', explode(',', $p));
echo '</br>'."my array";
print_r($co);
}
}
$result1 = mysqli_query($con,"SELECT `a` FROM `h` LIMIT 1");
while($row1 = mysqli_fetch_array($result1))
{
$s2[] = $row1['a'];
$length1=count($s2);
for($j=0;$j<$length1;$j++)
{
$a1 = array(preg_replace("([c]+)", "",$s2[$j] ));
$b1=(str_replace(array( '(', ')') , '', $a1));
print_r($b1);
$p1=implode(" ",$b1);
print_r($p1);
$co1=array_map('strval', explode(',', $p1));
echo '</br>'."my array2..........";
print_r($co1);
}
}
$map=array_map(null,$co1,$co);
echo "<br>";
echo JSON_ENCODE($map);
echo "<br>";
$object = new stdClass();
$length5=count($s2);
// echo "lennnnnnnnn".$length5;
for($l=0;$l<7;$l++) {
foreach ($map[$l] as $key => $value)
{
if($key == 0)
$object -> a = $value;
else if($key == 1)
$object -> b = $value;
}
$newArr[$l] = JSON_ENCODE($object);
}
print_r($newArr);
mysqli_close($con);
?>
printing array using,
print_r($newArr);
displays the following,
Array ( [0] => {"a":"26.5","b":"80"} [1] => {"a":" 27","b":" 222"} [2] => {"a":" 27.5","b":" 303"} [3] => {"a":" 28","b":" 408"} [4] => {"a":" 28.5","b":" 276"} [5] => {"a":" 29","b":" 151"} [6] => {"a":" 29.5","b":null} )
in d3js code,
var bins = <?php echo JSON_ENCODE($newArr) ; ?>;
bins.forEach(function(bin) {
bin.a = +bin.a;
bin.b = +bin.b;
});
displays the following,
["{\"a\":80,\"b\":26.5}","{\"a\":222,\"b\":27}"," {\"a\":303,\"b\":27.5}","{\"a\":408,\"b\":28}","{\"a\":276,\"b\":28.5}","{\"a\":151,\"b\":29}"," {\"a\":null,\"b\":29.5}"]
I need to call this output in my d3.js code using echo json_encode. When using this, the data creates forward slashes "\" with the numbers and so the numbers are not read as input for the graph. Is there any way to remove the slashes or to take the data with any other alternate code or function?
thanks in advance.
You didn't provide a complete example, but it looks like you're double json_encodeing. You json_encode array of already json_encoded values.