PHP to html template without template manager - php

Here I am again... I've been watching some tutorials and I'm now in good way on php programing...
What I want to know is: with a template manager like for example smarty, you can make 1 php page with the code and redirect it to the view html file... something like this on the php...
$a = new Trabalhos();
$id = new Users();
$sm->assign("id", $a->select());
if (isset($_GET['del'])) {
$a->setId($_GET['del']);
$a->delete();
}
if (isset($_POST['id'])
and isset ($_POST['trolha'])
and isset($_POST['padeiro'])
and isset($_POST['arquitecto'])
and isset($_POST['engenheiro'])
and isset($_POST['medico'])
and ! isset($_GET['edit'])) {
$a->setId($_POST['id']);
$a->setTrolha($_POST['trolha']);
$a->setPadeiro($_POST['padeiro']);
$a->setArquitecto($_POST['arquitecto']);
$a->setEngenheiro($_POST['engenheiro']);
$a->setMedico($_POST['medico']);
$a->insert();
}
$lista = $a->select();
$sm->assign("lista", $lista);
$sm->display("trabalhos.html");
Then I make the view page in trabalhos.html and I put this:
<form method="post">
| id <select name ="id">
{foreach from=$id item=d}
<option value ="{$d.id}">{$d.id}</option>
{/foreach}
</select>
| Trolha <input name ="trolha" type="text" />
| Padeiro <input name ="padeiro" type="text" />
| Arquitecto <input name ="arquitecto" type="text" />
| Engenheiro <input name ="engenheiro" type="text" />
| Medico <input name ="medico" type="text" />
<input type="submit" value="Guardar"/>
</form><br>
<table border="1">
<tr>
<td>ID</td>
<td>Trolha</td>
<td>Padeiro</td>
<td>Arquitecto</td>
<td>Engenheiro</td>
<td>Medico</td>
<td>Acoes</td>
</tr>
{foreach from = $lista item = row}
<tr>
<td>{$row.id}</td>
<td>{$row.trolha}</td>
<td>{$row.padeiro}</td>
<td>{$row.arquitecto}</td>
<td>{$row.engenheiro}</td>
<td>{$row.medico}</td>
<td>Edit | <a href="?del={$row.id}">Delete</td>
</tr>
{/foreach}
</table>
OK till there I get it and I make it work with the help of the tutorial and giving my variables
Now what I really want to know is how can I do the same without the help of external template managers, everyone will say that is easier with this and that, but I'm looking to learn php, not to run pre-made scripts, if you know what I mean
Right now I don't trust on external code... to trust it I need to understand it
So if they made it work with smarty I have to make it work by myself right?
Is there need of other languages out of php to do it? like java or something similar?
Or can I do it just with php and html coding?
If is possible to do it just with php and html coding can anyone tell me for example how will I make that column with the foreach php function work? And how do I transmit to the html the variables info?
Really sorry for that huge post, but I didn't see anything like what I'm asking in here and on google i just see people and forums talking about template managers, and that's not what I'm looking for ;)
Thank you very much for the answers last post got a positive one ;)

Trying to write your own template engine is a hard task. But you can do it in plain PHP, not need for other language.
Basically, your template engine will need 2 things in order to work:
Templates. Your trabalhos.html file is a template. It's a HTML file that contains special placeholders (like {$d.id}) that have a particular meaning for your template engine.
Variables. If you want to do something useful with your templates, you must provides variables to work with (this is what you do with an instruction like this $a->setId($_POST['id']);).
Now what you need to do is write some code that is able to parse your template files (recognize the placeholders you defined) and work with them. This is quite easy to do if you only need to replace placeholders with the value of a variable but will get tricky as soon as you start to implement features a little more complex like loops.
In addition to that, you also need to write some code that enables you to bind values to your variables as well as objects to store these.
This is a huge job but if your aim is to learn PHP, it's a really good way. Good luck!

You can use file write function.
$file = fopen("trabalhos.html","w");
fwrite($file,$lista);
fclose($file);

Related

How to access the variable values from URL in smarty template?

I'm using PHP and smarty for my website. I'm getting a URL in address bar and I want to use the values from URL into smaarty template. So is it possible to do that? If yes can you explain? For your understanding I'm giving you the URL as follows:
http://localhost/eprime/entprm/web/control/modules/enquiries/manage_contact_us.php?contact_id=56&contact_full_name=ZainabJuzerBhavnagarwala&contact_email_id=fatemabhav21#gmail.com&op=view&reply_to_enquiry_suc=1&from_date=11/09/2000&to_date=11/09/2013
Suppose from the above URL I want to access the values of variables contact_full_name and contact_email_id in my smarty template which is currently being displaed. Can you explain me how could I achieve this?
Actually I tried the following code but it didn't output anything.
<input type="text" name="contact_full_name" id="contact_full_name" value="{ if $data.contact_full_name!=''} {$data.contact_full_name|capitalize} {else} {$contact_full_name|capitalize} {/if}" class="">
Thanks in advance.
Look at smarty reserved variables :
{$smarty.get.contact_email_id}
Look at smarty reserved variables :
{$smarty.get.contact_email_id}
Since Smarty will output the contents of the variable, if present and nothing if it isn't, then you should just:-
<input type="text" name="contact_full_name" id="contact_full_name" value="{$smarty.get.contact_full_name|capitalize}" class="" />
(anyone can copy and paste LOL)
and per previous answer:
adding $smarty->debugging_ctrl='URL'; to your php script and &SMARTY_DEBUG to the URL will popup your assigned variables (but not get and post)

Allow a user to edit a php code and submit the results securely

Is there a way to allow user to edit a php code securely, for example this is a basic php code to echo
Hello World! onto the page.
The idea is not to allow full coding changes just things like the array or they could edit a date in mktime things like that. I thought there maybe a way to echo form input fields into a php code which will then display the results.
How could i go about allowing a user to edit the code changing (Hello World!) to something else and then click submit to display there edit.
<?php
echo "Hello World!";
?>
or another example would be how can the user edit the words in the array
<?php
$words = array("the ", "quick ", "brown ", "fox ",
"jumped ", "over ", "the ", "lazy ", "dog ");
shuffle($words);
foreach ($words as $word) {
echo $word;
};
unset($word);
?>
I presume that i would have to create a form which gets the php code and somehow get it to display the edited results?
<form name="form" method ="get" action="a.php">
<input type="text" id="edit" name="edit" size="30" />
<input type="submit" value="Submit" >
</form>
For anyone that is viewing this and would like to know what you can create using a form and php see here Form that edits php script
What you are trying to accomplish is what variables are for.
Taking this example:
echo "Hello World!";
You could change that to
echo $_POST["data"];
and in your html
<form type='post'>
<input type='text' name='data'/>
<input type='submit'/>
</form>
See it in action
Eval should be avoided at all costs, there is a very narrow set of problems where using eval is a sane solution.
You want people to run arbitrary PHP code, but not all arbitrary PHP code. Tough thing to get right.
First off do not just eval() form data. Only bad* can come of this.
<form method="POST">
<textarea name="php"></textarea>
<button type="submit">Run</button>
</form>
<pre>
<?= eval($_POST['php']) ?>
</pre>
One option that comes to mind is to use https://github.com/nikic/PHP-Parser.
Basically, the parser does nothing more than turn some PHP code into an abstract syntax tree. ("nothing more" is kind of sarcastic here as PHP has a ... uhm, let's just say "not nice" ... grammar, which makes parsing PHP very hard.)
You can then walk the AST and remove suspect expressions, reconstitute the tree to code, and then call eval() on it.
Outside of that, configuring a sandbox environment would be critical here, as nothing is foolproof. That way, when someone inevitably bricks the box, you can recover it.
php.ini configuration changes can make for a "safer" environment to execute arbitrary code by imposing restrictions. disable_functions and disable_classes can help limit the possible abuse. Setting a low memory_limit will prevent help reduce excessive resource slurping.
* Unless this is a social experiment to see how long it takes for someone to turn your machine into pudding
in THEORY you can do something like this, but PLEASE PLEASE PLEASE don't do it because it is extremely UNSECURE
<?php
if (isset($_REQUEST['do_eval'])){
eval($_REQUEST['to_eval']);
}
?>
<form action="eval.php">
<textarea name="to_eval" rows="20" cols="80"><?php if (isset($_REQUEST['eval'])) print($_REQUEST['eval']); ?></textarea>
<br />
<input type="submit" name="do_eval" value="Submit" />
</form>
if I get you right, then eval function is what you need (http://php.net/manual/en/function.eval.php)
Evaluates the given code as PHP.
Although it is very dangerous as a user can execute a destructive code or output some private data.
<?
if(isset($_POST['submit'])
{
eval($_POST['code']);
}
else
{
?>
<form method="POST">
<textarea name="code"></textarea>
<input type="submit" value="Submit"></form>
</form>
<?
}
This sounds extremely dangerous to me; since PHP code runs on the server, you are basically letting anyone and everyone tell your server what code to run, and telling it to run harmful code would be very easy. Unfortunately, I can't think of a trivial way to sanitize this type of input.
Having said that... you can have a form that submits the user's code to a page that can write that code into a .php file on your server, then redirects to the newly created .php file. But, again, I would not advise you to do this sort of thing.
I think I understand what you're trying to accomplish. The actual task I believe will require a large amount of javascript in association with your PHP.
So, let's run it down theoretically.
Let's say this is your start code:
$array = array('one', 'two', 'three');
var_dump($array);
Ok - so now you want to define that the user can modify the array. Your HTML now looks something like that code above - all escaped of course.
However, you put form element around the escaped content, and put each array element as an input field.
So, you'll end up with something like this: (Note this is HTML not PHP)
<form action="self.php">
<div>$array = array(</div>
<span>'<input name="arrayValue[]">, +</span>
<div>);<br>var_dump($array);</div>
<input type="submit" value="Process this code">
</form>
Now, you'll need to write some javascript that watches for the class 'addAnother' to be clicked. If so, it goes up to its parent element and clones it (see - that's the span) and adds it after the parent. This way you'll have another whole line that is that span - with another input.
If you style the inputs to look nice, you can make it look like the user is typing inline.
Once the submit is pressed, the values are sent to the PHP. Then, the PHP will create a new array from all of $_POST['arrayValue'];
Your actual code will do this:
$array = $_POST['arrayValue'];
var_dump($array);
And then, you'll rerender the HTML again.
I know this is all 'theory' - there's a bit more code to actually be written.
I honestly would re-think if you really want to take on this task - this is a LOT of work to do it in an interactive, secure way. Perhaps there are other ways to accomplish your core task. Best of luck!

Validate empty input field as the correct value in smarty

<td><input type="text" name="remove" value="Remove this text"></td>
How can i use smarty validation directly in my template file. The correct value for the textbox is empty.
I'm trying to avoid using Javascript, and I know I can do it either in the template file or the PHP. I haven't seen any real good examples of this.
I'm confused, and I would appreciate some help.
You can not validate anything using smarty. Smarty is for templating, that means: Smarty is there for generating output solely.
If you want to check if that element is empty, you have to rely on javascript or your server-sided language, e.g. PHP.
The only way to to anything roughly in your direction with smarty would be like this:
<td>
{if $element_not_empty}<div class="error">Please remove the text!</div>{/if}
<input type="text" name="remove" value="Remove this text">
</td>
But, of course, the variable $element_not_empty would be generated by PHP so there you are at server-sided validation again ;)

How to set a value of input type after it was created

I have a basic question which I cant find an answer to.
i have an input text
I want to change the value by1 every time i click the button.
so, when I make a new soldier, i want it to be shown in the soldiers count.
I started programming in PhP recently.
In Java, command Im looking for would be some setText or something like that.
Here's the basic idea:
You specifically mentioned PHP so I'll give you a PHP example:
This is at the top of every page you want the form on...
<?php
session_start();
if(!isset($_SESSION['soldiers']))
$_SESSION['soldiers'] = 0;
include('form_process.php');
Then in form_process.php:
<?php
if(isset($_POST['soldiers']) && is_numeric($_POST['soldiers']))
{
if($_POST['soldiers'] == $_SESSION['soldiers'])
$_SESSION['soldiers'] ++;
else
$_SESSION['soldiers'] = $_POST['soldiers'];
}
?>
<form id="soldiers" action="" method="post">
<input type="text" name="soldiers" value="<?php echo $_SESSION['soldiers']; ?>">
<input type="submit" name="submit" value="submit">
</form>
I would do this in html and jquery personally, but you asked for PHP so here you go.
Why use sessions? Cause you said the form is on every page so you need to maintain a constant number throughout the session. Better to use a database so the number is constant across all people who may be viewing the site, but you didn't specify that in your question.
I myself don't know what value something like this could be in the state it is in. To me it sounds like you wanted a javascript type way to just update the html of an element on click, which makes a little more sense than incrementing an input value the user can just manually overwrite to begin with. But hey, the beauty of programming is it never needs to make sense to anybody per say, so long as you get whatever you want out of it.

Get certain content from a html page

When I press 'View source code' of a certain web page, it's kind of like this:
<form action="/WANem/index-advanced.php" method="post">
<table border="1" width="100%">
<tr>
<td width="10%" >Delay time(ms) </td>
<td width="10%" ><input type="text" name="txtDelay1" size="7" value=1200>
</td>
<input type="submit" value="Apply settings" name="btnApply">
</table>
</form>
My question is: How can i get '1200' in the code using PHP.
I mean i just want to get a certain string in the html code of another website without having to press 'view source code' and copy that string.
Thanks for any reply.
What you're trying to do is called "web scraping".
Here's a StackOverflow question with a bunch of helpful answers:
How to implement a web scraper in PHP?
And here is a tutorial that probably explains it better than I could by typing it out here:
http://www.thefutureoftheweb.com/blog/web-scrape-with-php-tutorial
Hope it helps and good luck!
In your php file it is something as simple as this:
$value = $_POST['txtDelay1'];
Although, it looks as a really basic question. I suggest you to go through some tutorials, to get the idea on how it all works.
First on in google php form tutorial: http://www.phpf1.com/tutorial/php-form.html
EDIT:
Oh, now i see your edits. In that case, you can't skip sending a http request to get the source code, just like a browser does. Next, you have to parse the response from the server, just like a browser does as well. Ah, The response will be the "Source code" you're asking for. If you can, consider using python to this. It will be much more faster and efficient.
If PHP is a must, be aware that this task is a pain in the ass;)
You can do this with file_get_contents() and preg_match().
//$url is whatever your URL is
$url = file_get_contents($url);
preg_match('|name="txtDelay1".*?value=([\d]+)|', $html, $html);
echo $html[1];
//should print your value 1200
Check out the regex here.
However
This is only going to work as long as this code appears exactly and is not duplicated. Also, if you are scraping from another site, it could be changed by the owner, and the regex would no longer work.

Categories