ok so im here trying to practice some php (im a super beginner) and so long story short,
i put form elements in one page, passed it to the process php.
Im just messing aound trying to see what ive learned so far. i dont get any errors, just dont understand why it doesnt work.
<?php
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
$response = array("please enter correct information","hmm" . "$yourname");
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
?>
<?php nametest(); ?>
what im trying to do is, that if the name isnt set, to make a variable equal to a value inside response.
Try
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1];
}
return $yourname;
}
print nametest();
The function needs to return a value to be printed. I also noticed you have two ;; behind line 5.
Because you are assigning $yourname and $compname in the first two lines:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
UPDATE You can check if these are set in POST, and therefore not need to check them later:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
They will always be set, even if NULL or empty. So, your later calls to isset() will always be true.
Instead, you may check if they are empty with the empty() function:
UPDATE Not necessary according to corrections in comments. Your isset() should work.
// Check with empty()
// but still won't work properly. keep reading below...
function nametest() {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
However, there is another problem here of variable scope. The variables are not available inside the function unless you either pass them in as parameters or use the global keyword:
// $yourname is passed as a function argument.
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
Getting there... Now your function assigns $yourname, but it doesn't return or print any value. Add a return statement, and then you can echo out the result:
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
// Add a return statement
return $yourname;
}
// Now call the function, echo'ing its return value
echo nametest($yourname, $response);
Variable Scope is the biggest mistake here, your function can not 'see' the variables that you created outside of it, do this:
<?php
.
.
.
function nametest($yourname, $response) { // This creates two new variables that
// are visible only by this function
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1]; // Get rid of the extra semicolon
}
return $yourname; // This $yourname is only visible by this function so you
// need to send it's value back to the calling code
}
?>
<?php nametest($yourname, $response); ?> // This sends the values of the
// variables that you created at the
// top of this script
Related
I want to make a call of this php logic inside a html div but when passing it as a function the logic breaks since it does not send an error message in case of entering the pass wrong and its confirmation at the time of performing the password change.
<?php
require 'funcs/conexion.php';
require 'funcs/funcs.php';
$user_id = $mysqli->real_escape_string($_POST['user_id']);
$token = $mysqli->real_escape_string($_POST['token']);
$password = $mysqli->real_escape_string($_POST['password']);
$con_password = $mysqli->real_escape_string($_POST['con_password']);
if(validaPassword($password, $con_password))
{
$pass_hash = hashPassword($password);
if(cambiaPassword($pass_hash, $user_id, $token))
{
echo "Contraseña Modificada <br> <a href='index_alumnos.php' >Iniciar Sesion</a>";
} else {
echo "Error al modificar contraseña";
}
} else {
echo "Las contraseñas no coinciden <br> <a href='index_alumnos.php' >contacta a Academia</a>";
}
?>
If the echo happens before your actual div is drawn, the echo goes... right where it happens. Which isn't within your div.
One way of getting around this would be to put your error message into a variable and then deliver this variable into your div (whether it be through a return value, if it's a call, or some other means.)
Here's a simple example to illustrate this:
<?php
if(1 === 2) {
//great, 1 is 2
} else {
//oh no, an error
$someErrorLine = '1 is not 2';
} ?>
<h1>Hi</h1>
<div><?= $someErrorLine ?></div>
You could also check if the variable exists, something like if(isset($someErrorLine)) {} and echo the div with it, or put the div within your variable.
I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>
With my function what I have written I try thereby 2 things.
The links should be called like this http://localhost/?login=Bla, Now it is like this http://localhost/login,php?login "Bla
Next I would have asked, in my function a 1 is given after each call. I just can't figure out where this comes from, I've been sitting on this problem for a long time.
Output with the 1
This is the code with which I can call the pages
function Seite($pagename, $lay){
function Seite($pagename, $lay){
$path = "$lay/$pagename.php";
if (file_exists($path)) {
openSeite($path);
}
}
function openSeite($pageurl){
$fc = require($pageurl);
echo $fc;
}
function echopage($slug, $fade){
// $slug = ?SLUG=Seite
// $fade = Ordner des Layout
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
$contente = seite($page, "$fade");
echo $contente;
}
I call the content on the index.php with
<? echopage("login", "admin/layout"); ?>
isset($_GET["$slug"]) returns a 1 because it is set (true), write a traditional conditional with the echo inside the if statement.
*Better Yet assign your output to a variable and concatenate the values accordingly.
$output = NULL;
if(isset($_GET["$slug"]){
$contente = seite($page, "$fade");
$output .= $contente;
}else{
//handle error
}
HTML:
<?=$output?><!--Output your displayed text held in the variable-->
ISSUE:
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
You are essentially returning the set value, which is 1 also true.
From php manual for value: Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
You can test this by simply writing out a line of code echo isset($var); and checking the test php page. Then try defining a variable and doing the same thing. $var = "this is set"; then echo isset($var);, you will get a 1.
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 troubleshooting CAPTCHA problem in someone Else's code, where the form method is "POST"
But in the action.php file the code is like this:
$key=substr($_SESSION['key'],0,5);
$number = $_GET['img_code'];
if($_GET['img_code']){
if($number==$key)
{
echo "done";
exit();
}
else
{
echo false;
exit();
}
}
I have tried to var_dump($_GET['img_code']) and as expected I am getting null value.
but if I am doing it var_dump($_POST['img_code']) I am getting the correct value.
but once I am setting it to POST, I start getting error "captcha not entered correctly.
Any help will be greatly appreciated.
UPDATE:
FORM METHO
<form action="{$Site_Root}signup.php" method="post" class="frmRegister tutor-registration" name="frmRegister" id="frmRegister" enctype="multipart/form-data" >
Further Update:
If I am using $_REQUEST['img_code'] and then doing a var_dump I am getting the matching string for $key and $number like
string(5) "f065a" string(5) "f065a"
but problem is when I am applying this as a condition for example:
I am getting - "captcha not entered correctly."
if(isset($_POST['email'])){
if ($key==$number){ // condition line is added by me
if(!empty($_FILES['photo']['name']))
{
$_POST['photo'] = fileUpload($_FILES['photo'],TUTOR);
$thumb->image($physical_path['Tutor'].$_POST['photo']);
$thumb->size_width(120);
$thumb->jpeg_quality(100);
$filename = $thumb->get2(); //small_thumb_
}
else
{
$_POST['photo'] = "";
}
$tutor_id = $tut->Insert($_POST);
$to_email = $_POST['email'];
global $mail;
$mail = '';
$mail = new htmlMimeMail();
$mail->setFrom($config[WC_CONTACT_US]);
//Set Cc
// $mail->setCc(array($config[WC_CONTACT_US]));
$mail->setSubject('Welcome to TuitionJobsPortal.com!');
$tpl2 = new Smarty;
$tpl2->template_dir = $physical_path['EmailTemplate'];
$tpl2->compile_dir = $physical_path['Site_Root']. 'templates_c/';
$tpl2->debugging = DEBUG;
$tpl2->assign(array("membername" => $_POST['tutor_name'],
"vcode" => $_POST['verification_code'],
"tutor_id" => $tutor_id,
"Templates_Image" => $virtual_path['Site_Root'].'templates/images/',
"Site_Root" => $virtual_path['Site_Root'],
));
$content = $tpl2->fetch('registration'. $config['tplEx']);
$mail->setHtml($content);
$result = $mail->send(array($to_email));
header("location: signup.php?signup=true");
exit();
}
} //this is added.
I don't think you can access $_POST data from $_GET , so either change form method to GET or access posted data using $_POST['img_code'] .
You can use the $_REQUEST global variable, it can do the work of both GET and POST,