call php function depending on website section - php

I have a php website thats more or less like this. PHP noob here.
Index.php
<?
include('conexion.php');
include('funciones.php');
?>
<head>
</head>
<body>
<?php
if (!empty($_GET["palabra"])) {
function1($conexion);
} elseif (!empty($_GET["letra"])) {
include('letra.php');
} elseif (!empty($_POST["buscar"])) {
include('search.php');
} else {
function3($conexion);
}
?>
</body>
All functions fuctions and database connections are defined in the included files.
Website uses only a single html file, so all the content is included or called by the functions. Is there a good way for the website to identify which "section" or content is the user browsing?
So, for example I want a function to run only when the user is using the search page, should I continue to use the REQUEST to identify what the user is doing? Should I insert a variable like $section and then if($section=search){dosomething()} or maybe using the URL? should I use another approach?

You want something like this?
PHP Page
<?php
switch ($_GET["page"]) {
case 'login':
# code blocks
break;
case 'student_notes':
# code blocks
break;
default:
# code blocks
break;
}
?>
HTML Page
<form id="form1" name="form1" method="post" action="?page=login">
<p>
<label for="studentCount">Kişi Sayısı</label>
<input type="text" name="studentCount" id="studentCount" />
</p>
<p>
<input type="submit" name="button" id="button" value="Send" />
</p>
</form>
<form id="form1" name="form1" method="post" action="?page=student_notes">
<p>
<label for="studentCount">Kişi Sayısı</label>
<input type="text" name="studentCount" id="studentCount" />
</p>
<p>
<input type="submit" name="button" id="button" value="Send" />
</p>
</form>

I believe you are a little bit confuse about what PHP is and what can do.
PHP will execute in the server, meanwhile HTML execute in the client. Who define how to serve and what are you using the language.
For example:
The user click on an item in a menu, each link in the menu would send a URL to the server in a way like this:
<a href="index.php?page=palabra" >PALABRA</a>
<a href="index.php?page=letra" >LETRA<a>
<a href="index.php?page=buscar" >BUSCAR</a>
All those links will open the same page: INDEX.PHP
Is up to yo to define what to do with the $_GET var sent in the URL.
So, in your index.php you can defined:
<?php
switch ($_GET["page"]) {
case 'palabra':
# code blocks - DO SOMETHING
break;
case 'letra':
# code blocks - SHOW SOMETHING
break;
case 'buscar':
# code blocks - SEARCH SOMETHING
break;
}
?>
In that way who control what to show, and when are you.
Any way, PHP have some globals that will point the name of the script or the page being serve:
Check out https://www.php.net/manual/es/reserved.variables.server.php
I will recomend you research a little bit about php and better try to use a framework like cakePHP, Laravel or Simfony for a start. There are many more.

Related

How to validate two forms at once with php

I have two forms contained in one PHP file. One of the forms is for "log in" and the other form is to "sign up" i have some CSS and JS that will switch out the forms visually, but regardless the two forms are still in one php file.
These forms are standard:
<form action="login.php" method="post" name="user-sign-up">
<div class="error">
<?php if(!empty($error)){echo $error;} ?>
</div>
<span>First name</span>
<input type="text" name="fname" class="fname">
<input type="submit" value="Sign Up" class="signupdawg" id="firstname-signup">
</form>
Then I got another form underneath that one.
Here's my php, it sort of works and only works for one of the forms:
if( isset($_POST['fname']) && !empty($_POST['fname'])){
$upName = $_POST['fname'];
if(empty($upName)){
$error = 'All fields are required';
I only shortened the code, so it wouldn't take up to much space. I had other inputs like a password, but I just removed it because the code is pretty much the same except I had an "or" in my php empty check and a few more lines in my html for it.
Anyway, I am wondering how I can validate two forms at once with PHP.
Thank you.
You can only submit one form at a time, so you need to use something on the form to determine which one was submitted. This is just a simple example using your code:
if(isset($_POST['Sign_Up'])) {
//do sign up stuff
}
elseif(isset($_POST['Login'])) {
//do login stuff
}
Notice Sign Up is converted to Sign_Up. It may be better to use two separate action in each form and have two different files.
Additionally, isset is redundant here:
if( isset($_POST['fname']) && !empty($_POST['fname'])){
The empty already checks if it is set, so just:
if(!empty($_POST['fname'])){
You need to use a unique value on the submit button for each form, an example is below
index.html
<form method="post" ...>
...
<button name="submit" type="submit" value="login">login</button>
</form>
<form method="post" ...>
...
<button name="submit" type="submit" value="sginup">sginup</button>
</form>
PHP file
<?php
if (isset($_POST["submit"])) {
switch ($_POST["submit"]) {
case "login":
login();
break;
case "sginup":
singup();
break;
default:
break;
}
}
?>

After submit redirect to another page not with PHP

I have couple of identical HTML pages which take user input and with PHP I save the input on text files. As it's always the same I would like to apply the same PHP on every html page. So my question is if there is a way to redirect to the next html page but not through PHP, so that the PHP can be reusable for all the pages?
Because if I add onclick="window.location.href='/main2.html' then the PHP is not fired up or if I change action="main2.html" then again the PHP is not included. Or if I add header("Location: main2.html"); then it cannot really be applied to all the html pages, as it goes main.html -> main2.html -> main3.html etc.
HTML 1:
<form method="post" action="process.php">
<input type="text" name="address" required>
<input type="submit" value="Submit" id="intro">
</form>
HTML 2:
<form method="post" action="process.php">
<input type="text" name="address" required>
<input type="submit" value="Submit" >
</form>
PHP:
<?php
$myfile = fopen("text.txt", "a+");
$address = $_POST['address'].";";
fwrite($myfile, $address);
//header("Location: main2.html");
fclose($myfile);
?>
Thank you in advance!
Although you don't want to use PHP, it can make this pretty simple for you. You can use the session variable in PHP to track the user, the entries he has made and even allow them to go back and forward.
You can read more on it here.
You can redirect the user based on the session counter or the source from where the call is made and direct them accordingly to the next page. This makes your code scalable as well.
So you code will be something like this:
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$newURL = "HTMLPage".$_SESSION['counter']."html";
header('Location: '.$newURL);
The above code will redirect the user to the next page. PS: You will have to handle the case for your last html page.

Cannot echo the values from a simple php form

First time i try to create a simple form using the POST method.Problem is when i click the button nothing gets echoed.
here is my insert.php file :
<?php
if(isset($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
?>
<form action="insert.php" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
EDIT: I tried the GET method and it works...Any ideas why that happened? Server configurations?
NEW EDIT: So it turns out i switched method to GET and it worked.Then i switched back to POST (like the code i posted on top) and it works...I have no clue why this happened.Any suggests?
The code you have posted is perfectly valid and should work.
I'm going to guess that you do not have PHP enabled, or it is not working.
<?php ... ?> looks to the browser like a long, malformed HTML tag, and therefore ignores it, making the effect invisible.
Try right-clicking the page and selecting View Source. If you see your PHP there, then the server is indeed not processing it.
The most likely reason for this is probably the same problem I had with my very first bit of PHP code: you're trying to "run" it directly in your browser. This won't work. You need to upload it to a server (or install a server on your computer and call it from there)
Use !empty($_POST['newitem'] instead:
if(!empty($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
empty()
Try the following:
if($_POST) {
if(!empty($_POST['newitem'])) {
$itemnew = $_POSΤ['newitem'];
echo $itemnew;
// or leave it as is: echo $itemnew = $_POSΤ['newitem'];
}
}
?>
<form action="insert.php" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
The if($_POST) will make sure the code is only executed on a post. The empty() function will also check if it isset() but also checks if it is empty or not.
Try this :
<?php
if(isset($_POSΤ["newitem"])){
echo $itemnew = $_POSΤ["newitem"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<input type="text" name="newitem">
<input type="submit" value="Save">
</form>
$_SERVER['PHP_SELF']; is pre-defined variable in php.It allows the user to stay on same page after submitting the form.

Creating a iframe search page for my site

It is very difficult for me to put in words my query. But I will try.
I have a site xyz.com which has search facility for listed products. The search page url is generated like this :www.wyz.com/search/search_term
I want to create a iframe page in a third party site with a search facility which can directly communicated with my site xyz.com.
I have tried to create a search box with a submit button. I want to append the search query in as a variable to my form action url string.
So the search string should look like this :www.wyz.com/search/my_string_variable
The code I have written is:
<?php
$url='http://www.xyz.com/search/';
?>
<?php
if (isset($_POST['submit']))
{
$r1=$_POST['num1'];
}
?>
<?php
$result=$url.$r1
?>
<html><body>
<form action="<?php echo $result; ?>" method="post">
Num1:<input name="num1"><br>
<input type="submit" name="submit">
</form>
</body></html>
==================================================================
But output what I get, is only "http://www.xyz.com/search/". It removes my variable from the url. I am not able to find what is the reason? I have also tried to print result via to check the actual output and it shows that it has added the value at the end of url. But when I want to achieve the same thing via form action it does not work. please help?
<?php
$url='http://www.xyz.com/search/';
?>
<?php
if (isset($_POST['submit']))
{
$r1=$_POST['num1'];
$result=$url.$r1;
header("location:$result");
}
?>
<html><body>
<form action="" method="post">
Num1:<input name="num1"><br>
<input type="submit" name="submit">
</form>
</body></html>
Please try the above code. I have made some modifications. The main reason your code is not working is whenever you press the submit button it is going to the the url "http://www.xyz.com/search/" directly .The if condition is never executed. In the above mentioned code it will work properly
action="" - you are submitting to the wrong url. Here is alternate version -
<?php $url='http://www.xyz.com/search/';
if (isset($_POST['submit'])) {
$r1=$_POST['num1']; header("Location: ".$r1); // 302 redirection
}
?>
<html><body> <form target="_SELF" method="post"> Num1:<input name="num1" type="text" /><br /> <input type="submit" name="submit" /> </form> </body></html>

Html action without referencing a script and referencing a method instead

Normally, when I'm handling forms, in the "action" parameter, I usually have to reference a full PHP script, like this:
<form method="post" action="foo.php"></form>
Is there a way to tell the form to use a function or method rather than having to mention a whole script?
Not that I know of, but I'm pretty sure you could do something like this...
action="foo.php?fromForm=yes"
Then in your php code, you could have this...
if($_GET['fromForm'] == "yes") {
//put your function here, or call it here
}
else {
//rest of code goes here
}
imagining that your form looked something like:
<form name="form1" method="post" action="">
<p>
<label></label>
<input type="text" name="textfield" id="textfield" />
</p>
<p>
<label></label>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
then you could just put at the top of the php:
if (isset($_POST['textfield'])) {
foo();
}
replacing foo(); with the name of the function you want to execute.
This simply checks if there was any form data posted to the page with name="textfield".
No. What you're specifying is not a script, it's a URL. HTML/the browser doesn't know about server-side functions or methods, only about URLs.
You can use the onsubmit attribute to call a javascript method instead:
<form method="post" onsubmit="doSomething()"></form>
You can also use this to validate your form before passing it to a script such as the following:
<form method="post" action="foo.php" onsubmit="canSubmit()"></form>
NOTE: I'm assuming you're asking if you can access a method or function in the PHP code on the server-side, not call a JavaScript function on the client-side!
The client side cannot arbitrarily invoke methods on the server side. The URL or path to the resource, is what is used to identify a resource on the server.
If you want to perform different functionality in the same script, you could use if/else blocking and use query parameters to differentiate your URLs.
HTML:
<form method="post" action="foo.php?method=saveData"></form>
PHP:
<? /* foo.php */
if($_REQUEST['method'] == "saveData") {
// do stuff
} else if($_REQUEST['method'] == "doSomethingElse") {
// do other stuff
}
?>
This is at it's core a very basic example. For more complex needs, many frameworks can perform this level of branching, out of the box, and with much more sophistication.
If your PHP script is written as follows:
<?php
switch ($_GET ['f']) {
case 'do_one':
// do something
break;
case 'do_two':
// or use a callback
do_two_callback ();
break;
default:
// ...
}
?>
... you can always do this
<form method="post" action="foo.php?f=do_one"></form>

Categories