Issue with array in php - php

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";
}

Related

PHP to find string in text box

I need help with my PHP website. I need to search if textbox includes some text. Its working only on half. When I type "Kdy" it works but when I type "Kdy prijdes" it wont work. I need to change output when textbox includes some part of textbox but my idea wont work. Any solutions?
<h1>Zeptej se mě</h1>
<form id="frm" method="POST" action="?action">
<input type = "text" name = "textbox" value = ""/>
<input type="submit" value="Odešli" id="submit"/>
</form>
<?php
if(isset($_GET['action']))
{
$text = $_POST['textbox'];
$kde = array("kde", "Kde");
$kam = array("kam", "Kam");
$kdy = array("kdy", "Kdy");
$jak = array("jak", "Jak");
$co = array("co", "Co");
$proc = array("proč", "proc", "Proč", "Proc");
$kdo = array("kdo", "Kdo");
$koho = array("koho", "Koho");
if (in_array($text, $kde))
{
echo "Nikde";
}
elseif(in_array($text, $kam))
{
echo "Nikam";
}
elseif(in_array($text, $kdy))
{
echo "Nikdy";
}
elseif(in_array($text, $jak))
{
echo "Nevim";
}
elseif(in_array($text, $co))
{
echo "Nic";
}
elseif(in_array($text, $proc))
{
echo "Nevim";
}
elseif(in_array($text, $kdo))
{
echo "Nikdo";
}
elseif(in_array($text, $koho))
{
echo "Nikoho";
}
else
{
$text = array("Spíš ne", "Asi", "No nevím");
echo $text[array_rand($text)];
}
}
?>
I would try to find a solution for this using strpos()
so if you check for a specific part of text it could look like this:
if(strpos($text, "Kdy") !== false){
//do something
}
Another approach could be to explode() the $text into its parts and compare the array with an array of strings you want to check for.
But there might be smarter solutions for this.
You can use next simple function:
<?php
function find_text($text) {
// convert input text to lower case
$text = strtolower($text);
// build dictionary with responses on each word
$dict = [
"kde" => "Nikde",
"kam" => "Nikam",
"kdy" => "Nikdy",
"jak" => "Nevim",
"co" => "Nic",
"proč" => "Nevim",
"proc" => "Nevim",
"kdo" => "Nikdo",
"koho" => "Nikoho",
];
// loop trough dictionary
foreach($dict as $find=>$response) {
if (false !== strpos($text, $find)) {
// immediately return response when one of dictionary words found
return $response;
}
}
// if input cot contains no one of dictionary words return 'not found'
$text = array("Spíš ne", "Asi", "No nevím");
return $text[array_rand($text)];
};
// echo find_text('"Kdy prijdes"');
if(isset($_GET['action']))
{
echo find_text($_POST['textbox']);
}
?>
You can test PHP code here

multiple file upload uploads only single post

I have the following code for multiple file uploads using php and mysql. But for some reason , if 'n' files are selected, only the last(or 'n'th) file seems to be uploaded..
Here are the respective files:
HTML
<form enctype="multipart/form-data" method="post" action="<?php echo htmlentities($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<textarea class="form-control" name="postbox" id="pbox"></textarea>
</div>
<h5><strong>Add media:</strong></h5>
<input type="file" name="pfile[]" multiple="multiple" accept="image/*,audio/*,video/*"><br/>
<button type="submit" class="btn btn-success" name="psubmit">Post!</button>
</form>
<div class="posts">
<?php
if(isset($_POST['postbox'])){
$ps = escape($_POST['postbox']);
}
include_once('includes/uploadfile.php'); ?>
</div>
includes/uploadfile.php
<?php ob_start();
require_once 'core/init.php';
if(isset($_POST['psubmit']))
{
foreach ($_FILES['pfile']['tmp_name'] as $key=>$value)
{
$pfname = $_FILES["pfile"]['name'][$key];
$pftype = $_FILES['pfile']['type'][$key];
$pfsize = $_FILES['pfile']['size'][$key];
$pftmploc = $_FILES['pfile']['tmp_name'][$key];
$pferror = $_FILES['pfile']['error'][$key];
$blast = explode(".", $pfname);
$pfextn = end($blast);
if (!empty($ps) && empty($pfname))
{
$dbfname = NULL;
$abc = $get->addPost($a, $ps, $pfname);
header('location:'.escape($_SERVER['PHP_SELF'])); exit;
}
else if (!empty($pfname) && !empty($ps))
{
//list($width, $height) = getimagesize($pftmploc);
if($pfsize > 20971520)
{
echo "ERROR: Your file was larger than 20 Megabytes in size.";
unlink($pftmploc);
exit();
}
else if(!preg_match("/.(gif|jpg|png|mp3|mp4|avi)$/i", $pfname) )
{
echo "ERROR: Restricted file format!Kindly stick to these formats alone:gif,jpg,png,mp3,mp4,avi";
unlink($pftmploc);
exit();
}
else if($pferror == 1)
{ // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
}
$dbfname = rand(100000000000,999999999999).$pfname;
$updir = "ups/posts/";
$arraymov = array();
array_push($arraymov, $dbfname);
$movrslt = move_uploaded_file($pftmploc,$updir.$dbfname);
if($movrslt != true)
{
echo 'ERROR: File upload failed. Try again!';
exit();
}
}
$abc = $get->addPost($a, $ps, implode(',',$arraymov));
header('location:'.escape($_SERVER['PHP_SELF'])); exit;
}
?>
File upload function:
public function addPost($user_id,$status,$file_path){
$query = $this->_db->prepare("INSERT INTO postsinitial (puid, pstatus, postimg) VALUES (:k, :l, :m)");
$query->bindValue(':k',$user_id);
$query->bindValue(':l', nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8')));
$query->bindValue(':m',$file_path);
$query->execute();
$rsizes = $query->rowCount();
if ($rsizes > 0) {
return true;
}
else
{
return false;
}
}
I've tried to code to insert each file path as a comma-separated array of values so that a user can upload multiple images for only one record in database.This is important!
Tnx in advance!
Looks like you have got the logic wrong. You have to execute move_uploaded_file() within the same foreach() that loops through the $_FILES array.
...
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
}
move_uploaded_file(...
}
What you have done is trying to execute move_uploaded_file() in a separate foreach block using $pftmploc variable as the temporary file path. But since that variable was assigned inside the previous foreach() loop, it represents the last element of the uploaded files array. Thats why you are not getting all the files uploaded.
The foreach does not look quite right. Try this snippet in your uploadfile.php in place of the foreach part. It builds your loop a little differently, checking the tmp_name to see if the loop should continue.
if(isset($_POST['psubmit']))
{
$imagearray = array();
for ($i = 0; $_FILES['pfile']['tmp_name'][$i] $i++)
{
$pfname = $_FILES["pfile"]['name'][$i];
$pftype = $_FILES['pfile']['type'][$i];
$pfsize = $_FILES['pfile']['size'][$i];
$pftmploc = $_FILES['pfile']['tmp_name'][$i];
$pferror = $_FILES['pfile']['error'][$i];
$blast = explode(".", $pfname);
$pfextn = end($blast);
array_push($imagearray, $pfname);
if (!empty($ps) && empty($pfname))
{ ...

Why is strpos() not working when searching this .txt file?

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)

if TXT empty echo message possible?

Hi I have a piece of code that is able to delete each newline in a txt file. Now my question is if the txt file is empty it gives an error message that $line doesn't exist. Now i want to add a piece off code that if txt has no content it echo's a message like "no emails in the list"
<?php
$delete = #$_GET['delete'];
$textFile = file("../emaillist/emaillist.txt");
$lines = count($textFile);
if($delete != "" && $delete >! $lines || $delete === '0') {
$textFile[$delete] = "";
$fileUpdate = fopen("../emaillist/emaillist.txt", "wb");
for($a=0; $a<$lines; $a++) {
fwrite($fileUpdate, $textFile[$a]);
}
fclose($fileUpdate);
echo"<p class='accept'>Contact verwijderd!</p>";
exit;
}
foreach($textFile as $key => $val) {
$pre= "<label style='float:left;' class='tablog3a'>";
$line = #$line . $pre . $val . "</label><a style='float:right;' href =?delete=$key><img class='clickreverse' src='images/deletetodo.png'></a><br>";
}
echo $line;
?>
I allready tried:
else {
echo "no emails in the list";
}
but that gave nothing....
I can think of a few ways to check if a file is empty:
$textfile = file('text.txt');
$lines = count($textfile);
if (empty($lines))
echo 'file is empty';
Or:
if (filesize('text.txt') === 0)
echo 'file is empty';
Or, if you want to check if it is empty, not including blank lines or extra whitespace:
$textfile = trim(file_get_contents('text.txt'));
if (empty($textfile))
echo 'file is empty';

PHP - Check if URL exists in link

Here is what I want to do..
Lets say I am looking for the link "example.com" in a file at http://example.com/test.html".
I want to take a PHP script that looks for an in the mentioned website. However, I also need it to work if there is a class or ID tag in the <A>.
See below url
How can I check if a URL exists via PHP?
or try it
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
From here: http://www.php.net/manual/en/function.file-exists.php#75064
...and right below the above post, there's a curl solution:
function url_exists($url) {
if (!$fp = curl_init($url)) return false;
return true;
}
Update code:-
You can use SimpleHtmlDom Class for find id or class in tag
see the below URL
http://simplehtmldom.sourceforge.net/
http://simplehtmldom.sourceforge.net/manual_api.htm
http://sourceforge.net/projects/simplehtmldom/files/
http://davidwalsh.name/php-notifications
Here is what I have found in case anyone else needs it also!
$url = "http://example.com/test.html";
$searchFor = "example.com"
$input = #file_get_contents($url) or die("Could not access file: $url");
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
echo $match[2];
if ($match[2] == $searchFor)
{
$isMatch = 1;
} else {
$isMatch= 0;
}
// $match[0] = A tag
// $match[2] = link address
// $match[3] = link text
}
}
if ($isMatch)
{
echo "<p><font color=red size=5 align=center>The page specified does contain your link. You have been credited the award amount!</font></p>";
} else {
echo "<p><font color=red size=5 align=center>The specified page does not have your referral link.</font></p>";
}

Categories