|
I was in a double while loop.
And incremented in the 2nd internal while, my bad!
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
|
Oh, that's a good idea
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Hello good, I have a query, what happens is that I want to enter user roles in my code but I don't know how to do it, I have the registration and login form already created, I just need to add the reference that I already mentioned above:
register_user_be.php:
<?php
include 'conexion_be.php';
$nombre_completo = $_POST['nombre_completo'];
$correo = $_POST['correo'];
$usuario = $_POST['usuario'];
$contrasena = $_POST['contrasena'];
$contrasena = hash('sha512', $contrasena);
$query = "INSERT INTO usuarios(nombre_completo, correo, usuario, contrasena)
VALUES('$nombre_completo', '$correo', '$usuario', '$contrasena')";
$verificar_correo = mysqli_query($conexion, "SELECT * FROM usuarios WHERE correo='$correo' ");
if (mysqli_num_rows($verificar_correo) > 0) {
echo '
<script>
alert("Este correo ya está registrado");
window.location = "../index.php";
</script>
';
exit();
}
$verificar_usuario = mysqli_query($conexion, "SELECT * FROM usuarios WHERE usuario='$usuario' ");
if (mysqli_num_rows($verificar_usuario) > 0) {
echo '
<script>
alert("Este usuario ya está registrado");
window.location = "../index.php";
</script>
';
exit();
}
$ejecutar = mysqli_query($conexion, $query);
if ($ejecutar) {
echo '<script>
alert("Usuario registrado correctamente");
window.location = "../index.php";
</script>';
}else{
echo '<script>
alert("Inténtalo de nuevo, usuario no registrado");
window.location = "../index.php";
</script>';
}
mysqli_close($conexion);
?>
login_usuario_be.php:
<?php
session_start();
include 'conexion_be.php';
$correo = $_POST['correo'];
$contrasena = $_POST['contrasena'];
$contrasena = hash('sha512', $contrasena);
$validar_login = mysqli_query($conexion, "SELECT * FROM usuarios where correo='$correo' and contrasena='$contrasena'");
if (mysqli_num_rows($validar_login) > 0) {
$_SESSION['usuario'] = $correo;
header("location: ../inicio.php");
exit;
}else{
echo '
<script>
alert("El usuario no existe, por favor verifique los datos introducidos");
window.location = "../index.php";
</script>
';
exit;
}
?>
index.php:
<?php
session_start();
if (isset($_SESSION['usuario'])) {
header("location: inicio.php");
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iniciar Sesión</title>
<link rel="stylesheet" type="text/css" href="assets/css/estilos.css">
</head>
<body>
<main>
<div class="contenedor__todo">
<div class="caja__trasera">
<div class="caja__trasera-login">
<h3>¿Ya tienes una cuenta?</h3>
<p>Inicia sesión para entrar a la página</p>
<button id="btn__iniciar-sesion">Iniciar sesión</button>
</div>
<div class="caja__trasera-register">
<h3>¿Aún no tienes una cuenta?</h3>
<p>Regístrate para que puedas iniciar sesión</p>
<button id="btn__registrarse">Regístrate</button>
</div>
</div>
<!--
<div class="contenedor__login-register">
<!--
<form action="php/login_usuario_be.php" method="POST" class="formulario__login">
<h2>Iniciar sesión</h2>
<input type="text" placeholder="Correo electrónico" name="correo">
<input type="password" placeholder="Contraseña" name="contrasena">
<button>Entrar</button>
</form>
<!--
<form action="php/registro_usuario_be.php" method="POST" class="formulario__register">
<h2>Regístrarse</h2>
<input type="text" placeholder="Nombre Completo" name="nombre_completo">
<input type="text" placeholder="Correo Electrónico" name="correo">
<input type="text" placeholder="Usuario" name="usuario">
<input type="password" placeholder="Contraseña" name="contrasena">
<button>Regístrarse</button>
</form>
</div>
</div>
</main>
<script src="assets/js/script.js"></script>
</body>
</html
modified 17-Nov-20 3:47am.
|
|
|
|
|
|
I don't really want to "maintain a web site" but I want to expose some computing functionality for a hobby of mine.
Excel is driving me to tears.... So I am thinking perhaps I could have a single page static SPA!
But most web tech drive me to tears, me think would be nice do a Blazor SPA! Is it possible?
One with 0 server side setup! That I can just drop on web app folder somewhere?
Any links? tutorials?
|
|
|
|
|
hi all,
I am going to build an asp.net core website and an asp.net core webapi. My question is that from design perspective, should I just call into the webapi to get data for my website? or just call into the database to get data directly?
It looks like calling the webapi would promote separation of concerns and I don't have to expose my database connection strings in multiple places, but I am afraid there is a performance hit that will impact the performance of the load time of the website.
Any insight is greatly appreciated.
|
|
|
|
|
Quote: My question is that from design perspective, should I just call into the webapi to get data for my website? or just call into the database to get data directly? This is a preference-based and a scenario-based question. In my own application that I have, I am redirecting all the database related stuff through API, and this has decreased the attack surface a lot (I can secure the database requests at one place).
Also, if you route all the database traffic to ASP.NET Core Web API, you can develop the frontend independently—in future you can replace ASP.NET Core MVC with something like a React or Angular framework for frontend, and you can easily integrate the application in a mobile application; native, Xamarin or Flutter.
Quote: It looks like calling the webapi would promote separation of concerns Correct, like I said earlier.
Quote: I don't have to expose my database connection strings in multiple places Yes, and no. You still can prevent exposing the database connection string by using variables on your hosting environment and then reuse that value in all your processes. This part depends entirely on where you are hosting your application.
Quote: but I am afraid there is a performance hit that will impact the performance of the load time of the website. No, do not worry about this part.
If you create two applications, you are going to launch them separately and that can add 3-5 seconds of load time, but it would be much easier to scale the applications in the future. This will help you in handling the load like a pro.
Also, load time depends on how many users are you expecting to get? If there will be a lot of users (like thousands of active users) then try caching your website and the queries, so you do not send duplicate queries to the database for at least an hour.
Here are a few more ideas to improve the performance:
- Deploy your application as a stateless instance (try to move all the memory and state, e.g. session information to a database)
- Add a caching layer to your service
- Try to add scaling to your website (depends on the host environment)
- If you scale a stateless website, you can utilize caching and database to handle more requests and provide service to more users
- Keep separating the different domains inside your application to their own services (Microservice pattern)
I hope this helps you understand the bigger picture.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Thanks Afzaal, this is very insightful and answer most of my concerns. your ideas to improve performance aligned with what we had in mind except for number 1 that I am not sure if I understand.
Did you mean that I will need to make database calls through the webapi to get the session state, like if I have a survey engine, I will have to post every question that the user answer so he or she can come back to it later? if not, Can you give a brief example what you have in mind?
Thanks and greatly appreciate your help.
|
|
|
|
|
Quote: Did you mean that I will need to make database calls through the webapi to get the session state, Not specifically, but just outproc the session and other "state" information.
Take a look at this for inspiration: ASP NET Core MVC - How to configure Out of Process Session State? - Stack Overflow
Quote: if I have a survey engine, I will have to post every question that the user answer so he or she can come back to it later? Correct, so that none of the information is stored only in the ASP.NET Core process. This can help you scale the application as well, since your users are not stuck with using a specific process and load balancer can easily balance the traffic regardless of the survey state.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
the post about out of process session state is interesting. still need time to digust the topic as I am not familar with it at all. I believe I have a basic idea how to go about doing this now. thanks again for the help!
|
|
|
|
|
You should separate the database code from the controllers and views. I created a database class implementing an interface that is passed to the controllers, providing methods to obtain the required data from the database. Thus there is a minimal common interface between the web site and the database code, and the web site knows nothing about the database. This allows testing of the database code with a desktop test harness. It also allows easy replacement of the database code if for example I change database provider.
I used Dapper for database access, but PetaPoco is better IMO.
|
|
|
|
|
hi Leif Simon Goodwin,
Yes, I believe that calling into an webapi is better in terms of separation of concern, and I have started doing that for my project. I've never heard of petapoco before and it looks interesting. I am just using good old ADO.NET using queries and loading data to POCOs.
|
|
|
|
|
|
I used to use Entity Framework. Everything seemed to work well enough to get me hooked, until there are more complicated examples, such as pull fields from different tables using a stored procedure and try to update the fields in the object afterwards, that will get me all the time ...
|
|
|
|
|
hi all,
I am going to build an asp.net core website and an asp.net core webapi. My question is that from design perspective, should I just call into the webapi to get data for my website? or just call into the database to get data directly?
It looks like calling the webapi would promote separation of concerns and I don't have to expose my database connection strings in multiple places, but I am afraid there is a performance hit that will impact the performance of the load time of the website.
Any insight is greatly appreciated.
|
|
|
|
|
I am new to PHP programming and I am trying to teach myself WordPress theme development for fun and I am using PhpStorm as my IDE.
I am trying to better understand the inner-workings of WordPress and I am running into a roadblock on something.
I have a sandbox plugin that I created to use to play around with WordPress.
In my wp-content/plugins/sandbox/sandbox.php file, I am just running basic PHP code to help me get used to the language as it relates to WordPress.
Also, I installed both Kint and Whoops using Composer to help with debugging.
Now that I got that out of the way, here is what I am doing:
Code #1
namespace MyDevPlayground\Sandbox;
add_action( 'loop_start', __NAMESPACE__ . '\process_the_string' );
function process_the_string() {
$current_user = wp_get_current_user();
$data_packet = array(
'id' => $current_user->ID,
'email' => $current_user->user_email,
'name' => array(
'first_name' => $current_user->user_firstname,
'last_name' => $current_user->user_lastname,
),
);
render_user_message( $data_packet );
}
function render_user_message( array $current_user ) {
$user_id = $current_user['id'];
d( "Welcome {$current_user['name']['first_name']}, your user id is { {$user_id} }." );
ddd( "Welcome {$current_user['name']['first_name']}, your user id is {$user_id}." );
}
When I run Code #1 above everything is fine and Kint displays the values just fine.
Now for the problem I am having that I don’t understand about WordPress:
Code #2
<pre lang="PHP">namespace MyDevPlayground\Sandbox;
add_action( 'loop_start', __NAMESPACE__ . '\check_logged_in_user' );
function check_logged_in_user(){
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) {
d('Not logged in');
} else {
ddd('Logged in');
}
}
check_logged_in_user();
When I run Code #2 above, Whoops reports the following error:
Call to undefined function MyDevPlaygroundSandbox\wp_get_current_user
For some reason when I run Code #1, the wp_get_current_user() function loads just fine, but not with Code #2.
Can someone help me understand why this is in laymen’s terms if possible?
What is the difference between Code #1 and Code #2?
How come the wp_get_current_user() function is not loading in Code #2, but it is in Code #1?
Thank you for your help.
|
|
|
|
|
I'm working on a RestSharp wrapper class. I can call the API and step into the controller. The controller creates the response data and returns it. However, when I get the entity back from the API its properties are not set.
Controller
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("application/json"));
}
}
public class CustomerController : ApiController
{
[HttpGet]
public APIResponse<CustomerEntity> GetCustomer(int id)
{
var response = new APIResponse<CustomerEntity>
{
Success = true
};
try
{
var data = new CustomerEntity
{
Id = 1,
CustomerName = "ACME Widgets"
};
response.Result = data;
}
catch (Exception e)
{
var rm = new ReponseMessage
{
Exception = e,
Message = e.Message
};
response.Messages.Add(rm);
}
return response;
}
}
RestSharp Wrapper
public class APIExecutor
{
#region Private Fields
private RestClient client;
private RestRequest request;
private string baseURL;
#endregion
public APIExecutor(string url, Method method = Method.POST)
{
baseURL = "<a href="http:
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("Url");
}
client = new RestClient(baseURL);
client.AddHandler("application/json", () => { return new JsonDeserializer(); });
request = new RestRequest(url, method)
{
RequestFormat = DataFormat.Json
};
}
public async Task<APIResponse<T>> ExecuteAsync<T>()
{
IRestResponse<T> response = await client.ExecuteAsync<T>(request);
var results = new APIResponse<T>
{
StatusCode = response.StatusCode,
RequestURL = response.ResponseUri.ToString()
};
if (response.StatusCode == HttpStatusCode.OK)
{
results.Success = true;
results.Result = response.Data;
return results;
}
else
{
var exception = LogError(new Uri(baseURL), request, response);
var message = new ReponseMessage
{
Message = response.StatusDescription,
Exception = exception
};
results.Messages.Add(message);
results.Success = false;
}
return results;
}
}
The response content does not look like JSON. I'm wondering if either the WebApiConfig or RestClient.AddHandler is wrong.
I could some expert eyes on this. Not sure why deserialization isn't working.
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
modified 9-Nov-20 14:20pm.
|
|
|
|
|
Your API returns APIResponse<T> . Your client seems to be looking for a response of type T . I suspect this mismatch is what's causing the problem.
Kevin Marois wrote: The response content does not look like JSON.
What does it look like?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: What does it look like?
This is what the response content looks like:
{"<messages>k__BackingField":[],"<statuscode>k__BackingField" ,"<requesturl>k__BackingField":null,"<result>k__BackingField":{"<id>k__BackingField":1,"<customername>k__BackingField":"ACME Widgets"},"<success>k__BackingField":true}
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
That's definitely an APIResponse<CustomerEntity> rather than a CustomerEntity .
It looks like a problem with your JSON formatter - it's serializing the fields instead of the properties. All of those mangled names are what the compiler generates to store the values for auto-implemented properties[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: That's definitely an APIResponse<CustomerEntity> rather than a CustomerEntity .
It looks like a problem with your JSON formatter - it's serializing the fields instead of the properties
Agreed. What can I do about it? Maybe a custom JSON formatter?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
From what I can tell, this appears to be a server-side problem. If I type the URL into a browser, I get back the same format I posted earler. It's clearly not JSON.
Here's my WebAPIConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
}
Other than this, I'm not reallt sure what else to look for. I'm open to ideas.
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
|
Richard Deeming wrote: Are your classes marked as [Serializable] ? You may need to add [DataContract] to the class and [DataMember] to the properties.
Yes, I had the [Serializable] attribute, but not the others. I look at that twice and just didn't see it. Too many late nights
It seems to work OK now. Thank you for all your help.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|