I'm passing a folder name and path via a $_GET. All is fine until I pass a folder name containing and (&) ampersand then the folder name is cut short. i.e folder name test & replace is shorted to 'test '.
Have tried str_repalce, htmlentites, htmlspecialchars
$dir_path = $_GET['path'].$_GET['folder'];
The whole code:
<div class="panel-body" style="font-size:14px">
<?php
if(isset($_GET['path'])){
$dir_path = $_GET['path'].$_GET['folder']."/";
echo "full path = ".$dir_path."<br>folder = ".$Folder;
}else{
$dir_path = PUBLICPATH."/Folderholder/".$branch."/"; // branch url to that branchs folders and in $_GET['folder'];
}
//$dir = opendir($dir_path);
$mappath = str_replace(PUBLICPATH."/Folderholder/","",$dir_path);
echo "<p><i class='fa fa-sitemap'> <b>".$mappath."</b></i></p>\n"; ?>
<div class="row">
<div class="col-md-6">
<?php
echo "<button onclick='goBack()' class='btn btn-primary btn-sm'>Return</button><P>\n";
?>
</div>
<div class="col-md-6">
<?php
if(parent::$UM->get('Level') !== 'User' and $branch !== 'Main-Admin'){
echo "<a href='uploadfrm?path=".$dir_path."' class='btn btn-primary btn-sm'>Upload to this folder</a>";
}elseif(parent::$UM->get('Level') == 'Main-Admin'){
echo "<a href='uploadfrm?path=".$dir_path."' class='btn btn-primary btn-sm'>Upload to this folder</a>";
}
?>
</div>
</div>
<div class="row"><div class="col-md-12"> </div></div>
<table width="70%">
<?php
$files = scandir($dir_path);htmls
foreach ($files as $file)
{
if($file != "." && $file != "..")
{
echo "<tr>\n";
if(is_dir($dir_path.$file)){
echo "<td><i class='fa fa-folder'></i> <a href='".BASEURL."Folderholder/userdash?path=".$dir_path."&folder=".$file."'>$file</a></td>\n";
echo "<td> </td>\n";
}else{
echo "<td><i class='fa fa-download'></i> ".$file."</td>\n<td><a href='http://downloadfolder/download1.php?file=".$dir_path.$file."' target='_Blank'>Download</a></td>\n";
}//change path as required
echo "</tr>\n";
}
}
?>
</table>
</section>
</div>
The & character is used to separate key=value pairs in the query string.
When you generate the query string you should express it as an escape sequence: %26.
How you do that depends on how you are generating the query string in the first place.
You've tagged this php, but the PHP code you have shared is reading the data. You haven't shown us the code for generating it, but assuming that is still PHP:
To generate it in PHP you would normally use http_build_query:
$query = http_build_query(Array( path => "example&example", folder => "example&example" ));
urlencode should do the trick. It is specifically used for passing parameters to a URL to use as variables, as you are doing in your GETs.
Though previous answers in this thread are not incorrect, please also consider using rawurlencode as it will generate a more standards compliant (RFC 3986) URI. urlencode triggers the legacy encoding where spaces are replaced by plus-signs. (Anyone remember that?)
To stop the cut off of the folder name.
Two coding changes $dir_path = $_GET['path'].$_GET['folder']."/"; changed to
$dir_path = $_GET['path'].rawurldecode($_GET['folder'])."/";
and echo "<td><i class='fa fa-folder'></i> <a href='".BASEURL."Folderholder/userdash?path=".$dir_path."&folder=".$file."'>$file</a></td>\n";
changed to
echo "<td><i class='fa fa-folder'></i> <a href='".BASEURL."Folderholder/userdash?path=".$dir_path."&folder=".rawurlencode($file)."'>$file</a></td>\n";
<div class="panel-body" style="font-size:14px">
<?php
if(isset($_GET['path'])){
$dir_path = $_GET['path'].$_GET['folder']."/";
}else{
$dir_path = PUBLICPATH."/Folderholder/".$branch."/"; // branch url to that branchs folders and in $_GET['folder'];
}
//$dir = opendir($dir_path);
$mappath = str_replace(PUBLICPATH."/Folderholder/","",$dir_path);
echo "<p><i class='fa fa-sitemap'> <b>".$mappath."</b></i></p>\n"; ?>
<div class="row">
<div class="col-md-6">
<?php
echo "<button onclick='goBack()' class='btn btn-primary btn-sm'>Return</button><P>\n";
?>
</div>
<div class="col-md-6">
<?php
if(parent::$UM->get('Level') !== 'User' and $branch !== 'Main-Admin'){
echo "<a href='uploadfrm?path=".$dir_path."' class='btn btn-primary btn-sm'>Upload to this folder</a>";
}elseif(parent::$UM->get('Level') == 'Main-Admin'){
echo "<a href='uploadfrm?path=".$dir_path."' class='btn btn-primary btn-sm'>Upload to this folder</a>";
}
?>
</div>
</div>
<div class="row"><div class="col-md-12"> </div></div>
<table width="70%">
<?php
$files = scandir($dir_path);htmls
foreach ($files as $file)
{
if($file != "." && $file != "..")
{
echo "<tr>\n";
if(is_dir($dir_path.$file)){
echo "<td><i class='fa fa-folder'></i> <a href='".BASEURL."Folderholder/userdash?path=".$dir_path."&folder=".$file."'>$file</a></td>\n";
echo "<td> </td>\n";
}else{
echo "<td><i class='fa fa-download'></i> ".$file."</td>\n<td><a href='http://downloadfolder/download1.php?file=".$dir_path.$file."' target='_Blank'>Download</a></td>\n";
}//change path as required
echo "</tr>\n";
}
}
?>
</table>
</section>
</div>
Use urlencode to encode the url like:
$encodedURL = urlencode ('Your url');
Explanation: urlencode will encode the special characters to their entity values and than use it.
Related
I've searched around this site for an answer but couldn't find any help in my problem.
I have a script with a form and I'd like to get the contents of the input written into a txt file (line by line in mytext.txt file for example) when the submit button is pressed - or maybe simpler only the result.
Result / content of "echo $result['text'];" should be saved to text file (mytext.txt)
I tried to add something like that after each "echo" but it doesn't work. here is the sample code.
$f = fopen("mytext.txt", "w");
fwrite($f, $result);
fclose($f);
or
$f = fopen("mytext.txt", "w");
fwrite($f, $username);
fclose($f);
or
$txt = "$result";
$myfile = file_put_contents('mytext.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
but still no luck.
How can I do that and where to add it? With PHP or maybe with JavaScript? Help please.
edit:
PART of the script (I'm sorry I forgot about it)
<?php
if(count($check_ex) == 2){
$ex_name = $check_ex[0]."_".$check_ex[1];
}else{
$ex_name = $check_ex[0];
}
$additional_button = "<a href='javascript:void(0)' onclick='submitform_$dom_$ex_name()' ><button id='buy' class='btn btn-success btn-xs pull-right order-btn'>".__($additional_button_name, 'kate')."</button></a>";
}elseif($integration == 'woocommerce'){
if($show_price){
$show_price = '- '.kate_display_price($username).__('/year','kate');
}
$additional_button = "<a href='?&add-to-cart=$additional_button_link&username=$username' id='buy' class='btn btn-success btn-xs pull-right order-btn' $buy_new_tab >".__($additional_button_name,'kate')." $show_price</a>";
}elseif($integration == 'custom'){
if(!$additional_button_name == '' AND !$additional_button_link == ''){
$additional_button_links = str_replace( '{username}', $username, $additional_button_link );
$additional_button = "<a id='buy' class='btn btn-success btn-xs pull-right order-btn' href='$additional_button_links' $buy_new_tab >".__($additional_button_name,'kate')."</a>";
}else{
$additional_button = '';
}
}else{
$additional_button = '';
}
$custom_not_found_result_text = str_replace( '{username}', $username, $custom_not_found_result_texts );
$whmcs = "<script type='text/javascript'>
function submitform_$dom_$ex_name()
{
document.whmcs_$dom_$ex_name.submit();
}
</script>
<form method='post' name='whmcs_$dom_$ex_name' id='whmcs' action='$additional_button_link/cart.php?a=add&username=register' $buy_new_tab>
<input type='hidden' name='usernames[]' value='$username' >
<input type='hidden' name='usernamesregperiod[$username]' value='1'>
</form>";
if ($available->status == 1) {
$result = array('status'=>1,
'username'=>$username,
'text'=> '<div class="callout callout-success alert-success clearfix available">
<div class="col-xs-10" style="padding-left:1px;text-align:left;">
<i class="glyphicon glyphicon-ok" style="margin-right:1px;"></i> '.__($custom_found_result_text,'kate').' </div>
<div class="col-xs-2" style="padding-right:1px">'.__($additional_button,'kate').' '.$whmcs.'</div>
</div>
');
echo $result['text'];
} elseif($available->status == 0) {
$result = array('status'=>0,
'username'=>$username,
'text'=> '<div class="callout callout-danger alert-danger clearfix not-available">
<div class="col-xs-10" style="padding-left:1px;text-align:left;">
<i class="glyphicon glyphicon-remove" style="margin-right:1px;"></i> '.__($custom_not_found_result_text, 'kate').'
</div>
<div class="col-xs-2" style="padding-right:1px">'.$www_link.'</div>
</div>
');
echo $result['text'];
}elseif ($available->status == 2) {
$result = array('status'=>2,
'username'=> $username,
'text'=> '<div class="callout callout-warning alert-warning clearfix notfound">
<div class="col-xs-10" style="padding-left:1px;text-align:left;">
<i class="glyphicon glyphicon-exclamation-sign" style="margin-right:1px;"></i> '.__('not found','kate').'
</div>
</div>
');
echo $result['text'];
}
}
}
else
{
echo 'Please enter the username';
}
}
If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.
The code is correct, it may be that the directory does not have permission to create files.
You must check if the directory you're trying to save your txt file is writable.
Example:
$contents = 'Here goes your content';
$dirName = __DIR__; //in case you're saving in another directory, you may use 'files/directory/' instead of __DIR__
$fileName = $dirName.'/mytext.txt';
if (!is_writable($dirName)) {
throw new \Exception("This folder is not writable: '$dirName'");
}
//Checks if the content was added
if (!file_put_contents($fileName, $contents)) {
throw new \Exception("Could not write to file: $fileName");
}
I have this code inside a php file:
<?php
function convertToReadableSize($size){
$base = log($size) / log(1024);
$suffix = array("", "KB", "MB", "GB", "TB");
$f_base = floor($base);
return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}
$file_path = 'online_assets/images/';
?>
With a repeating loop displaying every entry:
<?php
$fileSystemIterator = new FilesystemIterator('online_assets/images/');
foreach ($fileSystemIterator as $fileInfo){
$entries[] = $fileInfo->getFilename();
?>
<div class="row">
<div class="col-md-7">
<a href="<?php echo $file_path;?>Room.jpg" target="new">
<img src="/slir/w320-h180-c320x180/<?php echo $file_path;?>Room.jpg" class="img-responsive"/></a>
</div>
<div class="col-md-5">
<h4 class="red"><?php $filename;?></h4>
<p>Filesize: <?php echo convertToReadableSize(filesize($cannery_file_path . 'Room.jpg'));?><br>Format: jpg<br>Quality: <?php list($width, $height) = getimagesize($file_path . 'Room.jpg'); echo ($width) . " x " . ($height); ?></p>
<a href="<?php echo $file_path;?>Room.jpg" target="new">
<button type="button" class="btn btn-primary btn-sm">Download Here</button></a>
</div>
</div>
<?php } ?>
What I am trying to accomplish here is a loop that will return a value essentially foreach image inside the /images/ folder - so all the client has to do is upload images to that folder and they appear, with a thumbnail, file information and a link to download.
I have the rest working, but the loop is giving me some troubles. What am I missing for this?
I picked the code for the FileSystemIterator from the php online manual.
Below is my code for downloading some files from a webpage.
Everything works fine except target="_blank". This button does nothing even though the link is correct. If I right click and press open in a new tab it works but when i press the button it does nothing.
<?php
while ($row = $result->fetch_assoc()) {
$i+=1;
$name = $row["filename"];
$location = "../uploadedfiles/" . $name;
?>
<div class="row">
<p><hr>Name : <?php echo $row["name"] ?> <br> Contact Details : <?php echo $row["number"] ?><br></p>
</div>
<div class="row">
<p>Date Sent: <?php echo date("F d Y-- H:i:s.", filectime($location)) ?><br></p>
</div>
<div class="row">
<p><p> <?php echo $i ?> ) <?php echo substr($name, 10) ?> <a href="../uploadedfiles/<?php echo $name; ?>" target='_blank'><button type='button' class='btn btn-info'>View / Download </button></a></p></p>
</div>
<?php }
?>
<hr>
<?php
} else {
echo "0 results";
}
$con->close();
The way you have created button within the anchor tag is not one of the best practices to be followed.
Ideally you should do something like this:
View/Download
Hope this helps.
Hi guys I have an application that allows users to post content on an empty div. I need some advice on making it scalable as I have to make sure if users are posting a lot of content the browser will not slow down or crash. I am a beginner so please put up with me. So in my code below I have an echo statement that prints out html content. I want to know how to make that function scalable in the long run? should I set the html as a variable then print it? should I encode it with JSON? please advice me as such. Thank-you
PHP Code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if($result) {
} else {
echo "bitch: " . $conn->error;
}
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
echo " <div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b>{$row['username']}</b></span>       <span class='glyphicon glyphicon-time'></span> Posted_on: {$row['time']} </h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>{$row['question']} </h4>
<p> {$row['description']}</p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div> ";
}//end if
}//end while
?>
Did you try to separate the data logic and data display ? if you used php MVC framework which will more convenient on your case.
Following is a simple example.
//demo.html code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if ($result) {
} else {
echo "bitch: " . $conn->error;
}
$time = time();
$data_result = array(); // focus on your data logic process
while ($row = $result->fetch_assoc()) {
if ($time < $row['logged_time'] + 30) {
$data_result[] = $row;
}
}
?>
<?php foreach($data_result as $index => $row) { ?>
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b><?php echo $row['username']?></b></span>
      <span class='glyphicon glyphicon-time'></span> Posted_on: <?php echo $row['time']?>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4><?php echo $row['question']?></h4>
<p> <?php echo $row['description']?></p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
<?php } ?>
It's fine what you're doing.
However as Eric has said you can exit and re-enter your PHP
You could store the html in a file, grab it using file_get_contents then use sprintf to manipulate it
In a file called "row.html"
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'>
<span class='glyphicon glyphicon-user'>
<b>%s</b> <!-- username -->
</span>      
<span class='glyphicon glyphicon-time'>
Posted_on: %s <!-- time -->
</span>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>%s</h4> <!-- question -->
<p> %s</p> <!-- description -->
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
Then in your PHP....
<?php
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
$rowHtml = file_get_contents('row.html');
echo sprintf($rowHtml,
$row['username'],
$row['time'],
$row['question'],
$row['description']);
}
}
?>
I personally like as much abstraction as possible between my languages :)
Good luck!
One way to echo out HTML with PHP is using Heredoc syntax (http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)
<?php
$name = 'MyName';
echo <<<MYHTML
<p>
My name is <b>"$name"</b>.
</p>
MYHTML;
?>
This code is broken because I am nesting php code blocks. What is the proper way to do this?
<?php
if ($prev_ID > $totalRows_totalBoogerRows)
{
echo "";
}
else
{
echo <<<_END
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID=<?php echo $prev_ID; ?>'>
<h4 style='text-align: right;'>Ep. <?php echo $prev_ID; ?>
</h4>
</a>
</div>"
_END;
}
?>
I breaks on line 11 because my closing PHP tag closes the first PHP opening tag on line one (I want it to only close the opening PHP tag on line 11). Also, I may be using <<<_END wrong.
When you are echoing a string that needs php variables inserted, do not open and close php tags but use string concatenation:
<?php
if ($prev_ID > $totalRows_totalBoogerRows)
{
echo "";
}
else
{
echo "
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID=".$prev_ID."'>
<h4 style='text-align: right;'>Ep. ".$prev_ID."</h4>
</a>
</div>";
}
?>
So why don't you use this?
<?php if(something): ?>
HTML
<?php else: ?>
HTML
<?php endif ?>
So:
<?php if ( $prev_ID <= $totalRows_totalBoogerRows ): ?>
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID=<?php echo $prev_ID ?>'>
<h4 style='text-align: right;'>Ep. <?php echo $prev_ID ?></h4>
</a>
</div>
<?php endif ?>
Your heredoc terminating token _END is in wrong place. There must not be any white space before it.
See the warning from PHP.NET manualString.Syntax.Heredoc.
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
Also when you use heredoc the string gets evaluated as double quoted string. So you can use variables inside like this.
echo <<<_END
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID=$prev_ID'>
<h4 style='text-align: right;'>Ep. $prev_ID
</h4>
</a>
</div>
_END;
Just close and reopen PHP tags
<?php
if ($prev_ID > $totalRows_totalBoogerRows)
{
echo "";
}
else
{?>
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID=<?php echo $prev_ID; ?>'>
<h4 style='text-align: right;'>Ep. <?php echo $prev_ID; ?>
</h4>
</a>
</div>
<?php}
?>
try this ,
<?php
if ($prev_ID > $totalRows_totalBoogerRows)
{
echo "";
}
else
{
echo <<<_END
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID='.echo $prev_ID;'>
<h4 style='text-align: right;'>Ep. echo $prev_ID;
</h4>
</a>
</div>"
_END;
}
?>
try this :
if ($prev_ID > $totalRows_totalBoogerRows)
{
echo "";
}
else
{
echo "
<div class='paging_button_left paging_button_left_episode'>
<a href='episode.php?post_ID=\"$prev_ID\"'>
<h4 style='text-align: right;'>Ep. \"$prev_ID\"
</h4>
</a>
</div>
";
}