remove breaks from php url string? - php

I for the life of me can't figure this out...
I've got a form, it ends up passing some fields as a query string.
$f = $_GET['full'];
$t = $_GET['title'];
$illegal = array("'", "#039;");
$f = str_replace($illegal, "", $f);
$t = str_replace($illegal, "", $t);
For some weird reason, apostrophes where messing up what I need, so I removed them as they were turning up (' for the first occurance and #039; afterwards).
Now $t outputs a useable string. $f however can contain breaks. And they end up in the string as
<br+%2F>
I've tried
$f = preg_replace("/\r?\n/", "", $f);
and
$breaks = array("<br+%2F>", "/\r?\n/", "<br />");
$f = str_replace($breaks, "%20", $f);
but when i output it in a url I STILL get
http://www.domain.com?t=good%20string&f=bad<br+%2F>string
The is causing a 404 page not found error. :(
EDIT
$f = html_entity_decode($_GET['full']);
$t = html_entity_decode($_GET['title']);
$illegal = array("'", "#039;");
$f = str_replace($illegal, "", $f);
$t = str_replace($illegal, "", $t);
$f = htmlspecialchars($f);
$breaks = array("<br+%2F>%0D%0A<br+%2F>%0D%0A", "<br+%2F>%0D%0A");
$f = str_replace($breaks, "%20", $f);
if (---private-stuff---) {
header( 'Location: /?title=' . $t . '&full=' . $f . '&fifth=fith%20percent');
}
The last $f STILL contains
<br+%2F>%0D%0A<br+%2F>%0D%0A
in the url. Shouldn't ONE of those functions stripped it out?!?

Use html entities decode
$string = html_entity_decode("'");
echo $string ; // '
so in your case that will be
$f = html_entity_decode($_GET['full']);
$t = html_entity_decode($_GET['title']);

Since you are getting a 404, it may be that you have a .htaccess rule (ModRewrite) that is trying to route you to some other page (that does not exist). Sounds like you may have two separate issues...
To get your actual text back out of the query string, Ibu is correct...use html_entity_decode()

Related

php - one time access by looking up serial in a .dat file

i've now written this short script.
It records a serial or token number, checks to see if its in a .dat file, and allows access if its present. Otherwise it denies access to the site.
It also removes the token from the file once it has been redeemed as it were.
However, when i add multiple tokes in the dat file, the code doesn work properly. It only works with a single entry. How would i make it work for multiple entries.
im thinking of maybe implementing some sort of array somewhere? or explode?
index.php
require_once "married.php";
session_start();
$url_request = (isset($_SERVER['HTTPS']) ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip = $_SERVER['REMOTE_ADDR'];
$token = substr($url_request,45);
$_SESSION["cookie"] = $token;
$tk = $_SESSION["cookie"];
$ips = array();
$page = file("urls.dat");
foreach($page as $line)
{
array_push($ips, $line);
}
if(in_array($tk, $ips))
{
//header("Location: mysite.co.uk");
echo "<title>My Site</title>Here is my site";
$file = fopen("ip_match.dat","a");
fwrite($file,$tk . " " . $ip . "\r\n");
fclose($file);
$oldMessage = $_SESSION["cookie"];
$deletedFormat = "";
$str=file_get_contents('urls.dat');
$str=str_replace("$oldMessage", "$deletedFormat",$str);
file_put_contents('urls.dat', $str);
exit;
} else {
echo ("<title>404 Not Found</title>
<h1>Not Found</h1>The requested URL was not found on this server.
<br>
<br>
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. test");
exit;
}
urls.dat
1089yht
url: http://mmmmmmmmmmmmm.co.uk/url/index.php?key=1089yht
ps. Happy Holidays all!
Look at JSON. You could do something like this:
$tokens = ['foo', 'bar'];
file_put_contents('urls.json', json_encode($tokens));
// and then you can decode it back
// returns ['foo', 'bar']
$decodedTokens = json_decode(file_get_contents('urls.json'));
If you still want to use simple text file, you could save every record at new line and then load line by line.
$tokens = [];
while(! feof($file)) {
$line = fgets($file);
// or save to array
$tokens[] = $line;
}
fclose($file);
try
$str = preg_replace("/{$oldMessage}/", $deletedFormat, $str, 1);
Instead of
$str=str_replace("$oldMessage", "$deletedFormat",$str);
Because: str_replace replaces everything.
preg_replace lets you limit how many replacements.

including leading whitespaces when using fgets in php

I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.
Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.
Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.
Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps
I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).

changing new line to <br> in text area

My problem is pretty simple. I want to change new lines in text area to <br> tags BUT I need the final string to be one-line text. I tried using nl2br function but as a result I get string with <br> tags and new lines. I also tried to simply replace &#013 or &#010 symbols with <br> using str_replace but it doesn't work.
Here is sample of my latest code:
Godziny otwarcia: <textarea name="open" rows="3" cols="20">'."$openh".'</textarea>
<input type="submit" name="openb" value="Zmień"/><br>
if($_POST['openb']) {
$open = $_POST['open'];
str_replace('&#010', '<br>', $open);
change_data(21, $open);
}
The $openh is result of this:
$tab = explode('<br>', $openh);
$openh = null;
for($i=0;$i<count($tab);$i++)
$openh = $openh . $tab[$i] . '&#013';
(yes, I know i could use str_replace, don't ask why I did it this way)
and the original $openh is $openh = 'Pon-pt 9:00-17:00<br>Środa 12:00-17:00'
Also you may want to see my change_data function as it is connected to why i need the string to be in one line, so here it is:
function change_data($des_line, $data) {
$file = 'config.php';
$lines = file($file);
$i=1;
foreach($lines as $line_num => $line) {
$wiersz[$i] = $line;
$i++;
}
$change = explode("'", $wiersz[$des_line]);
$wiersz[$des_line] = $change[0] . "'" . $data . "'" . $change[2];
$i = 1;
$f = fopen($file, w);
while($i <= count($wiersz)) {
fwrite($f, $wiersz[$i]);
$i++;
}
fclose($f);
header('location: index.php?p=admin');
}
I'm not PHP specialist so sometimes I do things little "hard" way.. I had huge problems with reading file config.php line by line and these are results of my few-hours effort :(
have you tried the php constant PHP_EOL? in you str_replace code?
$open=str_replace(PHP_EOL,"<br>",$_POST["open"]);
There is a ready made PHP function for that named nl2br
Source: https://stackoverflow.com/a/16376133/469161

PHP file-writing problems

I have a file called "number.txt"(there is a number inside, e.g.: 0 )
And I want to read the number inside the number.txt and use fwrite to write the number plus 1
(number+1), so that each time anyone visit this webpage, the number will add 1.
but when i test it, it only works at first time(now number.txt is 1).
Then i try another time, the fread function read 0 but not 1.
<?php
$fgc = file_get_contents('number.txt');
settype($cont, "integer");
$cont = $cont + 1;
settype($cont, "string");
file_put_contents('number.txt', $cont);
$str = settype($cont, "string");
$fp = fopen( $str ,'w+');
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
$da = $_GET['data'];
fwrite($fp, $da);
fclose($fp);
?>
And why not to do simple like this:
file_put_contents('numbers.txt', is_writeable('numbers.txt')?((int)file_get_contents('numbers.txt'))+1:exit('Failed to open file'));
Borrowing on Eugene's great one-liner, came up with the following solution.
(Credit goes to go Eugene)
The following code will create the file if it does not exist, and increment by +1 each time it is reloaded.
(Tested)
<?php
$filename = "number.txt";
$filename = fopen($filename, 'a') or die("can't open file");
file_put_contents('number.txt', ((int)file_get_contents('number.txt'))+1);
// To show (echo) the contents of the file, you can use one of the following
// include("number.txt");
// echo file_get_contents('number.txt');
?>
It is because you are setting the write data to the old GET var and not the new set var.
fwrite($fp, $da);
Try using
fwrite($fp, $str);
And also you only need to fopen() once.
$filename = 'number.txt';
$content = (int) file_get_contents($filename);
$content++;
var_dump($content);
file_put_contents($filename, $content);
You have to create that file number.txt and insert there 0 as file content, then your script should work every time.
You are reading the contents into the variable $fgc, but you're trying to use $cont to represent that value, which is uninitialized. So your settype call is going to cast that to 0. Instead, try:
$fgc = file_get_contents('number.txt');
settype($fgc, "integer");

shell_exec not working with dynamic commands

<?php
ini_set('max_execution_time', 864000);
$seq = "D:/Ractip/Sequence.txt";
$mir = "D:/Ractip/mirhominid.txt";
$shandle = fopen($seq, 'r');
$sdata = fread($shandle, filesize($seq));
$mhandle = fopen($mir, 'r');
$mdata = fread($mhandle, filesize($mir));
$sexp = explode(">", $sdata);
$mexp = explode(">", $mdata);
$i = 1;
$a = 1;
$count = count($sexp);
while($i < $count)
{
$name = explode("\n", $mexp[$a]);
$name = explode(" ", $name[0]);
$name1 = explode("\n", $sexp[$i]);
$file2 = "D:\Ractip\mir\\"."$name[1]".".txt";
$file1 = "D:\Ractip\sequence\\"."name1[0]".".txt";
if ($i == 1){
mkdir("D:/Ractip/Interactions/"."$name[1]", 0777);
}
$file = "D:/Ractip/Interactions/"."$name[1]"."/"."$name1[0]"."+"."$name[1]".".txt";
$fhandle = fopen($file, 'w');
$query = "ractip "."$file1"." "."$file2";
$exec = shell_exec($query);
print $exec;
fwrite($fhandle, $exec);
fclose($fhandle);
if ($i == $count){
$i = 1;
$a++;
}else{
$i++;
}
}
?>
This is the script. I am basically using a tool to get results of roughly 37.5 million combinations, so as you can understand it isn't something I can do on my own, therefore came along this script, previously I separated all candidates into individual files and so that is the explanation for the $name variables I'm calling them that way.
The problem is the shell_exec command, a preliminary Google search really did not explain why it is behaving this way, but shell_exec refuses to process dynamic commands, instead if I were to make a static command like ractip xy.txt zy.txt it will process that, what I need to do is build the command and then make the shell_exec process it, which it unfortunately isn't doing, it would be really helpful if someone can explain why this command behaves this way and if there is a workaround to this glitch.
I've finally gotten around to understanding what a guy on a forum meant when he said that these are just some things php doesn't do very well.
Oh yes, and I am deploying it through the browser, dunno if that is any help.
On both Windows and Linux, you'll be better off by keeping all slashes like "/".
Also, looks like you forgot a $ in $file1:
$file2 = "D:/Ractip/mir/" . $name[1] . '.txt';
$file1 = "D:/Ractip/sequence/" . $name1[0] . ".txt";
Finally, just in case, for clarity, I'd write
$query = "ractip '$file1' '$file2'";
or
$query = 'ractip ' . $file1 . ' ' . $file2 ;
You don't really need to quote a single string variable, i.e. $string and "$string" are the same thing. I did quote $file1 and $file2 with single quotes /inside/ $query, because, if the names contain spaces, the ractip utility would get confused as to where one filename stops and another starts. Maybe it's not your case here, but anyway...
What I observed in your code is that in the file names you are passing, the slashes are not properly escaped:
$file2 = "D:\\Ractip\\mir\\"."$name[1]".".txt";
$file1 = "D:\\Ractip\\sequence\\"."name1[0]".".txt";
This might be causing the command to search for a wrong file

Categories