What is the most elegant and efficient way of search a string against injected script file in PHP.
The flow:
i want make form search when user input strings & click search, data searched save on txt/php file with auto create new file based on month & year ex: -201601.php / txt
then data was saved on safety query with serial key on each string
then if data on -201601.php contents have more than 1000+ query, the data old was deleted automatic
then how showing 50 strings based on random strings on -201601.php
then in -201601.php there are no double string or same string
If you have a solution for my issue and want to post an answer, please add some explanation so that I can understand why/how you did it so that I won't come asking the same questions all over again. Thanks
Im search & create file that i want making it with my plot imagination. Here is what I have so far manually :
<center>
<form action="./cari.php?q=" method="GET">
<input type="text" name="q" value="" placeholder=" Cari .." style="cursor: pointer;width:69%"/>
<input type="submit" value="Search"/>
</form>
</center><?php
if(isset($_GET['q'])) {
$data = ''.$_GET['q']."<br>\n";
$ret = file_put_contents('rcnt.php', htmlspecialchars($data), FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
//echo "$ret bytes written to file";
}
}
//else {die('no post data to process');}
?>
Im stuck searching with cant find related tutorial & hope find answer :(
Please your help, i want learn more with this, i use XAMPP 5.6
First step, the ?q= var the browser will create, you don`t need to set this on your form action.
<form method="get">
<input type="text" name="q" placeholder="search">
</form>
The PHP code will be:
<?php
if(!empty($_GET["q"]))
{
$file = fopen(date("Ym") . ".txt","a+");
fwrite($file, $_GET["q"] . "\r\n"); //\r\n jump the line
flose($file);
}
?>
If today is the 1st search of the 1st day of the month, the file will not exists, then, the PHP will create it, otherwise, will open and write on it.
Hope it could help you.
We could try this way:
<?php
$theFile = date("Ym") . ".txt";
$myFile = file($theFile);
for($i = 0; $i < 100; $i++){ //deleting the first 100 lines
unset($myFile[$i]);
}
//rewriting the file without the 100st first lines
file_put_contents($theFile, implode($myFile));
?>
Related
How can I make my $superhero_list array updates after all the code on the superhero.php is done and I want to search for another name?
The problem I find is that after Im done with the superhero.php and go back to superhero.html, it doesnt save the last name on the $superhero_list array.
superhero.html
<html>
<head>
<title>Superhero List</title>
</head>
<body>
<form method="post" action="superhero.php">
<label for="heroname">Check The Super Hero Name:</label>
<input type="text" id="heroname" name="heroname">
</form>
</body>
</html>
superhero.php
<?php
$superhero_list = array();
if (in_array($_POST ["heroname"], $superhero_list)) {
echo 'Your hero was found.<br>';
echo "These are the Super Powers:<br> - Invisibility <br> - Xray Vision <br> - Flight <br> - Underwater Breathing <br> - Immortality <br> - Healing Power <br>
- Mind Reading <br> - Supersmart <br> - Strenght<br>";
} else {
echo "Hero was added to the Super Hero List!";
array_push($superhero_list,$_POST ["heroname"]);
}
echo '<br><br>';
echo 'This your Hero List:<br>';
echo implode("<br>",$superhero_list);
?>
Another thing, there is any better way to write this code? With functions or other loops?
Thanks in advance guys!
If you dont want to store in database then you need to store array value in cookie.
http://php.net/manual/en/features.cookies.php
For cookie you can store value until your browser will not close.
You are resetting the array every time you run the PHP script. You need to save the data so that next time it runs it can pull the data back.
You can either do this by building a database to hold all the names, or you can save them to a file. With something this small saving it to a file is probably the easiest and quickest option.
To save the data to a file change your php script to
<?php
$superhero_list = array();
//Load the list from the file
$filename = 'heroNames.txt';
//First check if the file exists
if (file_exists($filename)) {
//If the file exists load the data
//First open the file for reading using "r"
$myfile = fopen($filename, "r") or die("Unable to open file!");
//Save it into the temp string
$tempString = fgets($myfile);
//turn that string into an array using ":" as the seperator. We will save using ":" later
$superhero_list = explode(":", $tempString);
//ALWAYS CLOSE THE FILE!!!
fclose($myfile);
}
//Now the data is either empty since its the first time used or it has all the names of the old superheros
if (in_array($_POST ["heroname"], $superhero_list)) {
echo 'Your hero was found.<br>';
echo "These are the Super Powers:<br> - Invisibility <br> - Xray Vision <br> - Flight <br> - Underwater Breathing <br> - Immortality <br> - Healing Power <br>
- Mind Reading <br> - Supersmart <br> - Strenght<br>";
} else {
echo "Hero was added to the Super Hero List!";
array_push($superhero_list,$_POST ["heroname"]);
}
//Now to save the data.
//With PHP if you open a file to write and the file does not exist, it will create the file... SO...
//Open the file for writing using "w"
$myfile = fopen($filename, "w");
//Convert the superhero array to a string using ":" to separate them
$tempString = implode(":", $superhero_list);
//Now save that string to the file
fwrite($myfile, $tempString);
//ALWAYS CLOSE THE FILE
fclose($myfile);
echo '<br><br>';
echo 'This your Hero List:<br>';
echo implode("<br>",$superhero_list);
?>
To my understanding you want to:
If the hero exists, echo the information about the hero.
If the hero does not exist, add them to the array.
And you want to be able to keep track of every single hero that is added to the array, even after the user navigates away and back again.
When you navigate away from the php file/page, any data within the variables/file/class is lost. You would have to have some method to store the list of heros (Like a database/some other form of storage).
With a database, you would have fields for the name/each trait. When the user submits the form and sent to the superhero.php file, you would need to query the database for a list of entries/heros. Then you would be able to check if the hero exists or not. If the hero exists, echo that heros fields/data. If the hero does not exist, insert them into the database.
I guess another option would be to save each set of data to a text file. Then you would have to manage reading/writing to the file each time the script is called. However, I wouldn't do it this way...
Ok, so here is my page (basic template recreated for practice):
http://puu.sh/fRn4b/6d83015087.png
Its all static, bar the form.
What I am attempting to do with said form is to get the contents entered to show up in the little gray box just below (it has overflow set so scroll would be enabled once full).
I started with this:
<form action="index.php" method="post">
<input type="text" name="name" placeholder="Enter your name" required><br>
<textarea name="comment" id="comments" rows="10" required placeholder="Enter your thoughts"></textarea><br>
<input type="submit" name="submit">
</form>
if (isset($_POST['name']) && isset($_POST['comment'])) {
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$fullcomment = "<h2>".$name."</h2><p>".$comment."</p>";
echo $fullcomment;
}
That worked, and with the css it looked quite nice. However it would only post one comment and that comment would be lost on reloading. I wanted it to stick. So then the next attempt was:
if (isset($_POST['name']) && isset($_POST['comment'])) {
$file ="./index.php";
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$fullcomment = "<h2>".$name."</h2><p>".$comment."</p>";
file_put_contents($file, $fullcomment, FILE_APPEND);
}
Now upon submitting the form, nothing would happen (including no errors). Is it not possible to use file_put_contents on the file said function(?) is in? Because I tried changing the $file to "./index.txt" and that worked, it created a new file and added the forms content within.
As you can probably tell I am extremely new to this. This is me learning. I pick up new things and I think of ways I could apply them, even if said ways are not the most efficient method.
Any help would be great thank-you!
It does work but it adds the content at the end of the document, not within the comment box. Must need to find a different method.
Edit 2: I suppose I could just take the contents from the index.txt troubleshoot and add it to the .php file, but that seems a bit roundabout.
Edit 3: That worked yuhp. Although now refreshing index.php results in repeating the last entered form content, which is rather annoying. Would the solution to that be resetting the variables after the code has run?
You could use Ajax to solve this problem, but if you are not familiar with it, you can try this out :
$file ="./comments.txt";
// When you the page is loaded, get the comments from 'comments.txt'
$fullcomment = file_get_contents($file);
if (isset($_POST['name']) && isset($_POST['comment'])) {
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$fullcomment = "<h2>".$name."</h2><p>".$comment."</p>";
file_put_contents($file, $fullcomment, FILE_APPEND);
}
I want the Code below to read individual line of text from dataFile.txt and show it in input field.
Problem is After reading first line from text document it shows all remaining lines of text from text file into input field. But on clicking submit it should show second line only then again on submitting it should show third line only, inside input field. please help.
<?php
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$array1 = array();
<form action="datagGet.php" method="get">
<input type="text" value="
<?php while ( $line = fgets($f, 100) )
{
$nl = mb_strtolower($line);
echo $nl;
if(isset($_GET['done']))
{
$nl++;
}
else
{
break;
}
}
?>"
name="someText">
<input type="submit" name="done" >
</form>
You have several problems with you code. And the first comment above points to many of the. Key is the fact that the $_GET['done'] is set for the form submit and therefore you will echo all the lines of the output. It never breaks.
Also there is the fact that you are opening the file for reading each submit of the form. Although I don't see a simple way around this unless you store the file contents between requests.
One possible option is to use 'file()' to read the entire contents into an array. And then use sessions to store which line has been read. Then on each submit, look for the index of the array from the session read; advance it by one read the file again and return that line. Wow wasteful. But okay for simple site.
so use file to get the lines in an array.
output the first line into the value.
store the next index to be read in the $_SESSION variable like $_SESSION['next_line'] = 1
then upon further submissions. read it all back in. look up the 'next_line', and output that line.
so, for example
$array = file('your file name');
$output = $array[0];
if (isset($_SESSION['next_line']))
$_SESSION['next_line'] = intval($_SESSION['next_line']) + 1;
else
$_SESSION['next_line'] = 1;//prime the pump
echo the form with $output
then rinse and repeat. e.g. read, get output (next_line) with file, set $_session = next_line + 1; render output in form.
ps. some extra notes
* of course you'll need to start session on each request.
* you'll need to check if the $_SESSION['next_line'] is set. if not, set it to 1 (prime it)
I have a form element that gets user details and a php script that writes these inputs to a .txt file. What Im having trouble with is following the completion of the php script the url redirects to the http://. . ./the.php and displays a blank page- Im very new to server side scripts but what Im attempting to do is to allow the user to input data and store that data in a text file this text file should me made up of several different inputs collected on multiple days
<?php
if(isset($_POST['aDate'])) {
$aDate = $_POST['aDate'];
$fp = fopen("details.txt", "a");
fputs($fp, "date: $aDate");
fclose($fp);
?>
<form action="txtWrite.php" method="POST" onSubmit="detail()">
<input id="datepicker" name='aDate' type="text" class="time"/>
. . .
I have tested the input values by adding an echo($aDate) in the php script and it checks out, so how do I then redirect back to the html page that allows for more user input to be added to the text file? If you can understand what Im trying to accomplish and have an alternative route, Im all ears. Thanks for taking the time to help me out.
I think you're looking for header('Location:page.php'); which you would use like:
<?php
if(isset($_POST['aDate'])) {
$aDate = $_POST['aDate'];
$fp = fopen("details.txt", "a");
fputs($fp, "date: $aDate");
fclose($fp);
header('Location:page.php');
}
?>
<form action="txtWrite.php" method="POST" onSubmit="detail()">
<input id="datepicker" name='aDate' type="text" class="time"/>
. . .
header("Location: http://www.yousite.com/yourscript.html");
Thanks in advance for any help, I hope my explanation of my request is understandable.
I have a website where I upload various HTML pages with scripts, websites etc. that I have found useful over time... For the purpose of 1) a reference for myself, and 2) to share what I've found with others.
The website consists of 2 sections. A search page to find the script, and an admin page to upload it. The uploaded HTML file gets placed in a "docs/" directory on my server, and the details are added to a MySQL database for the search page.
The form looks like this:
<form name="upload" enctype="multipart/form-data" action="includes/add.php"
method="post" onsubmit="return validateForm();">
<label for="scriptname">Script Name</label><input class="inputarea" type="text"
name="scriptname"><br>
<label for="category">Category</label><input class="inputarea" type="text"
name="category"><br>
<label for="keywords">Keywords</label><input class="inputarea" type="text"
name="keywords"><br>
<label for="content">HTML File</label><input class="inputarea" type="file"
name="content"><br>
<input class="submit" type="submit" value="Add">
</form>
My question is this... Is there any way with JavaScript or PHP to do the following:
generate an automatic file name for the uploaded file (a few random digits would do)
In the "scriptname" input field, add text on submit so that it makes the Script name and file name into a hyperlink that's added to the database as text... eg. When submit button is pressed, the following is added to the database:
"scriptname_input"
Where the bold section is taken from the generated file name and the italic section is from the input field...
The purpose of this is so that in the search results, when the database column with the script name comes up, the script name is a link to the actual file. I have the search feature ready, and it is able to make a link from a database entry, but I just need to simplify the upload process.
If this is not possible, is there a different way to achieve this?
---EDIT---
Thank you all for your help! Much appreciated, I've worked it out using a combination of a few of the suggestions. However, I gave the credit to Ibere as his solution was the closest.
Here is the final code I used for the 'add.php' file that processed the upload and database addition, just in case it ever comes up again (I doubt it) :P
<?php
$filename = md5($_FILES['content']['name']);
$labelForUrl = $_POST['scriptname'];
$url = "$labelForUrl";
$target = "../docs/";
//This gets all the other information from the form
$name=$_POST['scriptname'];
$cat=$_POST['category'];
$key=$_POST['keywords'];
$link=$_POST['link'];
$file=($_FILES['content']['scriptname']);
// Connects to your Database
mysql_connect("localhost", "username", "password") or
die(mysql_error()) ;
mysql_select_db("scripts") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO scripttable (scriptname,category,keywords,link,content)
VALUES ('$url', '$cat', '$key', '$link', '$file')") ;
if(move_uploaded_file($_FILES['content']['tmp_name'], $target . $filename)) {
echo "The file ". $labelForUrl.
" has been uploaded";
}
else {
echo "There was an error uploading the file, please try again!";
}
?>
You can do something like this for the filename.
$filename = md5($_FILES['content']['name']);
$labelForUrl = $_POST['scriptname'];
md5 is not Random, but is good enough for generating a unreadable string for a filename.
Then you can create a url like this
<a href="docs/<?php echo $filename; ?>" ><?php echo $labelForUrl; ?></a>
Hope this helps.
EDIT: I forgot to add the extension to the filname. So the right code would be something like:
$filename = md5($_FILES['content']['name']).$_FILES['content']['type']
I recommend using uploadify for uploads. But, to do what you asked:
$randomFileName = rand(1000, 9999);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $randomFileName . $_FILES["file"]["type"]);
// update your db with the location
$loc = "upload/" . $randomFileName . $_FILES["file"]["type"];
mysqli_query("insert into `myTable` (`loc`) values ('$loc')");
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
For file uploading help, look at http://www.w3schools.com/php/php_file_upload.asp
This is very easy, if you know codeigniter ( PHP Framework ).
You can use the Upload Class
You can easily create forms and submit them and also display them.
I would do it that way. If you are familiar with MVC you can do that in 10-15 mins.
To generate random file names, I usually find this does the work quite well: md5( rand( 0, 100000 ) );. If you wish to limit the size of the file name, you may use the substr function.
(Assuming a MySQL database), make the connection and then query the database using the INSERT command. This link shows how to do all of this.