I have several links on a page, all of which need to execute a different method in PHP.
A link for "Create File", one for "Rename File" and one for "Delete file".
The only way I know of to execute PHP code with each hyperlink is by giving the URL of a different PHP file to each hyperlink.
Is there a way to link the URL (HREF) to a SPECIFIC method in a PHP file?
Here are a few lines of code that do not work, but might help you understand what I want to achieve:
Create File
Rename File
Rename File
I'm also pretty sure I'm taking the wrong approach, but I'm too much of a PHP novice to know better :)
Common approach in your situation would be setting a GET parameter called something like fileAction and then switching it's value, so your links would look like this:
Create File
Rename File
Delete File
And your filemanagement.php logiŃ would look somewhat like this:
<?php
$fileAction = $_GET['fileAction'];
switch ($fileAction) {
case 'create':
createFile();
break;
case 'rename':
renameFile();
break;
case 'delete':
deleteFile();
break;
default:
//your default logic here
break;
}
?>
you can send the method name as a $_GET value and execute the corresponding function, like so:
HTML:
Run some method
PHP:
<?php
if (isset($_GET['method'])) {
$method = $_GET['method'];
$method();
}
<?php
#$Method = $_GET['Method'];
if (!(isset($Method)))
{
$Method = "0"; // If URL does not contain ?Method=1 Then Assign It To 0
}
if ($Method > "3")
{
$Method = "0";
// If ?Method= value is higher than 3 Then Set it to 0
}
if ($Method == "0")
{
echo "Create File";
echo "Rename File";
echo "Delete File";
}
elseif ($Method == "1")
{
// Method = 1 Is Create File So:
// CreateFile();
}
elseif ($Method == "2")
{
// Method 2 is Rename File
// renameFile();
}
elseif ($Method == "3")
{
// Method 3 Is Delete File
// deleteFile();
}
?>
What you are describing is the perfect scenario for using an MVC framework. There are tons of these frameworks out there and they help you in organising your code better. If you are just starting out in PHP, I highly suggest you to look at a framework and some code samples on the web in order to get your head around the MVC principle.
When using an MVC framework, you simply define routes which map to a particular function (action) in a particular class (controller). I won't get too far in this answer, but I suggest you go through these ressources to get you started :
MVC definition on Wikipedia
CodeIgniter, an MVC framework for PHP
Related
I'm working with a page that, once a link is called this script checks and if the POST contains the keyword it and then finds that page. However no matter how I organize this if it doesn't work.
<?PHP
if($_POST['page']) {
$page = (int)$_POST['page'];
$exists = file_exists('pages/page_'.$page.'html');
if($exists) {
echo file_get_contexnts('pages/page_'.$page.'html');
} else {
echo 'There is no such page!';
}
} else if ($_POST['course']) die("0"); {
$course = (int)$_POST['course'];
$exists = file_exists('courses/course_'.$course.'html');
if($exists) {
echo file_get_contexnts('courses/course_'.$course.'html');
die("1");
} else {
echo 'There is no such page!';
}
}
?>
The error I'm currently receiving with this setup is:
Notice: Undefined index: course in C:\wamp\www\Home Page\load_page.php on line 12
Call Stack
# Time Memory Function Location
1 0.0003 253944 {main}( ) ..\load_page.php:0
Is it because there is no 'course' in the page? I might be confused of the code I'm modifying a tutorial of a simple ajax website. It is possible what I am trying to do does not work.
In that case how could I possible go about doing what I want to do.
Right now I have a home page and it loads in another page without switching pages. I like the floridness of it. I would like to have a sort of sub call. So if you are on the home page and you go to courses page then you can click on a specific course and that will load from a different directory within the courses directory.
Homepage (when you click on courses you go to...)
pages/courses_home.html (when you click on a course you go to...)
courses/course_1.html (you can view course and then click back to directory above or go to home)
That is the structure I'm looking to try to achieve.
If more information is needed please let me know what and I'll do my best to include it. Thank you.
The syntax should be:
if(isset($_POST["page"])) {
} elseif(isset($_POST["course"])) {
}
I am not sure why you have a die statement there, but I don't think it belongs. Also, keep in mind the logic for what happens if neither of these conditions is met.
Edit: also keep in mind that isset doesn't prevent empty strings, so you may want to check for that as well. A function you could use is
function checkPost($value) {
return isset($_POST[$value]) && $_POST[$value] !== "";
}
To use:
if(checkPost('page')) {
//some logic
}
Wrong syntax.
elseif ($_POST['course']) {
without die statement.If 'course' undefined else statement works and does not get error. Sorry for bad English.
Try this:
if isset(($_POST['page'])) {
...
} else if isset(($_POST['course'])) die("0"); {
instead of this:
if($_POST['page']) {
...
} else if ($_POST['course']) die("0"); {
I've been trying to get user input from a Javascript prompt into a PHP function and have run into a lot a walls doing so. I am at a loss trying jQuery's $.post method- as the PHP simply does not want to execute, not sure why.
Anyways, here is a gist of what I am doing at the moment:
1 A project and its data are loaded from a database- this info is displayed in a table.
2 All data in the table is editable via Javascript prompt(), the code I am using for this is below:
<div id="lvl3"><?php echo $fetchdata['name']; ?></div>
The above work as such: lvl3 is a tag for font styling; blank href to make it act as a link; popupprompt is the prompt function I made, it takes one argument, the 'type' or what is being edited (1 for project name, 2 for project description, ect); return false so the page doesn't reload; php echo to display project data in the table.
3 Once the user clicks the object above- it executes a javascript function called popupprompt taking an argument of 'type', or what project info is being changed. the code for this function is below:
function popupprompt(type) {
switch(type)
{
case 1:
var name = prompt("Project Name:", "");
if (name != null && name != "")
{
//Change Project Name
var getname = name;
var gettype = type;
$.post("edit.php", { type: gettype, name: getname });
} else if (name == "") {
senderror("Please enter a valid Project Name");
} else {
//Prompt canceled
sendnotification('Canceled my ass!');
}
break;
case 2:
//Description?
case 3:
//Version?
case 4:
//Release?
default:
alert("There was an error processing your request.");
break;
} }
Th issue I am having in this function is that nothing in edit.php is executed- and i haven't the slightest clue why. Also, i've had to change the brackets around so it shows properly in the code box- so don't mind those.
4 Anyways, now user input is posted to edit.php- which doesn't work, but i'll post it anyways:
<?php
$type = $_POST['type'];
$name = $_POST['name'];
switch($type) {
case 1:
dbconnect();
$urlext = geturlext();
$authenticated = isauthenticated();
if ($authenticated == false)
{
echo("<script>senderror('Access denied');</script>");
} else {
//Escape and trim input
$input = trim($input);
$input = mysql_real_escape_string($input);
$update = "UPDATE 'projects' SET 'name' = '$input' WHERE 'name' = '$urlext'";
$updatequery = mysql_query($update) or die(mysql_error());
echo("<script>sendnotification('Project Name updated');</script>");
}
break;
default:
break;
}
?>
Again had to move some brackets around. But anyways- this function is supposed to update the data in the database- however, it instead does nothing. I've placed alerts in the beginning and they are never called.
Anyways, long story short- if you know what i'm doing wrong please enlighten me, also, if there is a better way to do this- please let me know!
I appreciate all help,
Thanks
Figured it out after a good week of setting it aside. Took a long look at it in firebug, rooted out a typo that was causing most of my issues and also a MySQL syntax error.
I don't know why, but my custom error reporting system does not work when called from a file in this manner. It might be another thing i'm overlooking but firebug sure helped.
Thanks to those who tried to help <3
I have a series of PHP page, and I would like to use conditional logic to apply different rules to each page. Im not sure if my method is the best way to go about it, so I wanted to see if the community had any recommendations, as this doesn't feel like the best approach. Code Below:
<?php
$nameurl = $_SERVER["REQUEST_URI"];
if ($nameurl == "/fs/about.php"){
echo "about page";
}
elseif ($nameurl == "/fs/index.php"){
echo "home page";
}
?>
Ideally, I would like to only use the filename (index.php or about.php) instead of having /fs/. Im not sure if there is another way of using $_SERVER with PHP but it seems like there might be a more efficient and reusable way of writing this. Thoughts?
You could use
// get script name
$script = explode('/', $_SERVER['PHP_SELF']);
$scriptname = $script[count($script) - 1];
switch ($scriptname) {
case "index.php":
// Something you only want to show on this page
break;
case "about.php":
// Something you only want to show on this page
break;
}
To save a couple of lines of code, you could replace the multiple ifs with a switch:
http://php.net/manual/en/control-structures.switch.php
$nameurl = $_SERVER["REQUEST_URI"];
switch ($nameurl) {
case "/fs/about.php":
echo "about page";
break;
case "/fs/index.php":
echo "home page";
break;
default:
echo "unknown page";
break;
}
Makes it a little easier to add new cases in the future, but it's essentially doing the same thing...
There might be ways to make it more optimized, but I think if you start doing too much you lose the ability to easily understand what's happening in the code, so unless you comment what you're doing future people looking at your work will curse you. :P
Try this
$nameurl = basename($_SERVER['REQUEST_URI'], '.php');
echo $nameurl, " page";
http://php.net/manual/en/function.basename.php
You could try :
$currentFile = $_SERVER["PHP_SELF"];
$current_filename = explode('/', $currentFile);
or
$current_filename = basename($_SERVER['REQUEST_URI']) .'php';
I have:
one
And:
two
PHP page:
<?php
if mypage=one then
echo "my stuff text........one";
if mypage=two then
echo "my stuff text........two";
?>
I want to get text separately for each link from same php page
First of all, if then construct is not available in PHP so your code is syntactically wrong. The use of switch as suggested already is a good way to go. However, for your problem, you should use $_GET['mypage'] instead of $_POST['mypage']. It seems you are beginning PHP. Once you get some good basics, you will probably be making use of the functions such as include() and require(). Make sure you do not make mistakes beginners do:
<?php
if (isset($_GET['mypage'])
{
#include($_GET['mypage']);
}
?>
The above code works and looks simple but it has a very dangerous implementation allowing the malicious users to perform an attack known as file inclusion attack. So you should try to use the switch statements such as:
<?php
$mypage = $_GET['mypage']; //also you might want to cleanup $mypage variable
switch($mypage)
{
case "one":
#include("one.php");
break;
case "two":
#include("two.php");
break;
default:
#include("404.php");
}
?>
Umm, that php is not even remotely valid code. You want a switch statement:
<?php
$mypage = isset($_GET['mypage']) ? $_GET['mypage'] : '';
switch ($mypage) {
case 'one':
echo "my stuff text........one";
break;
case 'two':
echo "my stuff text........two";
break;
default:
header('HTTP/1.0 404 Not Found');
echo 'This page does not exist';
}
I have searched all over the internet to run a function from URL and found out it is not possible.
I am asking if there is another way to do this. I will explain below what I am trying to achieve.
On my website I have several functions that when a hyperlink is clicked on that cracks.php page, the main content changes accordingly. Now I want to direct people from a single URL to that cracks.php page with the function already called.
Example - www.example.com/cracks.php?AC ( which will call a function named AC and the content changes before the page loads)
Ive found this method below, but couldnt get it to work.
if(document.location.search == '?AC')
{
AC();
}
Sorry for the messy code on the website. Thanks for reading, any help would be appreciated.
You can call www.example.com/cracks.php?do=AC and then get do with $doMethod = $_GET['do'];. What you then do is, use a switch function or a few ifs to check and execute when e.g. $doMethod equals AC.
Like this:
$doMethod = $_GET['do'];
switch($doMethod)
{
case "AC":
//some random stuff to do
break;
case "BD":
//some random stuff to do
break;
case "XY":
//some random stuff to do
break;
default:
break;
}
That depends if you need to do that dynamically or you can do it hard coded. Because that hard coded is too simple (with if's and switches), what you have to do is:
$functionsList = Array('func1', 'func2');
function func1(){
echo '1';
}
function func2(){
echo '2';
}
if (function_exists($_GET['f']) and in_array($_GET['f'], $functionsList)){
call_user_func($_GET['f']);
}
Then call your_file_name.php?f=func1 and your_file_name.php?f=func2 and you'll see different outputs.
With the help of Mark Koopman I managed to use his Javascript method and it worked like I wanted.
So heres the method in Javascript:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>