I need to create a basic search engine with PHP to search for an ID within a .txt file but still don't know how to do it, I'm new programming :(
Any help would be much appreciated.
Here's the code I have so far.
<style type="text/css">
td {
font-family:verdana,arial;
font-size:8pt;
border-color:#ccc; }
.header{
background-color:66b50b;
border-style:solid;
border-color:#32661e;
border-width:1px;
font-weight:bold;
font-size:10pt;
color:ffffff; }
.estiloceldaw{
background-color:ffffff;
border-style:solid;
border-color:666666;
border-width:1px; }
.estiloceldag{
background-color:ddeeff;
color:333333;
font-weight:bold;
font-size:10pt; }
</style>
<?php
$criterioid=$_POST["id"];
echo $criterioid;
$critrionombre=$_POST["nombre"];
$catalogo= array();
$datospelicula = array("clave","titulo","sinopsis","genero","anio","precio","status");
function TraeCatalogo()
{
$numregistros=0;
$ar=fopen("catalogo.txt","r") or
die("No se pudo abrir el archivo");
while (!feof($ar)) {
$linea=fgets($ar);
$catalogo[] = $datospelicula =explode("|",$linea);
$numregistros=$numregistros+1;
}
fclose($ar);
echo "numero de registros".$numregistros;
return $catalogo;
}
function Muestralistado($catalogo,$criterioid,$criterionombre)
{
$tabla= "<table><tr colspan=6><td>Clave</td><td>Nombre</td><td>Sinopsis</td><td>Genero</td><td>Año</td><td>precio</td><td>Status</td></tr>";
if (!isset($criterioid) || trim($criterioid) == "")
{
foreach ($catalogo as $k => $pelicula)
{
$clave=$catalogo[$k][0];
$titulo=$catalogo[$k][1];
$sinopsis=$catalogo[$k][2];
$genero=$catalogo[$k][3];
$anio=$catalogo[$k][4];
$precio=$catalogo[$k][5];
$status=$catalogo[$k][6];
$tabla.="<tr><td>".$clave."</td><td>".$titulo."</td><td>".$sinopsis."</td><td>".$genero."</td><td>".$anio."</td><td>".$precio."</td><td>".$status."</td></tr>";}
}else
{
$tabla.="<tr><td colspan=6>hay un criterio de busqueda!</td></tr>";
} $tabla.="<table>";
echo $tabla;
}
$catalogo2=TraeCatalogo("wa");
Muestralistado($catalogo2);
//var_dump($catalogo2);
?>
<html>
<body> Buscar Pelicula: <form action="index.php" method="post">
Nombre: <input type="text" name="nombre"> id: <input type="text" name="id"> <input type="submit">
</form>
</body>
</html>
$foundText = array(); // Create an array to store your found words
Then, once you've opened the file:
while (!feof($ar))
{
$dataBuffer = fgets($ar); // Load some text into buffer
$explodedText = explode($dataBuffer, "|");
foreach($explodedText as $item){
if(strpos($item, $clave) != false)
$foundText[] = $dataBuffer ;
}
}
}
And then you can iterate through each found item:
foreach($foundText as $textItem){
echo 'Word found: ' . $textItem . ' <br>';
}
Related
I'm trying to create a banning system for a chat that I made and it has a separate "console" only seen by admins. Im using Mac OS 10.11.4, I am the owner and am using Mamp with php version 5.6.10
Ban.php
<?php
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
//example ip addresses
if ($ban === '1.1.1.1' || 192.168.1.132) {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
Chat.php:
<?php
require "blocked.php";
require "connect.inc.php";
require "core.inc.php";
require "commands.php";
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
if (loggedin()) {
echo 'Welcome, '.$first,'<br />';
if ($first != 'SnR' || 'Koi') {
fwrite($activef, $active."\n"."=");
}
} else if (!loggedin()) {
die('Not logged in');
}
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
echo 'Cant send an empty message','<br />';
}
}
$file = "chat.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
if ($linecount > 49) {
unlink($file);
} else {
echo 'Line count: '.$linecount,'<br />';
}
echo 'Chat will reset at 50 lines','<br />';
echo 'Your IP:';
echo $ip_addr,'<br />';
?>
<html>
<head>
</head>
<body>
<!-- <a href='active.txt'>Online users</a><br /> -->
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
</html>
<?php
if ($first == 'SnR' && 'Koi') {
include 'AdminCMD.php';
include 'ban.php';
?>
<iframe id='reload' src='refresh2.php' class="field2">
<fieldset class="field">
</fieldset>
</iframe>
<?php
}
?>
The problem is that everything is fine until you give an input, no matter what you put into the box the output is always "Can't ban an Admin" meaning that it doesn't write to the given file
Thank you for any help.
Your code contains an error, preventing the file from being written. The first line of PHP code,$ban = $_POST['ban'];, could fail if no post data was sent. You need to first check if the $_POST['ban'] was set. A fixed version of your code can be found below.
<?php
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
When i ran your code it returns undefined index ban, you can try this and make sure what is not working for you.
<?php
$ban = isset($_POST['ban']) ? $_POST['ban'] : null;
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if(isset($ban)){
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
I made a Photo gallery by php.
I am able to make upload image and show the image list. But i want to add a delete button where users can delete there unwanted image. But i was failed to add this button work.
Someone please help to fix it?
Here is my code on GitHub: https://github.com/sagar290/photo_gallerey/blob/6cad3743e735ea109723de7e14d5477bff1e964b/gallery.php
<?php
if (isset($_FILES["file"]["name"])) {
$name = $_FILES['file']['name'];
//$size = $_FILES['file']['size'];
//$extention = $type;
$type = strtolower($_FILES['file']['type']);
$tmp_name = $_FILES['file']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($type=='image/jpg')||($type=='image/jpeg')||($type=='image/gif')) {
$location = 'photos/';
if(move_uploaded_file($tmp_name, 'photos/'.$name)) {
echo $name.' is uploaded';
}
}else {
echo 'file must be jpg or jpeg ';
}
}else {
echo 'please choose a file';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo gallery</title>
<style type="text/css">
ul {
list-style-type: none;
}
li {
float: left;
padding: 10px;
margin: 10px;
font: bold 10px Verdana, sans-serif;
}
img {
display: block;
border: 1px solid #333300;
margin-bottom: 5px;
}
</style>
</head>
<body>
<h2>Photo gallery</h2>
<form action="gallery.php" method="POST" enctype="multipart/form-data">
UPLOAD:
<input type="file" name="file"><br><br>
<input type="submit" value="submit">
</form>
<ul>
<form action="gallery.php" method="POST">
<?php
//define location of photo image
$photosDir = './photos';
//define which file extention are images
$photosExt = array('gif','jpg','jpeg','tif','tiff','bmp','png');
//initialize array to hold filenames of images found
$photoList = array();
//read directory contents
//build photo list
if (file_exists($photosDir)) {
$dp = opendir($photosDir) or die('Error: cannot open file');
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
$fileData = pathinfo($file);
if (in_array($fileData['extension'], $photosExt)) {
$photoList[] = "$photosDir/$file"; // file includes as an array
}
}
}
closedir($dp);
}else {
die('ERROR: directory dosent exists');
}
//itarate over photo list
//display each image and file name
if (count($photoList)>0) {
for ($x=0; $x <count($photoList) ; $x++) {
?>
<li>
<input type="submit" name="delete" value="Delete">
<img src="<?php echo $photoList[$x]; ?>" height="150" width="200"/>
<?php echo basename($photoList[$x]); ?><br>
<?php echo round(filesize($photoList[$x])/1024) . 'KB'; ?>
</li>
<?php
}
} else {
die('ERROR: No image found');
}
?>
</form>
</ul>
</body>
</html>
hello just change your submit input to:
<input type="submit" name="delete" value="<?php echo $photoList[$x] ?>">
and then check for that value:
<?php if(isset($_POST['delete']) && !empty($_POST['delete'])){
//find the file
$file = 'photos/'.$_POST['delete'];
if(is_file($file)){
unlink($file);
}else{
echo $_POST['delete']." has not been found!";
}
}?>
Sorry if I have done wrong , is my first question on StackOverflow.
I want to write the value of var after doing several checks that are within the functions and as a result if everything is okey want to print the variables in a particular div. I have created three different div , one to display errors , one to show var and other one for the form.
What I Do That IS THIS:
https://mega.co.nz/#!3EQGQSAL!94ao1u6UhARYaYdjJzfFqY6ln1oPyO9JQ4_ElT7WEkA
Code:
<html>
<head>
<meta charset="UTF-8">
<title>Agenda Alex Ventura</title>
<style type="text/css">
#errores {
display: block;
background-color: grey;
border-color: red;
border-top-style: double;
border-right-style: double;
border-bottom-style: double;
border-left-style: double;
}
#contactos {
margin-top: 20px;
background-color: aquamarine;
}
#formulario{
margin-top: 50px;
}
</style>
</head>
<body>
<div id="errores">
<?php
if (!(isset($_POST['enviar']))) {
//Primera vez
$nombre = "";
$telefono = "";
} else {
if (errores()) {
//Segunda o siguientes veces con error
$nombre = "";
$telefono = "";
} else {
//Todo ok
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
imprimir_datos();
}
}
function errores() {
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
if ((empty($nombre)) || (empty($telefono))) {
echo "Los campos de usuariio y telefono no pueden estar vacíos";
return true;
}
if (strlen($telefono) < 9) {
echo "El telefono debe tener 9 digitos " . strlen($telefono);
return true;
}
if (strlen($telefono) > 9) {
echo "El telefono debe tener 9 digitos " . strlen($telefono);
return true;
}
$expresion = '[0-9]';
if (preg_match($expresion, $telefono) != true) {
echo "El telefono debe tener solo numeros " . ($telefono);
return true;
}
return false;
}
?>
</div>
<div id="contactos">
<?php
function imprimir_datos() {
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
echo "Nombre: $nombre, Telefono: $telefono</br>";
}
?>
</div>
<div id="formulario">
<form action=<?php echo $_SERVER['PHP_SELF'] ?> method="POST">
Nombre : <input type="text" name="nombre" value="<?php echo "$nombre"; ?>"/>
Telefono: <input type="text" name="telefono" value="<?php echo "$telefono"; ?>"/>`enter code here`
<input TYPE="submit" VALUE="Enviar" name="enviar"/>
</form>
</div>
</body>
https://mega.co.nz/#!CA5TmCQJ!utWGpH7PZwpPcHbDK3eTG6JMuTRz_Z6KKAFWtbqPm1o
oh, i see now. Patterns needs delimiters.
change this:
if (preg_match($expresion, $telefono) != true) {
to this:
if (preg_match("/" . $expresion . "/", $telefono) != true)
And for the printing the details, try this. Move the function outside from the div, and call it within the div.
<div id="contactos"><?php imprimir_datos(); ?></div>
<?php
function imprimir_datos() {
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
echo "Nombre: $nombre, Telefono: $telefono</br>";
}
?>
like google
https://www.google.com/#q=cars
I have this very simple search script but want to get a search page linking to the results of a term like If I search for cars in google i get this page
https://www.google.com/#q=cars
right now this script just returns the search results in the same page
<?php
$source_dir = ".";
$results = array();
if(get_magic_quotes_gpc()==1) $_POST["q"]=stripslashes($_POST["q"]);
$criteria = strtolower($_POST["q"]);
function check_criteria($filename,$criteria){
if($criteria=='' or $criteria=='""'){
return false;
}
else{
$criteria1=$criteria;
if(substr($criteria,0,1)=='"' and substr($criteria,-1)=='"'){
$criteria1=substr($criteria,1,-1);
if(strpos($filename,$criteria1)!==false){
return true;
}
}
elseif(strpos($criteria,' ')!==false){
$arr=explode(' ',$criteria);
if($arr) foreach($arr as $val){
$criteria1=trim($val);
if(strpos($filename,$criteria1)!==false){
return true;
}
}
}
else{
if(strpos($filename,$criteria1)!==false){
return true;
}
}
}
}
function find_files($mydir){
global $results, $criteria;
if(($tdir=#opendir($mydir))!==false){
while($f=readdir($tdir)){
if($f!="." and $f!=".."){
if(is_dir($mydir."/".$f)){
if(find_files($mydir."/".$f)>=1000) return count($results);
}
elseif(is_file($mydir."/".$f)){
if(check_criteria(strtolower($f),$criteria)){
// found!
if(count($results)>=1000) return count($results);
$results[]=$mydir."/".$f;
}
}
}
}
closedir($tdir);
}
return count($results);
}
function format_filesize($size,$dec=1) {
$kb = 1024; // Kilobyte
$mb = 1024 * $kb; // Megabyte
$gb = 1024 * $mb; // Gigabyte
$tb = 1024 * $gb; // Terabyte
if($size < $kb) {
return $size." bytes";
}
else if($size < $mb) {
return round($size/$kb,$dec)." kb";
}
else if($size < $gb) {
return round($size/$mb,$dec)." mb";
}
else if($size < $tb) {
return round($size/$gb,$dec)." gb";
}
else {
return round($size/$tb,$dec)." tb";
}
}
?>
<html>
<head>
<title>Search Files</title>
<style>
.err {
color: #f00;
}
label {
font-weight: bold;
}
th {
background-color: #ccc;
font-weight: bold;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body bgcolor="#000000" text="#FFFFFF">
<h1> </h1>
<form method="post">
<label for="q">search:</label>
<input type="text" name="q" id="q" value="<?php echo htmlspecialchars($_POST["q"]) ?>" size="32" maxlength="128"> <input type="submit" name="search" value=" Search! ">
</form>
<?php
// Search results
if($_POST["search"]){
echo '<hr>'."\n\n";
echo '<h3>Search results:</h3>';
if(strlen($_POST["q"])<1){
echo '<p class="err">Please enter keyword.</p>';
}
elseif(strlen($_POST["q"])<2){
echo '<p class="err">Keyword is too short.</p>';
}
else{
$n=find_files($source_dir);
if($n<=0){
echo '<p>No results found.</p>';
}
elseif($n>=1000){
echo '<p>Too much results, please refine your search. Displaying first <b>100</b> results:</p>';
}
else{
echo '<p><b>'.$n.'</b> files found:</p>';
}
if($results){
echo '<table width="500" cellspacing="0" cellpadding="3" border="0">'."\n";
echo '<tr><th align="left">File Name</th><th align="right">Size</th></tr>';
foreach($results as $val){
$size=filesize($val);
echo '<tr><td align="left" valign="top" nowrap>'.basename($val).' </td><td align="right" valign="top" nowrap>'.format_filesize($size).'</td></tr>'."\n";
}
echo '</table>'."\n";
}
}
}
?>
</body>
</html>
If you just want to display the results in a new page (which is what I gather from your post), do the following.
Create a new file, and move everything contained within if($_POST["search"]){} to that file. Remember the newly-created file name.
Add action="NEW_NAME_HERE" to your form tag, where NEW_NAME_HERE is the newly-created file name from step 1.
See here and here for a bit more on action
this is my sample excelsheet values
State 1972-1973 1973-1974 1974-1975 1975-1976 1976-1977 1977-1978 1978-1979 1979-1980 1980-1981 1981-1982
Alabama $733,750 $1,066,300 $1,136,244 $1,343,670 $1,476,307 $1,642,927 $1,507,315 $1,849,825 $2,402,873 $2,079,000
Alaska $1,019,000 $1,100,000 $1,180,500 $1,172,300 $1,415,300 $1,411,700 $1,666,500 $2,026,400 $3,409,800 $7,200,000
Arkansas $890,496 $1,173,304 $1,193,362 $1,735,266 $1,824,536 $1,929,071 $2,090,590 $2,173,595 $2,042,632 $2,203,864
through php coding i need to store in db.how to store it.
just try this
<title>Upload page</title>
<style type="text/css">
body {
background: #E3F4FC;
font: normal 14px/30px Helvetica, Arial, sans-serif;
color: #2b2b2b;
}
a {
color:#898989;
font-size:14px;
font-weight:bold;
text-decoration:none;
}
a:hover {
color:#CC0033;
}
h1 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #CC0033;
}
h2 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #898989;
}
#container {
background: #CCC;
margin: 100px auto;
width: 945px;
}
#form {padding: 20px 150px;}
#form input {margin-bottom: 20px;}
</style>
</head>
<body>
<div id="container">
<div id="form">
<?php
include "e2.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE books"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT INTO books (BookID,Title,Author,PublisherName,CopyrightYear) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
}else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='index.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
</div>
</div>
</body>
</html>
this is e2.php
$db = mysql_connect("localhost","root","") or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("books",$db))
die("No database selected.");
?>
Try this
simplex excel library and script you can create your own excel import to mysql.
if (isset($_FILES['file'])) {
require_once "simplexlsx.class.php";
$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
echo '<h1>Parsing Result</h1>';
echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
list($cols,) = $xlsx->dimension();
foreach( $xlsx->rows() as $k => $r) {
// if ($k == 0) continue; // skip first row
echo '<tr>';
for( $i = 0; $i < $cols; $i++)
echo '<td>'.( (isset($r[$i])) ? $r[$i] : ' ' ).'</td>';
echo '</tr>';
}
echo '</table>';
}
?>
<h1>Upload</h1>
<form method="post" enctype="multipart/form-data">
*.XLSX <input type="file" name="file" /> <input type="submit" value="Parse" />
</form>
the following worked for me if the source is a csv file:
$filename = "/path/to/your/csvfile.csv";
$handle = fopen ($filename, "r");
$buffer = "";
while (!feof($handle)) {
$buffer .= fgets($handle, 16384);
}
$array = parse_csv_php($buffer);
// do what you want with your array...
function parse_csv_php(&$data,$delim=';',$enclosure='"'){
$enclosed=false;
$fldcount=0;
$linecount=0;
$fldval='';
for($i=0;$i<strlen($data);$i++) {
$chr=$data{$i};
switch($chr) {
case $enclosure:
if($enclosed&&$data{$i+1}==$enclosure) {
$fldval.=$chr;
++$i; //skip next char
} else { $enclosed=!$enclosed; }
break;
case $delim:
if(!$enclosed) {
$ret_array[$linecount][$fldcount++]=$fldval;
$fldval='';
} else { $fldval.=$chr; }
break;
case "\r":
if(!$enclosed&&$data{$i+1}=="\n")
continue;
case "\n":
if(!$enclosed) {
$ret_array[$linecount][$fldcount]=$fldval;
$linecount++;
$fldcount=0;
$fldval='';
} else { $fldval.=$chr; }
break;
default:
$fldval.=$chr;
}
}
if($fldval) {
$ret_array[$linecount][$fldcount]=$fldval;
}
return $ret_array;
}