combine 2 if conditions without || and && - php

hello i have 2 if conditions
$file ='ips.txt';
$ips = file($file);
$client = $_SERVER['REMOTE_ADDR'];
$ips = file($file, FILE_IGNORE_NEW_LINES);
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
for($i=0;$i<$linecount;$i++){
if (trim($ips[$i]) == $client){
echo"dablokilia<br>";
break;
}
}
include "404.php";
and
if(preg_match('/(Chrome|CriOS)\//i',$_SERVER['HTTP_USER_AGENT'])
&& !preg_match('/(Aviator|ChromePlus|coc_|Dragon|Edge|Flock|Iron|Kinza|Maxthon|MxNitro|Nichrome|OPR|Perk|Rockmelt|Seznam|Sleipnir|Spark|UBrowser|Vivaldi|WebExplorer|YaBrowser)/i',$_SERVER['HTTP_USER_AGENT'])){
include '404.php';
}
How can i merge them to get 1 workable if condition?
So I want to get clients if then check it into my ips.txt file if it's on it don't load anything if it's not on it check if browser is chrome and then load 404.php
thanks

<?php
if(preg_match('/(Chrome|CriOS)\//i',$_SERVER['HTTP_USER_AGENT'])
&& !preg_match('/(Aviator|ChromePlus|coc_|Dragon|Edge|Flock|Iron|Kinza|Maxthon|MxNitro|Nichrome|OPR|Perk|Rockmelt|Seznam|Sleipnir|Spark|UBrowser|Vivaldi|WebExplorer|YaBrowser)/i',$_SERVER['HTTP_USER_AGENT'])){
echo (strpos(file_get_contents('ips.txt'), $_SERVER['REMOTE_ADDR']) !== false)?'':include 'page.php';
}
?>
i have fixed
that code checks if browser is chrome
if chrome it checks if ip is listed on ips.txt if itsnot it loads code.php on index.html

Related

Opening a CSV file from SFTP server in PHP

We currently open a csv from our server and then do some stuff with the data like this:
$CSVfile = fopen('filename.csv', "r");
if($CSVfile !== FALSE) {
$count = 0;
while(! feof($CSVfile)) {
$data = fgetcsv($CSVfile, 5000, ",");
if ($count > 0 && !empty($data)) {
// Do something
}
}
}
We need to change the system as the file will now be hosted on an external server so we need to SFTP into it to retrieve the file. I've installed phpseclib and got the connection working but it just keeps echoing the file contents on the screen. I have it set up like this:
include 'vendor/autoload.php';
$sftp = new \phpseclib\Net\SFTP('SERVER');
if (!$sftp->login('USERNAME', 'PASSWORD')) {
exit('Login Failed');
} else {
$file = $sftp->fetch('FILE_LOCATION');
}
$CSVfile = fopen($file, "r");
if($CSVfile !== FALSE) {
$count = 0;
while(! feof($CSVfile)) {
$data = fgetcsv($CSVfile, 5000, ",");
if ($count > 0 && !empty($data)) {
// Do Something
}
}
}
How do I get the new system to read the file contents and do something with it rather than just showing all the file contents?
As #verjas commented already, there's no fetch method in phpseclib.
If you want to download a file to a string, use SFTP::get:
$contents = $sftp->get("/remote/path/file.csv");
You can then use str_getcsv to parse the contents. According to a contributed note at the function documentation, this should do:
$data = str_getcsv($contents, "\n"); // parse the rows
foreach ($data as $line)
{
$row_data = str_getcsv($line); // parse the items in rows
}

Where can I find or create a urllist.txt file?

I'm trying to make a simple search engine, just to know how it works. I'm following an old tutorial on how to do it with php and mySQL.
However it doesn't explain how to create a urllist.txt file. I downloaded a Quantcast-Top-Million.txt file as required but i'm still confused about how to create a urllist and how it's related to the Quantcast-Top-Million.txt file.
$file_handle = fopen("Quantcast-Top-Million.txt",
"r");
while (!feof ($file_handle)){
$line=fgets($file_handle);
if(preg_match('/ˆ\d+/',$line)){
$tmp=explode("\t",$line);
$rank=trim($tmp[0]);
$url=trim($tmp[1]);
if($url != 'Hidden profile') {
echo $i ;
}
}
}
fclose($file_handle);
$file_handle = fopen("urllist.txt", "r");
while (!feof($file_handle)) {
$url = trim(fgets($file_handle));
$content = file_get_contents($url);
$document = array($url,$content);
$serialized = serialize($document);
$fp = fopen('./documents/'.md5($url), 'w');
fwrite($fp, $serialized); fclose($fp);
}
fclose($file_handle);

Page Hit Counter - Working but want to limit it to per IP Address

I currently have a working script that counts the number of views and stores them in a .txt file.
It's working fine but how do I make it so that it limits to your IP Address?
I tried this but it's not counting.
// Get filename of Page
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php');
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
// Remove .php extension
$counterName = basename($pageName, ".php").".txt";
// Open the file for reading
// "a+" Read & write the file. Create file if not exist.
$fp = fopen($counterName, "a+");
$fpIP = fopen("ip_".$counterName, "a+");
fwrite($fpIP, $ip."-");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Reopen the file and erase the contents
$fp = fopen($counterName, "w");
$ipRead = file_get_contents('ip_index.txt');
if(strpos($ipRead, "$ip") !== FALSE) {
echo $count;
}
else {
fwrite($fp1, $count);
echo $count;
}
fclose($fp);
Below is my updated code with Barmar's code (fully working) which will show each individual visitor how many times they have been to your page based on their IP address.
// Get filename of Page
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php');
// Remove .php extension
$counterName = basename($pageName, ".php").".counter";
// Get IP
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
$count_text = #file_get_contents($counterName);
$counters = $count_text ? json_decode($count_text, true) : array();
if (isset($counters[$ip])) {
$counters[$ip]++;
} else {
$counters[$ip] = 1;
}
file_put_contents($counterName, json_encode($counters));
echo $counters[$ip];
Store an associative array that's keyed off $ip in the counter file.
$count_text = #file_get_contents($counterName);
$counters = $count_text ? json_decode($count_text, true) : array();
if (isset($counters[$ip])) {
$counters[$ip]++;
} else {
$counters[$ip] = 1;
}
file_put_contents($counterName, json_encode($counters));
echo $counters[$ip];
You don't need the ip_XXX.txt file in this design.

PHP die stops everything. What else can I use?

I hope this is the last time I have to bother you good people. I'm a newbie hack who is working on a unique hit counter for each page of a web site. I seem to have it working properly but after the first time when it hits and adds the IP to the file it stops the whole page from loading on refresh or coming back. I know the problem is with the 'die' statement which ends the loop of checking for the IP. I have also tried 'break' and 'exit' but the same thing happens. I have searched for anything else but I can't find anything. Is there a way of getting out of the php code without stopping everything else from loading? Thanks in advance.
<?php
// Declare string names
$ip_file = "ip_index.txt";
// get ip address of user
$user_ip = $_SERVER['REMOTE_ADDR'];
$ip_handle = fopen($ip_file, "r");
while (!feof($ip_handle) ) {
$line_of_text = fgets($ip_handle);
$ip = trim($line_of_text);
if ($user_ip==$ip){
die();
}
}
$count_file = 'count_index.txt';
// read contents of count.txt
$count_file = "count_index.txt";
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$handle = fopen($count_file, "r");
$old_count=fgets($handle);
fclose($handle);
// write contents of count.txt
$fp = fopen($count_file, 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($count_file, "w");
$new_count = $old_count +1;
fwrite($handle, $new_count);
fclose($handle);
// write new IP to ip.txt file
$fp = fopen($ip_file, 'r');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($ip_file, 'a+');
$w_user_ip=$user_ip . "\n";
fwrite($handle, $w_user_ip);
fclose($handle);
?>
Don't exit the whole script when you find a match, just exit the loop. Set a variable that allows you to skip over the code that increments the unique hit counter.
$ip_exists = false;
while (!feof($ip_handle) ) {
$line_of_text = fgets($ip_handle);
$ip = trim($line_of_text);
if ($user_ip==$ip){
$ip_exists = true;
break;
}
}
if (!$ip_exists) {
// Update all the files
...
}
Not sure what you mean. You can reverse the condition of the if block and then just wrap the remaining code in the braces.
eg
if ($user_ip != $ip) {
$count_file = 'count_index.txt';
// read contents of count.txt
$count_file = "count_index.txt";
// ... etc
}
}
When you have:
if ($user_ip==$ip){
die();
}
Put everything you don't want to run if the IPs are the same in an else{} block
Do this:
....
if ($user_ip != $ip) {
$count_file = 'count_index.txt';
// read contents of count.txt
$count_file = "count_index.txt";
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$handle = fopen($count_file, "r");
$old_count=fgets($handle);
fclose($handle);
// write contents of count.txt
$fp = fopen($count_file, 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($count_file, "w");
$new_count = $old_count +1;
fwrite($handle, $new_count);
fclose($handle);
// write new IP to ip.txt file
$fp = fopen($ip_file, 'r');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($ip_file, 'a+');
$w_user_ip=$user_ip . "\n";
fwrite($handle, $w_user_ip);
fclose($handle);
}
If this is included by other code you can use return:
if ($user_ip==$ip){
return;
}
This will stop further execution of your script but code which is including wont die.
If on the other hand you want to terminate the while loop only then break is what you need (what issue did you have when using it?)
if ($user_ip==$ip){
break;
}

Find and replace word in text file

I want to detect if a word in a text file exists, and then remove it.. so, this is my code:
<?php
$search = $id;
$lines = file("./user/".$_GET['own'].".txt");
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
// open to read and modify
$file = "./user/".$_GET['own'].".txt";
$fh = fopen($file, 'r+');
$data = fread($fh, filesize($file));
$new_data = str_replace($id."\n", "", $data);
fclose($fh);
// Open to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_data);
fclose($fh);
$status = "has been successfully deleted.";
}
}
// If the text was not found, show a message
if(!$found)
{
$status = "is not exist in your list.";
}
?>
I got this work hours before.. I did some changes to my script and somehow, it didnt work anymore.. can anyone see through the code and tell me what is wrong??
or can anybody give simpler way to do what I want?? my code is messed..
I want to detect if a word in a text file exists, and then remove it..
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents);
file_put_contents($filename,$contents);
?>
That is all that there is to it.
Edit:
To make this equivalent to your solution, one can use
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents,$count);
if($count>0)
{
file_put_contents($filename,$contents);
echo "found and removed";
}
else
{
echo "not found";
}
?>

Categories