PHP Search txt file dosen't look on the first line - php

Ive got this bit of code to look in my txt file to see if i already have the item, However it never looks on the first line. Is there something i can do to fix this?
<?php
for($i=0, $count = count($match[1]);$i<$count;$i++) {
$filename = 'alreadyadded.txt';
$searchfor = $match[1][$i];
$file = file_get_contents($filename);
if(strpos($file, $searchfor)) {
echo $match[1][$i]." Is already added, No Actions needed. <br />";
} else {
echo "grabbing this one".$match[1][$i]."<br />";
}
}
?>

You should do it this way:
if(strpos($file, $searchfor) !== false) {
echo $match[1][$i]." Is already added, No Actions needed. <br />";
} else {
echo "grabbing this one".$match[1][$i]."<br />";
}
if the position found is 0 (the first character) you basically get wrong result. You want to compare the result to false including datatype.
0 == false returns true
0 === false returns false
0 != false returns false
0 !== false returns true

This doesn't solve the problem but should make it slightly faster. You don't need to read the file each time.
$filename = 'alreadyadded.txt';
$file = file_get_contents($filename);
for($i=0, $count = count($match[1]);$i<$count;$i++) {
$searchfor = $match[1][$i];
if(strpos($file, $searchfor)!==false) {
echo $match[1][$i]." Is already added, No Actions needed. <br />";
} else {
echo "grabbing this one".$match[1][$i]."<br />";
}
}

Related

Loop until the request response message equals to "true" in php

I'm trying to make a php script that would make a loop that would get the contents of my site/server and if the text response is for example "false" then it would do the same thing, basically will loop until the site's text response will echo "true".
This is what i tried:
$getcontents = file_get_contents("http://example.com/script.php"); // it will echo false
if (strpos($getcontents , 'false')) {
$getcontents = file_get_contents("http://example.com/script.php");
else if (strpos($getcontents , 'false')) {
$getcontents = file_get_contents("http://example.com/script.php");
}
else if (strpos($getcontents , 'true')) {
echo "finished".;
}
I'm not sure if this is the right way or even if it is possible and i apologize in advance if i did not explain myself very well. Thank you for attention!
You could use a regular while loop.
$getcontents = 'false'; //set value to allow loop to start
while(strpos($getcontents , 'false') !== false) {
$getcontents = file_get_contents("http://example.com/script.php");
}
echo "finished";
This will loop until $getcontents does not contain false.
You could also use a recursive function like this.
function check_for_false() {
$getcontents = file_get_contents("http://example.com/script.php");
if(strpos($getcontents , 'false') !== false) {
check_for_false();
} else if(strpos($getcontents , 'true') !== false) {
echo "finished";
} else {
echo "response didn't contain \"true\" or \"false\"";
}
}
This function should keep calling itself until $getcontents contains the word true, and does not contain false.

how to search string in txt with PHP Stripos

I have a text file containing
number, zero, one
number, two, three
number, four, five
in a file called data.txt
I want to search for the number and tried this but doesnt seem to work
$file = 'domain.com/data.txt';
$searchnum = 'zero';
if (stripos($file, $searchnum) == true) { echo 'number found' }
Update 1.0
i tried this as well but it doesnt seem to pull the data on the txt file
$file = "domain.com/data.txt";
$searchnum = "zero";
if(exec('grep '.escapeshellarg($searchnum).' '.$file )) {
echo "record found";
}
else {
echo "record notfound";
}
You're doing it correctly, you just need to pull the file contents.
$file = file_get_contents('./data.txt'); // you can use a full http address if your server allows it
$searchnum = 'zero';
if (stripos($file, $searchnum) !== false) { echo 'number found'; }
stripos() returns the index of the searched string, or FALSE if it is not found.
So you would do if (stripos($file, $searchnum) !== false) { echo 'number found'; }
!== is used because you need to distinguish false from 0.

PHP - Display differences between two CSV files

I have written a small script which upload two csv files and compare them.
//set files upload directory
$target_dir1 = "uploads/old/";
$target_file1 = $target_dir1 . basename($_FILES["fileToUpload1"]["name"]);
$target_dir2 = "uploads/new/";
$target_file2 = $target_dir2 . basename($_FILES["fileToUpload2"]["name"]);
$uploadOk = 1;
//Upload files
if ($uploadOk == 0) {
echo "<BR> Sorry, your files were not uploaded. <BR>";
} else {
if (move_uploaded_file($_FILES["fileToUpload1"]["tmp_name"], $target_file1)) {
echo "<BR> The 1st file ". basename( $_FILES["fileToUpload1"]["name"]). " has been uploaded. <BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 1st file. <BR>";
}
if (move_uploaded_file($_FILES["fileToUpload2"]["tmp_name"], $target_file2)) {
echo "<BR> The 2nd file ". basename( $_FILES["fileToUpload2"]["name"]). " has been uploaded.<BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 2nd file. <BR>";
}
}
//Get contetnt 1st file
$table1 = Array();
$filehandle1 = fopen($target_file1, "r") ;
if($filehandle1 !== FALSE) {
while(! feof($filehandle1)) { // feof end of file
$data1 = fgetcsv($filehandle1, 1000, ",");
array_push($table1, $data1);
}
}
fclose($filehandle1);
//Get content 2nd file
$table2 = Array();
$filehandle2 = fopen($target_file2, "r") ;
if($filehandle2 !== FALSE) {
while(! feof($filehandle2)) {
$data2 = fgetcsv($filehandle2, 1000, ",");
array_push($table2, $data2);
}
}
fclose($filehandle2);
//Find difference between these two files
$headers= array();
$headers = $table1[0];
$i= 0;
foreach ($table1 as $table) {
echo '<BR>';
$diff = array_diff($table2[$i], $table);
if(!empty($diff)) {
print_r($diff);
$chiave= key($diff);
echo $headers[$chiave];
};
echo '<BR>';
$i++;
}
And this is the error I get, however difference between the two files are dispalyed correctly:
Warning: array_diff(): Argument #1 is not an array in /var/www/csv_files/upload.php on line 67 Call Stack: 0.0053 337384 1. {main}() /var/www/csv_files/upload.php:0 0.0064 367220 2. array_diff() /var/www/csv_files/upload.php:67
You get this error because the first argument is not a array where one is expected. You are now checking a table with the nth element of a array but not the whole array. I think you are making a mistake in thinking table2 is a 2 dimensional array, and it's not. It is used a one dimensional array with nth data2 elements.
Hope this helps!
Seems yes, sometimes table2 is empty or those CSV files have different amount of rows - as result that warning.
So - you need add extra checks if $table2[$i] is not null.
Just a bit another variant from me - how to read file faster (Get content 1st and second file):
$table1 = file($target_file1);
$table2 = file($target_file2);
And then you can do same things as before, with extra tests:
if (count($table1)) {
$headers = str_getcsv($table1[0]);
foreach ($table1 as $key => $table) {
if (!isset($table2[$key])) {
echo 'Row ' . ($key+1) . ' is not exists in second CSV file.';
} else {
$diff = array_diff(str_getcsv($table2[$key]), str_getcsv($table));
// Here is code as in your example
print_r($diff);
$chiave = key($diff);
echo $headers[$chiave];
}
}
}
Good luck! :)

PHP Regular Expressions and CSV Validation

I am trying to create a CSV Checker which inserts the checked data into a Database and any unsuccessful data added to a .txt file.
I am trying to used regular expressions to validate the data I am inserting, the while loop without any validation works and inserts fine but as soon as regular expressions are used it does not work.
<?php
include_once('connection.php');
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$date = date('d/m/y h:i:s a', time());
$filetxt = "./errors.txt";
$errors = array();
$var1 = 5;
$var2 = 1000;
$var3 = 10;
$sql = '';
if(isset($_POST["Import"]))
{
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while(($emapData = fgetcsv($file, 10000, ",")) !==FALSE)
{
if(isset($_GET['strProductCode']))
{
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode']))
{
$errors['strProductCode'];
}
}
if(isset($_GET['strProductName']))
{
$emapData[1] = $conn->real_escape_string(trim($_GET['strProductName']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductName']))
{
$errors['strProductName'];
}
}
if(isset($_GET['strProductDesc']))
{
$emapData[2] = $conn->real_escape_string(trim($_GET['strProductDesc']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductDesc']))
{
$errors['strProductDesc'];
}
}
if(isset($_GET['intStock']))
{
if (!preg_match("^[0-9]", $_POST['intStock']))
{
$errors['intStock'];
}
}
if(isset($_GET['intPrice']))
{
if (!preg_match("[0-9]", $_POST['intPrice']))
{
$errors['intPrice'];
}
}
if(isset($_GET['dtmDiscontinued'])){
if($emapData[6] == preg_match("[a-zA-Z]", $_POST['dtmDiscontinued']))
{
$emapData[6] = $date;
echo $date;
}else{
$emapData[6] = Null;
}
}
if(count($errors > 0))
{
// errors
$write = "$emapData[0], $emapData[1], $emapData[2], $emapData[3], $emapData[4], $emapData[5], $emapData[6]\r\n";
file_put_contents($filetxt , $write , FILE_APPEND);
}else{
// insert into Database
$sql = "INSERT INTO tblproductdata(strProductCode, strProductName, strProductDesc, intStock, intPrice, dtmAdded, dtmDiscontinued) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$date','$emapData[6]')";
$res=$conn->query($sql);
}
}
fclose($file);
echo "CSV File has successfully been Imported";
echo "<br>";
echo "Any errors within the CVS Database are reported here.";
echo "<br>";
$fh = fopen($filetxt, 'r');
$theData = fread($fh, filesize($filetxt));
fclose($fh);
echo $theData;
}else{
echo "Invalid File: Please Upload a Valid CSV File";
}
header("Location: index.php");
}
?>
My knowledge of PHP is not great but this is my best attempt.
Any help would be greatly appreciated.
There are several issues in your code. Let's start with the regular expressions and your error checking:
Some of your expressions are invalid. Note that each expression needs a delimiting character at the beginng and ending of the expression. In some of your expressions (like ^[0-9]) these delimiters are missing. Please also note that using ^ as a delimiter for a regular expression is not a good choice, because the ^ character also has a special meaning in regular expressions.
This should actually cause PHP Warnings. I see that you have error_reporting enabled; you should also have a look at your display_errors setting.
As mentioned in my comment, you do not assign any values to the $errors array. The statement $errors['strProductName'] in itself does not change the array; this means that $errors will always be empty. You probably mean to do something like:
$errors['strProductName'] = TRUE;
You're actually checking count($errors > 0) where you should be checking count($errors > 0). count($errors > 0) translates to either count(TRUE) or count(FALSE) which both equal 1.
Some other notes:
Some times, you check for $_GET['strProductCode'], but then use $_POST['strProductCode'].
You do not reset the $errors array for each iteration. That means that for each line that you read, the $errors variable will still contain the errors from the previous iteration. As a result, the first invalid line will cause all following lines to be recognized as invalid, too.
You register an error when one of the parameters is of an invalid format, but not when one of them is not set at all (i.e. when isset($_POST[...]) is FALSE). Each of them should probably be sth. like this:
if (isset($_POST['strProductCode'])) {
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode'])) {
$errors['strProductCode'] = TRUE;
}
} else {
$errors['strProductCode'] = TRUE;
}

Check if an image exists

I have foreach loop that looks like this:
foreach($wdata->query->pages->$wpageid->images as $iimages)
{
$name = $iimages->title;
$filename = str_replace(" ", "_",$name);
$filename = str_replace("File:","",$filename);
$digest = md5($filename);
$folder = $digest[0].'/'.$digest[0].$digest[1].'/'. $filename;
$url = 'http://upload.wikimedia.org/wikipedia/commons/'.$folder;
echo "<img style='height:100px;' src='$url'>";
}
It displayes images from a returned json array ($wdata)
However, some images have been moved, or don't exist anymore, and I get cracked images, does anyone know how to check if an image is real, exists and can be viewed before it is echoed
Use the file_get_cotents() function to check if it's there
if (file_get_contents("http://....") !== false) { //display image }
It is a remote file and file_exists() does not work for this circumstance. So I suggest you to use getimagesize() function which returns an array if the image exists.
<?php
$imageSize=getimagesize($url);
if(!is_array($imageSize))
{
echo "<img style='height:100px;' src='$url'>";
}
else
{
echo "no image";
}
?>
Another solution:
if (true === file_get_contents($url,0,null,0,1))
{
echo "<img style='height:100px;' src='$url'>";
}
This is faster because it tries to read only one byte of the file if exists.
Use a function as below and pass your url for test
if (image_exist($url)) {
echo "<img ...";
}
function image_exist($url) {
$file_headers = #get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 Found') {
return true;
}
return false;
}

Categories