So I am trying to collect and store emails addresses in a text file and is is working other than it not recognising if an address has already been submitted. It will add an address to the text file even if it is already present. Thank you for your insight.
<?php
function showForm() {
echo '
<form method="post" action="">
Email Address: <input type="email" name="email"> <br />
<input type="submit" value="Submit" name="submit">
</form>
';
}
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
$pos = strpos($logcontents, $email);
if ($pos === true) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
} else {
showForm();
}
?>
strpos() returns the position at which the string has been found, or false.
Checking $pos === true can never succeed because the return value of strpos() cannot be true.
Try if ($pos !== false) { ... instead.
Your this line:
$pos = strpos($logcontents, $email);
returns position of the string found, not boolean value.
AND
if ($pos === true) {
may contain 0 as position.
You should change this to:
if ($pos != false) {
Reference
strpos won't ever return true. It can return position zero which will be interpreted by PHP as false unless you use strict comparison.
if ($pos !== false)
Related
I have many input files with different names, but when I upload only one file is saved, that's the reason why?
_form.blade.php :
<input type="file" name="tampak_depan" class="form-control"/>
<input type="file" name="tampak_kiri_depan" class="form-control"/>
<input type="file" name="tampak_kanan_depan" class="form-control"/>
<input type="file" name="tampak_belakang" class="form-control"/>
Controller.php :
tampak depan :
$tampak_depan = $request->file('tampak_depan');
if($tampak_depan !== null) {
$art->tampak_depan = time().'_tampak_depan_'.$tampak_depan->getClientOriginalName();
}
if($tampak_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_depan->move($path,$art->tampak_depan) == false) {
print $tampak_depan->getErrorMessage();
die;
}
}
tampak kiri depan :
$tampak_kiri_depan = $request->post('tampak_kiri_depan');
if($tampak_kiri_depan !== null) {
$art->tampak_kiri_depan = time().'tampak_kiri_depan'.$tampak_kiri_depan->getClientOriginalName();
}
if($tampak_kiri_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_kiri_depan->move($path,$art->tampak_kiri_depan) == false) {
print $tampak_kiri_depan->getErrorMessage();
die;
}
}
tampak kanan depan :
$tampak_kanan_depan = $request->post('tampak_kanan_depan');
if($tampak_kanan_depan !== null) {
$art->tampak_kanan_depan = time().'tampak_kanan_depan'.$tampak_kanan_depan->getClientOriginalName();
}
if($tampak_kanan_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_kanan_depan->move($path,$art->tampak_kanan_depan) == false) {
print $tampak_kanan_depan->getErrorMessage();
die;
}
}
tampak belakang :
$tampak_belakang = $request->post('tampak_belakang');
if($tampak_belakang !== null) {
$art->tampak_belakang = time().'tampak_belakang'.$tampak_belakang->getClientOriginalName();
}
if($tampak_belakang !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_belakang->move($path,$art->tampak_belakang) == false) {
print $tampak_belakang->getErrorMessage();
die;
}
}
Looks like you're using the right function in the first example, but the wrong function in the others.
In 'tampak depan', you're using $request->file(), but in the others you're using $request->post().
Change those to $request->file() and they should work.
I am trying to read all lines from a file and than see if a given string contains any of these lines.
My code
$mails = file('blacklist.txt');
$email = "hendrik#anonbox.net";
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) > 0) {
$fail = true;
}
}
if($fail) {
echo "Fail";
} else {
echo "you can use that";
}
The blacklist.txt can be found here http://pastebin.com/aJyVkcNx.
I would expect strpos return a position for at least one string in the blacklist, but it does not. I am guessing that somehow I am generating not the kind of values within the $mails as I am expecting.
EDIT this is print_r($mails) http://pastebin.com/83ZqVwHx
EDIT2 some clarification: I want to see if a domain is within an email, even if the mail contains subdomain.domain.tld. And I tried to use !== false instead of my > 0 which yielded the same result.
You need to parse the email well since you're checking the domain of the email address if its inside the blacklist. Example:
$email = "hendrik#foo.anonbox.net";
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
preg_match('/#.*?([^.]+[.]\w{3}|[^.])$/', $email, $matches);
if(!empty($matches) && isset($matches[1])) {
$domain = $matches[1];
} else {
// not good email
exit;
}
// THIS IS FOR SAMPLES SAKE, i know youre using file()
$blacklist = explode("\n", file_get_contents('http://pastebin.com/raw.php?i=aJyVkcNx'));
foreach($blacklist as $email) {
if(stripos($email, $domain) !== false) {
echo 'you are blacklisted';
exit;
}
}
}
// his/her email is ok continue
strpos returns FALSE if the string was not found.'
Simply use this :
$fail = false;
foreach($mails as $mail) {
if(strpos($email, $mail) === false) {
$fail = true;
}
}
Or even better use this:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik#anonbox.net";
if(strpos($email, $blacklist) === false){
echo "fail";
} else {
echo "This email is not blacklisted";
}
You have found the common pitfall with the strpos function. The return value of the strpos function refers to the position at which it found the string. In this instance, if the string begins at the first character, it will return 0. Note that 0 !== false.
The correct way to use the function is:
if(strpos($email, $mail) !== false){
// the string was found, potentially at position 0
}
However, this function may not be necessary at all; if you are simply checking if $mail is the same as $email, instead of seeing if the string exists within a larger string, then just use:
if($mail == $email){
// they are the same
}
Though you might still use foreach, that’s array reduce pattern:
function check_against($carry, $mail, $blacklisted) {
return $carry ||= strpos($mail, $blacklisted) !== false;
};
var_dump(array_reduce($mails, "check_against", $email_to_check));
Hope it helps.
Yet another way to solve this. Works fine:
$blacklist = file_get_contents('blacklist.txt');
$email = "hendrik#x.ip6.li";
$domain = substr(trim($email), strpos($email, '#')+1);
if(strpos($blacklist, $domain)){
echo "Your email has been blacklisted!";
}else{
echo "You are all good to go! not blacklisted :-)";
}
Goodluck!
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 />";
}
}
my scenerio is:
A user want to check if the specific(client) url is present in destination url or not and I have created simple script to test the specific url in one destination url.
Here is my php script:
if(isset($_POST['check_url']))
{
$client_url = $_POST['client_url'];
$destination_url = $_POST['destination_url'];
$contents = file_get_contents($destination_url);
$search = $client_url;
if(strpos($contents,$search)== FALSE)
{
echo "Not Found";
}
else
{
echo "Found";
}
}
Here is my html script:
<form method="post" action="test.php">
<label>Client URL:</label>
<input type="text" value="" name="client_url" /><br />
<label>Destination URL:</label>
<textarea value="" name="destination_url" ></textarea><br />
<button type="submit" name="check_url">Check</button>
</form>
The above script is working in case of single destination url but when I tried to post multiple destination url(by converting it into array) I'm getting the error:
Warning: file_get_contents( http://learntk12.org/story.php?title=seo-link-building-service) [function.file-get-contents]: failed to open stream: No such file or directory in "path to source file" on line 24
where line 24 is: $contents[$i] = file_get_contents($arr[$i]);
Here is my php code with array:
if(isset($_POST['check_url']))
{
$client_url = $_POST['client_url'];
$destination_url = $_POST['destination_url'];
$destination =str_replace("\r",",",$destination_url);
$arr = explode(",",$destination);
$search = $client_url;
for($i=0;$i<count($arr);$i++)
{
$contents[$i] = file_get_contents($arr[$i]);
if (strpos($contents[$i], $search) === FALSE)
{
echo "Not Found";
}
else
{
echo "Found";
}
}
}
Where am I lagging in this script?
Try this:
if (isset($_POST['check_url']))
{
$client_url = $_POST['client_url'];
$destination_url = $_POST['destination_url'];
$destinations = str_replace(array("\r\n", "\n"), ',', $destination_url); // replace both types of line breaks with a comma, \r alone will not suffice
$destinations = explode(',', $destinations); // split at commas
foreach ($destinations as $destination) // loop through each item in array
{
$contents = file_get_contents($destination); // get contents of URL
echo (FALSE === strpos($contents, $client_url)) // check if remote data contains URL
? 'Not Found' // echo if TRUE of above expression
: 'Found'; // echo if FALSE of above expression
}
}
As far as I see you don't have an array $contents. It should work like this:
$contents = file_get_contents($arr[$i]);
if (strpos($contents, $search) === FALSE) {
echo "Not Found";
} else {
echo "Found";
}
The function purpose is to validate the URLs of a YouTube video and check if the video exists. This is a snippet of my actual code. I manipulate the string to my desired format and then i proceed to check if it is valid and exists. If it passes the test, then i echo the results. The problem is that I am not calling the function correctly.
I am getting this echo even though the video does exist:
The video does not exist or invalid url
Edited: and added isValidURL function
*Code for checking if video exist or is invalid:*
if($_POST)
{
// After applying url manipulation and getting the url in a proper format result = $formatted_url
function isValidURL($formatted_url) {
$formatted_url = trim($formatted_url);
$isValid = true;
if (strpos($formatted_url, 'http://') === false && strpos($formatted_url, 'https://') === false) {
$formatted_url = 'http://'.$formatted_url;
}
//first check with php's FILTER_VALIDATE_URL
if (filter_var($formatted_url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) === false) {
$isValid = false;
} else {
//not all invalid URLs are caught by FILTER_VALIDATE_URL
//use our own mechanism
$host = parse_url($formatted_url, PHP_URL_HOST);
$dotcount = substr_count($host, '.');
//the host should contain at least one dot
if ($dotcount > 0) {
//if the host contains one dot
if ($dotcount == 1) {
//and it start with www.
if (strpos($host, 'www.') === 0) {
//there is no top level domain, so it is invalid
$isValid = false;
}
} else {
//the host contains multiple dots
if (strpos($host, '..') !== false) {
//dots can't be next to each other, so it is invalid
$isValid = false;
}
}
} else {
//no dots, so it is invalid
$isValid = false;
}
}
//return false if host is invalid
//otherwise return true
return $isValid;
}
$isValid = getYoutubeVideoID($formatted_url);
function isYoutubeVideo($formatted_url) {
$isValid = false;
//validate the url, see: http://snipplr.com/view/50618/
if (isValidURL($formatted_url)) {
//code adapted from Moridin: http://snipplr.com/view/19232/
$idLength = 11;
$idOffset = 3;
$idStarts = strpos($formatted_url, "?v=");
if ($idStarts !== FALSE) {
//there is a videoID present, now validate it
$videoID = substr($formatted_url, $idStarts + $idOffset, $idLength);
$http = new HTTP("http://gdata.youtube.com");
$result = $http->doRequest("/feeds/api/videos/".$videoID, "GET");
//returns Array('headers' => Array(), 'body' => String);
$code = $result['headers']['http_code'];
//did the request return a http code of 2xx?
if (substr($code, 0, 1) == 2) {
$isValid = true;
}
}
}
return $isValid;
}
$isValid = isYoutubeVideo($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
if ( $isValid == true ) {
//Iframe code
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
//Old way to embed code
echo htmlentities ('<embed src="http://www.youtube.com/v/'.$v.'" width="'.$wdth.'" height="'.$hth.'" type="application/x-shockwave-flash" wmode="transparent" embed="" /></embed>');
}
else {
echo ("The video does not exist or invalid url");
}
}
?>
You are missing the isValidURL() function. Try changing this line:
if (isValidURL($formatted_url)) {
to
if(preg_match('/http:\/\/www\.youtube\.com\/watch\?v=[^&]+/', $formatted_url, $result)) {
or
$test = parse_url($formatted_url);
if($test['host']=="www.youtube.com"){