I have to redirect a to a page and say x already exist.
I am doing some think like this:
header('location:newcategory.php'?msg=category exists);
I would prefer to do this from PHP, rather than in JavaScript.
On the page doing the redirecting:
header("Location: newcategory.php?msg=" . urlencode('category exists'));
On the newcategory.php page:
echo $_GET['msg'];
header("Location: :newcategory.php?msg=category exists&var=".$x);
in the newcategory.php add this
if(msg == "category exists")
{
echo $var." already exists";
}
It won't be good if you pass whole message in a GET parameter, as it would be probably vulnerable to some sort of XSS. The best way is to store collection of message and their identifiers and produce message on the fly. For example you could have an array:
$messages = array(
'exists' => 'category %s exists',
'failed' => 'query %s failed'
);
And then pass only message identifier in an URL, optional is parameter defining more clearly what happened:
header("Location: newcategory.php?msg=exists&id=2");
In target page you could write something like that:
$msg = '';
switch($_GET['msg'])
{
case 'exists':
{
$msg = sprintf($messages[$_GET['msg']], intval($_GET['id']));
break;
}
}
echo $msg;
It could be also wrapped in some classes, but I'd shown you the idea, hope it helps.
Related
I want to set a message for the user to see in php, but I'm having issues crossing controllers. Here was my first try:
if($revOutcome > 0){
$message = "<p>Review updated!</p>";
header('Location: /acme/accounts/index.php?action=seshLink');
exit;
}
And here was my second try:
if($revOutcome > 0){
header('Location: /acme/accounts/index.php?action=seshLink&message=Update was successful!');
exit;
}
I have an isset in the view that checks if $message is set, and if it is, echo what is displayed in $message. But for some reason, it's not displaying. Here is the code for the view:
<?php
if (isset($message)) {
echo $message;
}
?>
And here is the switch case statement seshLink:
case 'seshLink':
$userId = $clientData['clientId'];
$revData = getCliRev($userId);
if(!$revData){
$message = "<p>No reviews here yet. Write your first one today!</p>";
include '../view/admin.php';
exit;
}
else {
$RevDisplay = buildAdminReviewDisplay($revData);
}
include '../view/admin.php';
break;
I really don't know why $message isn't displaying.
Because you are making a request call (parameters through url) which means that you need to get your variables using $_GET array like
...
if (isset($_GET["message"]))
...
I am using already this code:
<?php
// [...]
ELSE IF(isset($_GET['msg'])){
echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
<h2 class='panel-title'>Good job!</h2></div>
<div class='panel-body'><h4>".addslashes(strip_tags(trim(#$_GET[msg])))."</h4></div></div>";
}
//[...]
?>
Which is called from other pages if some operation goes well:
if ($result){
header("Location:index.php?msg=DB updated succesfully");
exit;
}
BUT as you may imagine, it is not clean. Working, but not the best.
Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?
And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google.
But I just can't understand how to do it.
Thanks a lot guys!
Because you prefer to keep your code pure
i just suggest you to do not send the message in GET/POST
just send the status like
index.php?status=success
then check the status in result file
if(isset($_GET['status']) AND $_GET['status'] == success){
echo "bla bla";
}elseif(isset($_GET['status']) AND $_GET['status'] == fail){
echo "bla bla";
}else{
//do something
}
EDIT
If you have many messages, then you can create array
$message = [
'success' => 'success message here',
'fail' => 'failmessage here',
'notFound' => 'not found message'
];
$status = ( isset($_GET['status']) AND
isset($message[$_GET['status']]) )?$_GET['status']:'notFound';
echo $message[$status];
I think i'm going to go with this: PHP. How to pass variable and auto redirect to another PHP file
<?php
session_start();
$id = $user_profile['id'];
$_SESSION['id'] = $id;
header('Location: checkIfExsists.php');
?>
And on the checkIfExsists.php page, retrieve the variable so:
<?php
session_start();
$id = $_SESSION['id'];
?>
New code
session_start()
// [...]
ELSE IF(isset($_GET['msg'])){
echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
<h2 class='panel-title'>Good job!</h2></div>
<div class='panel-body'><h4>".addslashes(strip_tags(trim(#$_SESSION['msg'])))."</h4></div></div>";
}
And..
session_start();
if ($result){
$_SESSION['msg'] = "DB updated!";
header("Location:index.php?msg");
exit;
}
What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...
I'm trying to integrate an API builder to my control panel through a form or post data. I can't figure out how to put the post data as the value for the array.
I tried using print_r($_POST['VALUE']) with and without quotes.
I tried using just $_POST['VALUE'] with and without quotes.
I also tried to set $value = $_POST['VALUE'] then using $value with and without quotes but that caused an error 500.
Here is the code I am trying to use:
$res = $api->remoteCall('requestLogin', array(
'type' => 'external',
'domain' => 'print_r($_POST['domain'])',
'lang' => 'en',
'username' => 'print_r($_POST['uname'])',
'password' => 'print_r($_POST['pass'])',
'apiUrl' => '127.0.0.1',
'uploadDir' => '/web/'.print_r($_POST['domain']).'/public_html',
I apologize as I am new to PHP, but thank you in advance.
I'm not sure what other logic is being done there, how the post variables are being sent to the script your sample code is running on, or any of the other details which might point towards a more complete solution but here are some basic tips to help you troubleshoot.
The post variables should be formatted like this:
$res = $api->remoteCall('requestLogin', array(
'domain' => $_POST['domain'],
You can dump the entire post array to the screen by doing
print_r($_POST);
This should output your array to the screen so you can verify that you're receiving the post data in the code and should help you fix any typos or misnamed post variables. If the array has the key as $_POST['domainName'] and you're echoing $_POST['domain']
You're calling code (the "form or post data") should have the post fields in place and named correctly in order for them to be sent to the script
<input type="text" name="domain">
You should be performing some basic validation on your post fields before adding them to something that's going to be stored anywhere or sent off to a third-party. At the most minimal you'll want to check that there is a value being set for the essential fields (required fields) and I'd look to make sure the values are matching requirements of the API you're passing them off to.
Several things may go wrong when using api. POST values, input values, API call or connection or maybe api response. So not only at the time of implementation and coding but also when integrating api call script with the application there should be some sort of testing and error handling in place. A simple script can be like this
$error = array();
$request = array();
$request['type'] = 'external';
if (isset($_POST['domain']) && !empty($_POST['domain'])) {
$request['domain'] = $_POST['domain'];
$request['uploadDir'] = "/web/{$_POST['domain']}/public_html";
} else {
$error[] = "Domain is empty";
}
if (isset($_POST['uname']) && !empty($_POST['uname'])) {
$request['username'] = $_POST['uname'];
} else {
$error[] = "Username is empty";
}
if (isset($_POST['pass']) && !empty($_POST['pass'])) {
$request['password'] = $_POST['pass'];
} else {
$error[] = "Username is empty";
}
$request['lang'] = 'en';
$request['apiUrl'] = '127.0.0.1';
if (count($error) > 0) {
echo implode( "<br>" , $error );
} else {
try{
$res = $api->remoteCall('requestLogin',$request);
} catch ( Exception $e ) {
print_r($e);
exit();
}
}
Here's what I'm trying to do:
$errmsg_1 = 'Please make changes to your post';
$errmsg_2 = 'Please make changes to your post image';
$error = 1;
echo $errmsg_.$error; //'Please make changes to your post';
Nothing will work, and there are many error messages like these ones that I have to echo.
Can anyone help?
What you're asking for is known as a variable variable -- see http://uk.php.net/manual/en/language.variables.variable.php for more info.
But please don't do that; it's considered very poor coding practice.
What you actually need is an array:
$errmsg = array(
'Please make changes to your post', //this will be $errmsg[0]
'Please make changes to your post image' //this will be $errmsg[1]
);
$error = 0; //nb: arrays start at item number 0, not 1.
echo $errmsg[$error];
That's much better coding practice than messing around with variable variables.
Store error messages in array:
$errmsg[1] = 'Please make changes to your post';
$errmsg[2] = 'Please make changes to your post image';
// and so on
$error = 1;
echo $errmsg[$error];
Try
echo {'$errmsg_' . $error};
Although you're doing this really rather incorrectly. You should be using an array instead; concatenating variable names is bad practice and leads to messy/unreadable/broken code. Using an array would work like this:
$errors = array(
'Please make changes to your post',
'Please make changes to your post image'
);
echo $errors[$error];
Although bear in mind that $error starts from 0 as arrays are 0-index based.
Off the top of my head I think you want $errmsg_{$error}, but I'm not in a position to test/double check that right now.
This should work:
$errmsg_1 = 'Please make changes to your post';
$errmsg_2 = 'Please make changes to your post image';
$error = 1;
echo ${'errmsg_ ' . $error};
No offence meant but what you're doing is bad design.
A small but no means perfect solution would be store your errors as an Array.
$errors = array('Please make changes to your post', 'Please make changes to your post image');
$error = 0;
echo $errors[$error];
Try using this ${$errmsg_.$error}
This is a variable variable: http://php.net/manual/en/language.variables.variable.php
You're trying to do this:
function errorMsg($code)
{
$msg;
switch($code)
{
case 1:
$msg = 'Please make changes to your post';
break;
case 2:
$msg = 'Please make changes to your post image';
break;
}
return $msg;
}
echo errorMsg(1);
$error_msg = 'Please make changes to your ';
$error[1] = 'post';
$error[2] = 'post image';
for($i=1; $i<=count($error); $i++)
echo $error_msg . $error[$i];
Use arrays. keep the indexes for easy future reference, as well as easy error message changing and organized API.
$errmsg = array(
1 => 'Please make changes to your post',
2 => 'Please make changes to your post image'
);
$error = 1;
echo $errmsg[$error]; //'Please make changes to your post';