I have a form on my site where users can enter links to articles
So far... when a link is submitted, I am able to get that link to post to a destination html page.
However... if another link is submitted, it deletes the first one.
I would like the links to 'stack' and make a list to the destination (directory) page (which is currently an html page).
I don't know how to achieve this. Any advice or examples would be greatly appreciated.
I have include a very stripped down version of all three pages....
1.) The Form
<!DOCTYPE html>
<html>
<head>
<title>FORM</title>
<style>
body{margin-top:20px; margin-left:20px;}
.fieldHeader{font-family:Arial, Helvetica, sans-serif; font-size:12pt;}
.articleURL{margin-top:10px; width:700px; height:25px;}
.btnWrap{margin-top:20px;}
.postButton{cursor:pointer;}
</style>
</head>
<body>
<form action="urlUpload.php" method="post" enctype="multipart/form-data">
<div class="fieldHeader">Enter Article Link:</div>
<input class="articleURL" id="articleURL" name="articleURL" autocomplete="off">
<div class="btnWrap"><input class="postButton" type="submit" name="submit" value="POST"></button></div>
</form>
</body>
</html>
The Upload PHP (buffer) Page
<?php ob_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>urlUpload</title>
<style>body{margin-top:20px; margin-left:20px;}</style>
</head>
<body>
<?php $articleURL = htmlspecialchars($_POST['articleURL']); echo $articleURL;?>
</body>
</html>
<?php echo ''; file_put_contents("urlDirectory.html", ob_get_contents()); ?>
3.) The Destination HTML 'Directory List' page
<!DOCTYPE html>
<html>
<head>
<title>urlDirectory</title>
<style>body{margin-top:20px; margin-left:20px;}</style>
</head>
<body>
Sumbitted URL's should be listed here:
</body>
</html>
PS: I may not even need the middle php 'buffer' page. My knowledge of this sort of thing is limited thus far. If I don't need that, and can skip that page to accomplish my needs, please advise as well.
You can do this by using PHP to write the file and using urlDirectory.html as a template. You will just need to change your php file:
urlUpload.php
<?php
function saveUrl($url, $template, $tag)
{
// If template is invalid, return
if (!file_exists($template)) {
return false;
}
// Remove whitespace from URL
$url = trim($url);
// Ignore invalid urls
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return true;
}
// Read template into array
$html = file($template);
foreach ($html as &$line) {
// Look for the tag, we will add our new URL directly before this tag, use
// preg_match incase the tag is preceded or followed by some other text
if (preg_match("/(.*)?(" . preg_quote($tag, '/') . ")(.*)?/", $line, $matches)) {
// Create line for URL
$urlLine = '<p>' . htmlspecialchars($_POST['articleURL']) . '</p>' . PHP_EOL;
// Handle lines that just contain body and lines that have text before body
$line = $matches[1] == $tag ? $urlLine . $matches[1] : $matches[1] . $urlLine . $matches[2];
// If we have text after body add that too
if (isset($matches[3])) {
$line .= $matches[3];
}
// Don't process any more lines
break;
}
}
// Save file
return file_put_contents($template, implode('', $html));
}
$template = 'urlDirectory.html';
$result = saveUrl($_POST['articleURL'], $template, '</body>');
// Output to browser
echo $result ? file_get_contents($template) : 'Template error';
Related
I'm creating a web app where I want to include JavaScript files with all file sources in an array, but I can't do that.
Header.php
<head>
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
Index.php
<?php
include('header.php');
array_push($import_scripts,'file03.js')
?>
But this only includes file01.js and file02.js, JavaScript files.
Your issue is that you've already echo'ed the scripts in headers.php by the time you push the new value into the array in index.php. So you need to add to extra scripts before you include headers.php. Here's one way to do it (using the null coalescing operator to prevent errors when $extra_scripts is not set):
header.php
<?php
$import_scripts = array_merge(array(
'file01.js',
'file02.js'
), $extra_scripts ?? []);
?>
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>' . PHP_EOL;
}
?><title>Demo</title>
</head>
<body>
<p>Blog</p>
index.php
<?php
$extra_scripts = ['file03.js'];
include 'header.php';
?>
Output (demo on 3v4l.org)
<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
<script src="file01.js"></script>
<script src="file02.js"></script>
<script src="file03.js"></script>
<title>Demo</title>
</head>
<body>
<p>Blog</p>
header.php
<?php
function scripts()
{
return [
'file01.js',
'file02.js'
];
}
function render($scripts)
{
foreach ($scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
}
?>
<head>
index.php:
<?php
include 'header.php';
$extra_scripts = scripts();
$extra_scripts[] = 'script3.js';
render($extra_scripts);
?>
</head>
<body>
PHP is processed top down so it will currently be adding file03.js to the array after the foreach has been run.
This means you have two options:
Run the scripts after the header (Not reccomended)
Like Nick suggested, in index.php, specify additional scripts before the header is called
Other answers have answered why (you output content before adding the item to the array).
The best solution is to do all your processing before your output. Also helps with error trapping, error reporting, debugging, access control, redirect control, handling posts... as well as changes like this.
Solution 1: Use a template engine.
This may be more complex than you need, and/or add bloat. I use Twig, have used Smarty (but their site is now filled with Casino ads, so that's a concern), or others built into frameworks. Google "PHP Template engine" for examples.
Solution 2: Create yourself a quick class that does the output. Here's a rough, (untested - you will need to debug it and expand it) example.
class Page
{
private string $title = 'PageTitle';
private array $importScripts = [];
private string $bodyContent = '';
public setTitle(string $title): void
{
$this->title = $title;
}
public addImportScript(string $importScript): void
{
$this->importScripts[] = $importScript;
}
public addContent(string $htmlSafeBodyContent): void
{
$this->bodyContent .= $bodyContent;
}
public out(): void
{
echo '<!DOCTYPE html>
<html>
<head>
<!-- Scripts Section -->
';
foreach ($this->importScripts as $script) {
echo '<script src="' . htmlspecialchars($script) . '"></script>' . PHP_EOL;
}
echo '
<!-- End Scripts Section -->
<title>' . htmlspecialchars($this->title) . '</title>
</head>
<body> . $this->bodyContent . '
</body>
</html>';
exit();
}
}
// Usage
$page = new page();
$page->setTitle('My Page Title'); // Optional
$page->addImportScript('script1');
$page->addImportScript('script2');
$page->addContent('<h1>Welcome</h1>');
// Do your processing here
$page->addContent('<div>Here are the results</div>');
$page->addImportScript('script3');
// Output
$page->out();
I'd create a new php file, say functions.php and add the following code into it.
<?php
// script common for all pages.
$pageScripts = [
'common_1.js',
'common_2.js',
];
function addScripts(array $scripts = []) {
global $pageScripts;
if (!empty ($scripts)) { // if there are new scripts to be added, add it to the array.
$pageScripts = array_merge($pageScripts, $scripts);
}
return;
}
function jsScripts() {
global $pageScripts;
$scriptPath = './scripts/'; // assume all scripts are saved in the `scripts` directory.
foreach ($pageScripts as $script) {
// to make sure correct path is used
if (stripos($script, $scriptPath) !== 0) {
$script = $scriptPath . ltrim($script, '/');
}
echo '<script src="' . $script .'" type="text/javascript">' . PHP_EOL;
}
return;
}
Then change your header.php as
<?php
include_once './functions.php';
// REST of your `header.php`
// insert your script files where you needed.
jsScripts();
// REST of your `header.php`
Now, you can use this in different pages like
E.g. page_1.php
<?php
include_once './functions.php';
addScripts([
'page_1_custom.js',
'page_1_custom_2.js',
]);
// include the header
include_once('./header.php');
page_2.php
<?php
include_once './functions.php';
addScripts([
'./scripts/page_2_custom.js',
'./scripts/page_2_custom_2.js',
]);
// include the header
include_once('./header.php');
You are adding 'file03.js' to $import_scripts after including 'header.php', so echoing scripts it have been done yet. That's why 'file03.js' is not invoked.
So, you need to add 'file03.js' to $import_scripts before echoing scripts, this means before include 'header.php'.
A nice way is to move $import_scripts definition to index.php, and add 'file03.js' before including 'header.php'.
But it seems that you want to invoke certain JS scripts always, and add some more in some pages. In this case, a good idea is to define $import_scripts in a PHP file we can call init.php.
This solution will be as shown:
header.php
<head>
<?php
foreach ($import_scripts as $script) {
echo '<script src="' . $script . '"></script>';
}
?>
</head>
<body>
init.php
<?php
$import_scripts = array(
'file01.js',
'file02.js'
);
index.php
<?php
require 'init.php';
array_push($import_scripts,'file03.js');
include 'header.php';
header.php
<?php
echo "<head>";
$importScripts = ['file01.js','file02.js'];
foreach ($importScripts as $script) {
echo '<script src="' . $script . '"></script>';
}
echo "</head>";
echo "<body>";
index.php
<?php
include 'header.php';
array_push($importScripts, 'file03.js');
print_r($importScripts);
Output
Array ( [0] => file01.js [1] => file02.js [2] => file03.js )
im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>
I am trying to remove script tags from HTML using PHP but it doesn't work if there's HTML inside the javascript.
For example, if the script tags contain something like this:
function tip(content) {
$('<div id="tip">' + content + '</div>').css
It will stop at </div> and the rest of the script will still be taken into account.
This is what I have been using to remove the script tags:
foreach ($doc->getElementsByTagName('script') as $node)
{
$node->parentNode->removeChild($node);
}
How about some regex-based pre-processing?
Example input.html:
<html>
<head>
<title>My example</title>
</head>
<body>
<h1>Test</h1>
<div id="foo"> </div>
<script type="text/javascript">
document.getElementById('foo').innerHTML = '<span style="color:red;">Hello World!</span>';
</script>
</body>
</html>
Script tag removing php script:
<?php
// unformatted source output:
header("Content-Type: text/plain");
// read the example input file given above into a string:
$input = file_get_contents('input.html');
echo "Before:\r\n";
echo $input;
echo "\r\n\r\n-----------------------\r\n\r\n";
// replace script tags including their contents by ""
$output = preg_replace("~<script[^<>]*>.*</script>~Uis", "", $input);
echo "After:\r\n";
echo $output;
echo "\r\n\r\n-----------------------\r\n\r\n";
?>
You can use strip_tags function. In which you can allow the HTML attributes which you want allowed.
I think this is 'here and now' problem, and you need no something special. Just do something like this:
$text = file_get_content('index.html');
while(mb_strpos($text, '<script') != false) {
$startPosition = mb_strpos($text, '<script');
$endPosition = mb_strpos($text, '</script>');
$text = mb_substr($text, 0, $startPosition).mb_substr($text, $endPosition + 7, mb_strlen($text));
}
echo $text;
Only set encoding for 'mb_' like functions
Is there any php code i can use to click a link or process a form on the page the php is on?
Im building a redirect script and what i need to do is use php to move user to next page, its mandatory that php has to be used html doesnt work. In it i have a self submit forum but it doesnt work how i load the script. Is there a way i can use php code to submit it? or remove it and put a link there then use php to click that link?
This is the code below:
if ($_GET['ref_spoof'] != NULL)
{
$offer = urldecode($_GET['ref_spoof']);
$p1 = strpos ($offer, '?') + 1;
$url_par = substr ($offer , $p1);
$paryval = split ('&', $url_par);
$p = array();
foreach ($paryval as $value)
{
$p[] = split ('=',$value);
}
//header('Location: '.$offer.'') ;
print
'
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">$("#mylink").click()</script>
Index Page
<script type="text/javascript">$("#mylink").click()</script>
<script type="text/javascript">document.getElementById("myLink").click();</script>
<form action="'.$offer.'" method="get" id="myform">
';
foreach ($p as $value)
{
echo '<input type="hidden" name="'.$value[0].'" value="'.$value[1].'">';
}
echo '</form><script language="JavaScript"> document.getElementById(\'myform\').submit();</script></body></html>';
}
Looks like you're trying to make this too complicated.
You're loading a page that submits a form using GET.
Is there any reason you can't use
header("Location : ".$offer."?".http_build_query($p));
http_build_query being a function to generate an URL string from an array. Assuming $p is the array containing all form fieldnames+values.
example of http_build_query:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data);
will result in:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
I am trying to get the title element's content that is contained in a echo statement of a PHP file.
I am using a PHP file for a website that when accessed by a Ajax call it returns only part of the page, but when accessed directly it returns the entire page.
That much is working fine. But I would like to change the title of the page when it is accessed via the Ajax call, the innerHTML of the title tag is what I'm trying to get.
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo '
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Products at Avrent</title>
<meta http-equiv="content-type" content="text/htmlcharset=utf-8" />
With a HTML file this code works.
<?php
if(isset($_GET['url'])) {
$url = $_GET['url'];
$html = file_get_html($url);
/* get page's title */
preg_match("/<title>(.+)<\/title>/siU", $html, $matches);
$title = $matches[1];
echo $title;
}
?>
But it returns gibberish when I try using it with a PHP file.
Can someone help me find a PHP script that will work on a PHP file?
Here's what I've gathered: you have a bunch of HTML pages. You have an index.php script that takes a URL, loads up the HTML from that URL, swaps out the title, then spits the HTML back out?
First of all, why do you have things set up like that? If you insist...
You (at the very least) should do this:
index.php
Remove the RegEx. You're using an HTML parser; use that!
<?php
if(isset($_GET['url'])) {
$url = $_GET['url'];
$html = file_get_html($url);
/* get page's title */
$title = $html->find('title', 0)->innertext;
echo $title;
}
?>
ajax_page.php
Set title from variable.
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo '
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>' . $page_title . '</title>
<meta http-equiv="content-type" content="text/htmlcharset=utf-8" />
Then, from index.php:
$page_title = "INSERT THE PAGE TITLE HERE";
require "ajax_page.php";