PHP How to replace specific string from an URL - php

I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:
http://www.server.com/en/something/else/to/do
I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.
I use this class to change Language:
class IDIOMAS {
private $UserLng;
private $langSelected;
public $lang = array();
public function __construct($userLanguage){
$this->UserLng = $userLanguage;
}
public function userLanguage(){
switch($this->UserLng){
case "en":
$lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';
// Menu
$lang['MENU_LOGIN'] = 'Login';
$lang['MENU_SIGNUP'] = 'Sign up';
$lang['MENU_LOGOUT'] = 'Logout';
$lang['MENU_SEARCH'] = 'Search';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
$lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
$lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
$lang['SUBSCRIBE_SEND'] = 'SEND';
//LOGIN
$lang['LOGIN_TITLE'] = 'Please Login to your account';
$lang['LOGIN_USER'] = 'User';
$lang['LOGIN_PASSWORD'] = 'Password';
$lang['LOGIN_ERROR'] = '¡User and/or password invalid!';
//REGISTER
$lang['REGISTER_NAME'] = 'Please write your name';
$lang['REGISTER_LAST_NAME'] = 'Please write your last name';
$lang['REGISTER_EMAIL'] = 'Write your E-mail';
$lang['REGISTER_CITY'] = 'Enter your City name';
$lang['REGISTER_COUNTRY'] = '¿Where are you from?';
$lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
$lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';
return $lang;
break;
case "es":
$lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';
// Menu
$lang['MENU_LOGIN'] = 'Entrar';
$lang['MENU_SIGNUP'] = 'Registrarse';
$lang['MENU_LOGOUT'] = 'Salir';
$lang['MENU_SEARCH'] = 'Buscar';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
$lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
$lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
$lang['SUBSCRIBE_SEND'] = 'Enviar';
//LOGIN
$lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
$lang['LOGIN_USER'] = 'Usuario';
$lang['LOGIN_PASSWORD'] = 'Clave';
$lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';
//REGISTRO
$lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
$lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
$lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
$lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
$lang['REGISTRO_PAIS'] = '¿De donde eres?';
$lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
$lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';
return $lang;
break;
}
}
}
I use this class with this code:
$language = new IDIOMAS($lang);
$langArray = array();
$langArray = $language->userLanguage();
And set the language like this:
if (!isset($_SESSION['idioma'])){
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$_SESSION['idioma'] = $lang;
}else{
$lang = $_SESSION['idioma'];
}
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
$_SESSION['idioma'] = $_GET['lang'];
$lang = $_SESSION['idioma'];
}
Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in www.server.com and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in www.server.com/es/something/else/to/do i need to change specificallly the /es parameter.
I have a function to get the current url for redirections when being logged or register.
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
I was trying to change the lang value inside that function with no success,
Really appreciate any help

Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:
// Find the first forward slash location
$pos1 = strpos($url,'/'); // The whole URL
// You only need this next line if your language codes are different sizes
// If they are always 2 then can alter the code to not use it
$pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting
$base = substr($url,0,$pos1); // Get domain name half
$end = substr($url,$pos2); // Get everything after language area
// Now from the function return the result
$val = $base.'/'.$newlang.'/'.$end;
return $val;
You may need to add or subtract 1 on the $pos to get the right values returned, like so:
$pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
$base = substr($url,0,$pos1-1); // In case its returning the slash
$end = substr($url,$pos2+1); // In case its return the slash
Please tweak and test this, it is only the concept in action, I have not tested this snip-it.

Finally i got it by modifying the getUrl function to this:
function getUrl($newlang) {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
$substr = substr($url,27,3);
$base = substr($url,0,28);
$resto = substr($url,31,1000);
$newUrl = $base.$newlang."/".$resto;
return $newUrl;
}
and calling the function like this getUrl("en") or getUrl("es");
Maybe this can be usefull for someone else.

Related

Display all data from an API in PHP

I want to display all data I want from Matomo API but I can only display them one by one
I don't know if I should do a for loop and where or how.
My code :
<?php
include 'TabMetrique.php';
$token_auth = '*********';
getMetrique($metrique);
$url = "http://localhost/matomo/";
$url .= "?module=API&method=".getMetrique($metrique)."&idSite=1";
$url .= "&period=month&date=2022-05-14";
$url .= "&format=JSON";
$url .= "&token_auth=$token_auth";
$fetched = file_get_contents($url);
$content = json_decode($fetched,true);
// case error
if (!$content) {
print("No data found");
}
else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
?>
My IF condition doesn't work but that's not a problem at the moment
And TabMetrique.php :
<?php
$metrique [0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique [1] = 'UserCountry.getCountry'; // Pays
$metrique [2] = 'UserCountry.getContinent'; //continent
$metrique [3] = 'UserCountry.getRegion'; // Region
$metrique [4] = 'UserCountry.getCity'; // Ville
$metrique [5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique [6] = 'UserLanguage.getLanguage'; // Langue
$metrique [7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique [8] = 'VisitsSummary.get';
$metrique [9] = 'VisitsSummary.getVisits'; //visiteur
$metrique [10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
function getMetrique($metrique){
return $metrique[9];
}
?>
someone can help me ? thx
Well first remove the function it is unnecessary, all you need is an array and then process it with a forech loop.
code TabMetrique.php
<?php
$metrique[0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique[1] = 'UserCountry.getCountry'; // Pays
$metrique[2] = 'UserCountry.getContinent'; //continent
$metrique[3] = 'UserCountry.getRegion'; // Region
$metrique[4] = 'UserCountry.getCity'; // Ville
$metrique[5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique[6] = 'UserLanguage.getLanguage'; // Langue
$metrique[7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique[8] = 'VisitsSummary.get';
$metrique[9] = 'VisitsSummary.getVisits'; //visiteur
$metrique[10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
?>
Now a simple foreach loop to control getting the names from the metrique array
<?php
include 'TabMetrique.php';
$token_auth = '*********';
$url = "http://localhost/matomo/?";
$url .= "period=month&date=2022-05-14";
$url .= "&format=JSON&module=API";
$url .= "&token_auth=$token_auth&idSite=1";
foreach ($metrique as $metric) {
//get static part of the url and add dynamic bit to it
// note i moved the dynamic part to be last, that should not matter to the api
$u = $url . "&method=$metric";
$content = json_decode(file_get_contents($u), true);
// case error
if (!$content) {
print("No data found");
} else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
}

Get the username from a login php script

I'm using a login script that I have found in Innvo.com, they do not answer... I have modified a little bit this code though, I need to retrieve the username value at the login page and I can not find the way... first I will put the code of the file (login.php) with all the classes that take care of the login, then the code that should go in the login page (access.php), where I need to retrieve the username of the logged user... thanks
FILE: login.php
// Some pre-defined constants to indicate the login state
define('LOGIN_NOERROR',0);
define('LOGIN_USER_CREDENTIALS',-1);
define('LOGIN_USER_EXISTS',-2);
define('LOGIN_USER_NONEXISTS',-3);
define('LOGIN_PASSWORD_LINKSENT',-4);
define('LOGIN_PASSWORD_BADMATCH',-5);
define('LOGIN_PASSWORD_TOOSHORT',-6);
define('LOGIN_PASSWORD_LINKEXPIRED',-7);
define('LOGIN_SESSION_EXPIRED',-8);
define('LOGIN_AWAITS_APPROVAL',-9);
class auth {
private $db = null; // Database object
private $baseurl = 'https://exemple.com/recover.php'; // a URL that will have this script included. Used for password reset emails which require a hyperlink
private $hashfunction = 'sha256'; // Hash function used, this is always computed by PHP due to mysql versions giving binary & non-binary outputs depending on its version
private $hashlength = 32; // Length of $this->hashfunction output in binary format
private $secret = 'LDGH$$$$$'; // A secret salt used in passwords alongside user-specific salts, change this
public $account = array(); // User details on successful login
private $errors = array( // Error array for when there is a UI issue for the user
LOGIN_NOERROR=>'',
LOGIN_USER_CREDENTIALS=>'<br /><h3 style="margin-left: 20px;">Usuari i/o contrasenya incorrectes!</h3>',
LOGIN_USER_EXISTS=>'<br /><h3 style="margin-left: 20px;">Aquest usuari ja existeix al sistema!</h3>',
LOGIN_USER_NONEXISTS=>'<br /><h3 style="margin-left: 20px;">Aquest usuari no existeix al sistema!</h3>',
LOGIN_PASSWORD_LINKSENT=>'<br /><h3 style="margin-left: 20px;">Li hem enviat un correu electrònic amb un enllaç per a restablir la contrasenya. Ha de seguir les instruccions que s\'esmenten al correu per a crear una contrasenya nova.</h3>',
LOGIN_PASSWORD_BADMATCH=>'<br /><h3 style="margin-left: 20px;">Les contrasenyes no coincideixen!</h3>',
LOGIN_PASSWORD_TOOSHORT=>'<br /><h3 style="margin-left: 20px;">Les contrasenyes han de tenir al menys 8 caràcters!</h3>',
LOGIN_PASSWORD_LINKEXPIRED=>'<br /><h3 style="margin-left: 20px;">L\'enllaç per a restablir la contrasenya ha caducat!</h3>',
LOGIN_SESSION_EXPIRED=>'<br /><h3 style="margin-left: 20px;">La seva sessió ha caducat!</h3>',
LOGIN_AWAITS_APPROVAL=>'<br /><h3 style="margin-left: 20px;">El seu compte espera l\'aprovació de l\'administrador del lloc, rebrà un correu quan això estigui fet!</h3>'
);
public $forms = array( // Unique HTMLforms used
'signin'=>array(
'fields'=>array(
'username'=>array('type'=>'text','placeholder'=>'Correu electrònic','icon'=>'envelope'),
'password'=>array('type'=>'password','placeholder'=>'Contrasenya','icon'=>'lock')
),
'submit'=>'Accedir',
'message'=>'<br /><h3 style="margin-left: 20px;">Introdueixi el seu correu electrònic i la seva contrasenya per accedir-hi</h3>'
),
'signup'=>array(
'fields'=>array(
'newusername'=>array('type'=>'text','placeholder'=>'Correu electrònic','icon'=>'envelope'),
'newnamelastname'=>array('type'=>'text','placeholder'=>'Nom i cognom','icon'=>'envelope'),
'newpassword'=>array('type'=>'password','placeholder'=>'Contrasenya','icon'=>'lock'),
'confirmnewpassword'=>array('type'=>'password','placeholder'=>'Confirmi la contrasenya','icon'=>'lock')
),
'submit'=>'Crear un compte nou',
'message'=>'<br /><h3 style="margin-left: 20px;">Si us plau, empleni tots els camps per a crear el seu compte.
És important que el correu sigui vàlid per a poder recuperar la contrasenya si fos el cas!</h3>'
),
'lost'=>array(
'fields'=>array(
'lostusername'=>array('type'=>'text','placeholder'=>'Correu electrònic','icon'=>'envelope')
),
'submit'=>'Envia\'m el correu',
'message'=>'<br /><h3 style="margin-left: 20px;">Introdueixi el seu correu electrònic per a rebre les instruccions de recuperació de la seva contrasenya</h3>'
),
'reset'=>array(
'fields'=>array(
'newpassword1'=>array('type'=>'password','placeholder'=>'Contrasenya','icon'=>'lock'),
'newpassword2'=>array('type'=>'password','placeholder'=>'Confirmi la contrasenya','icon'=>'lock')
),
'submit'=>'Restableix la contrasenya',
'message'=>'Estableixi una nova contrasenya pell seu usuari!'
)
);
// Initiate the database if its not connected already
public function __construct($dbobj = null) {
!$dbobj->connect_errno
or die("Failed to connect to MySQL: (" . $dbobj->connect_errno . ") " . $dbobj->connect_error);
$this->db = &$dbobj;
if(isset($_COOKIE['cddzck']) && $this->session_validate()) {
// Logged In here
if(isset($_GET['logout']))
$this->logout();
}
else {
// Sign in attempt
if(isset($_POST['username'],$_POST['password']))
$this->login($_POST['username'],$_POST['password']);
// Sign up attempt
else if(isset($_POST['newusername'],$_POST['newnamelastname'],$_POST['newpassword'],$_POST['confirmnewpassword']))
$this->user_add($_POST['newusername'],$_POST['newnamelastname'],$_POST['newpassword'],$_POST['confirmnewpassword']);
// Lost password, email submitted via form
else if(isset($_POST['lostusername']))
$this->password_reset_form($_POST['lostusername']);
// Lost password area
else if(isset($_GET['reset']) && $this->session_valid($_GET['reset'])) {
// Form not submitted
if(!isset($_POST['newpassword1'],$_POST['newpassword2']))
$this->session_check($_GET['reset'],'lostpassword');
// Form submitted
else
$this->password_reset($_GET['reset'],$_POST['newpassword1'],$_POST['newpassword2']);
}
// Login as user, for use within an admin area to impersonate a logged in user
// You should add in the session value yourself in the admin area using $this->session_add($userid,$type = 'login') and then login via this method/URI
else if(isset($_GET['cddzck']) && $this->session_valid($_GET['cddzck'])) {
if(($this->session_check($_GET['cddzck'],'login') == 0) && isset($this->account['id'])) {
setcookie("cddzck",$_GET['cddzck'],time() + 21600);
$this->redirect();
}
else
sleep(1);
}
// None shall pass (unless logged in...)
die($this->form(LOGIN_NOERROR,(isset($_GET['form']) && in_array($_GET['form'],array('signup','lost','reset')) ? $_GET['form'] : 'signin')));
}
}
// Add a session to the hash table
public function session_add($userid,$type = 'login') {
$hash = hash($this->hashfunction,bin2hex(openssl_random_pseudo_bytes($this->hashlength)));
$result = $this->query('INSERT IGNORE sessions (hash,sessiontype,userid,created)
VALUES (UNHEX(\''.$hash.'\'),\''.$type.'\','.$userid.',UNIX_TIMESTAMP())');
return $hash;
}
// Run this in a cron job once an hour to remove stale sessions and lost password requests
public function housekeeping() {
// Remove sessions older than 6 hours
// Remove password reset authentication strings after 1 hour
$this->query('DELETE FROM sessions
WHERE (sessiontype = \'login\' AND created < UNIX_TIMESTAMP() - 21600)
OR (sessiontype = \'lostpassword\' AND created < UNIX_TIMESTAMP() - 3600);');
}
// User is not logged in, display one of the forms
private function form($error,$formname) {
// Throttle failed attempts
if($formname == 'signin' && $error != 0)
sleep(1);
// Show a sign up or sign in link in the navigation
if($formname == 'signin')
$link = '<p>Crear compte nou</p>';
else
$link = '<p>Accedir</p>';
// Get all form fields and buttons
$formfields = '';
foreach($this->forms[$formname]['fields'] as $name => $field)
$formfields .= sprintf('<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="glyphicon glyphicon-%s blue"></i></span>
<input name="%s" type="%s" placeholder="%s" class="form-control">
</div>
',$field['icon'],$name,$field['type'],$field['placeholder']);
$formfields .= sprintf('<p class="center col-md-5"><button class="btn btn-primary" type="submit">%s</button></p><p> </p>',$this->forms[$formname]['submit']);
// Navigation links for sign up/sign in/forgot password
$navigation = '<ul class="nav navbar-nav navbar-left">
<li>'.$link.'</li>
<li><p>Recuperar contrasenya</p></li>
</ul>';
// Form wrapped in bootstrap 3.0 HTML with variables inserted
$form = sprintf('<div class="well col-md-5 center login-box">
<div class="alert alert-info">%s </div>
<form method="post" action="?form=%s" class="form-horizontal">%s</form>
</div>',($error != 0 ? $this->errors[$error] : $this->forms[$formname]['message']),$formname.(isset($_GET['reset']) ? '&reset='.$_GET['reset'] : ''),$formfields);
// The above HTML is taken from a bootstrap template, you can place it into an existing template as such, using %s placeholders for the content area and navigation, for example.
// echo sprintf(file_get_contents('template.html'),$navigation,$form);
// otherwise, here is the raw output that is used
echo $navigation.'<hr>'.$form;
exit(0);
}
// User is trying to log in
private function login($username,$password) {
$result = $this->query('SELECT id,active,salt,password
FROM users
WHERE active = \'1\' AND username = \''.$this->db->real_escape_string($username).'\';');
// We fetch the row because MySQL's SHA2() functions returns either a binary of hex string format depending on version.
// For simplicity the comparison is made in PHP, though it's trivial to change this to save the roundtrip of data
if(!($this->account = $result->fetch_array(MYSQLI_ASSOC)))
die($this->form(LOGIN_USER_CREDENTIALS,'signin'));
else if($this->account['password'] != pack('H*',hash($this->hashfunction,$this->secret.$this->account['salt'].$password)))
die($this->form(LOGIN_USER_CREDENTIALS,'signin'));
// Successful login, you're about to be logged in and redirected
$this->query('UPDATE users
SET lastlogin = UNIX_TIMESTAMP()
WHERE id = '.$this->account['id']);
$hash = $this->session_add($this->account['id'],'login');
setcookie("cddzck",$hash,time() + 21600);
$this->redirect();
}
// Add a new user to the database and send the mail to awaits approval
private function user_add($username,$namelastname,$password,$password2) {
if($password != $password2) // Passwords do not match
die($this->form(LOGIN_PASSWORD_BADMATCH,'signup'));
elseif(strlen($password) < 8) // Password less than 8 characters
die($this->form(LOGIN_PASSWORD_TOOSHORT,'signup'));
$salt = openssl_random_pseudo_bytes($this->hashlength);
$hash = pack("H*",hash($this->hashfunction,$this->secret.$salt.$password));
$this->query('INSERT IGNORE users (created,username,namelastname,salt,password)
VALUES (UNIX_TIMESTAMP(),\''.$this->db->real_escape_string($username).'\',\''.$this->db->real_escape_string($namelastname).'\',\''.$this->db->real_escape_string($salt).'\',\''.$this->db->real_escape_string($hash).'\');');
if($this->db->affected_rows < 1)
die($this->form(LOGIN_USER_EXISTS,'signup'));
//ach $this->login($username,$password);
$emailcontents = sprintf("Nou usuari $username ($namelastname) esperant l'aprovació pel seu compte!");
$from = "CddZ-IAC";
$headers = "From: $from";
mail('andres#chandia.net','Nou usuari al CddZ esperant l\'aprovació!', $emailcontents, $headers, '-f ' . $from);
die($this->form(LOGIN_AWAITS_APPROVAL,'signin'));
}
// Reset a password, displays the reset password form if a valid authentication string is provided
private function password_reset_form($username) {
$result = $this->query('SELECT id
FROM users
WHERE username = \''.$this->db->real_escape_string($username).'\'');
if(!($row = $result->fetch_array(MYSQLI_ASSOC)))
die($this->form(LOGIN_USER_NONEXISTS,'lost'));
$hash = $this->session_add($row['id'],'lostpassword');
$emailcontents = sprintf("Benvolgut $namelastname, ha de seguir aquest enllaç per a restablir la seva contrasenya:\n\n%s?form=reset&reset=%s\n\nSalutacions!",$this->baseurl,$hash);
// Here you would send the reset link to an email address (the whole idea of ensuring this is the rightful owner of the account
// ... but for testing purposes , the output of the email is below
mail($username,'Restableixi la seva contrasenya', $emailcontents);
//echo "<hr>$emailcontents<hr>";
die($this->form(LOGIN_PASSWORD_LINKSENT,'reset'));
}
// On successful reset password link, allow the user to reset their password
private function password_reset($reset,$password,$password2) {
if(($error = $this->session_check($reset,'lostpassword')) < 0)
die($this->form($error,'reset'));
if($password != $password2)
die($this->form(LOGIN_PASSWORD_BADMATCH,'reset'));
elseif(strlen($password) < 8)
die($this->form(LOGIN_PASSWORD_TOOSHORT,'reset'));
$salt = openssl_random_pseudo_bytes($this->hashlength);
$hash = pack('H*',hash($this->hashfunction,$this->secret.$salt.$password));
$this->query('UPDATE sessions AS s
INNER JOIN users AS u ON s.userid = u.id
SET u.salt = \''.$this->db->real_escape_string($salt).'\',u.password = \''.$this->db->real_escape_string($hash).'\'
WHERE s.hash = UNHEX(\''.$reset.'\') AND s.sessiontype = \'lostpassword\'');
$this->query('DELETE FROM sessions
WHERE hash = UNHEX(\''.$reset.'\') AND sessiontype = \'lostpassword\'');
$this->login($this->account['username'],$password);
}
// Log out
private function logout() {
$this->query('DELETE FROM sessions
WHERE sessions.sessiontype = \'login\' AND sessions.hash = UNHEX(\''.$_COOKIE['cddzck'].'\');');
setcookie("cddzck","",time() - 3600);
$this->redirect();
}
private function redirect() {
header('Location: //'.$_SERVER['HTTP_HOST'].$this->clean_uri());
exit(0);
}
// Removes login-specific details from the current URI
private function clean_uri() {
return preg_replace("'[?&](form|reset|logout|cddzck)=[^&]+'",'',$_SERVER['REQUEST_URI']);
}
// Validate that a user-provided session is syntactically valid
private function session_valid($hash) {
return preg_match("'^[a-f0-9]{".($this->hashlength*2)."}$'",$hash);
}
// Check a session cookie to see whether it's valid, and logged in or not
private function session_validate() {
if(!isset($_COOKIE['cddzck']) || !$this->session_valid($_COOKIE['cddzck']))
die($this->form(LOGIN_SESSION_EXPIRED,'signin'));
if($this->session_check($_COOKIE['cddzck'],'login') < 0) {
setcookie("cddzck","",time() - 1800);
die($this->form(LOGIN_SESSION_EXPIRED,'signin'));
}
return $this->account['id'];
}
// Look up the hash table for a given session in a given context
private function session_check($hash,$type = 'login') {
$result = $this->query('SELECT u.id,u.flags,u.created,u.lastlogin,u.username
FROM sessions AS s
INNER JOIN users AS u ON s.userid = u.id
WHERE s.hash = UNHEX(\''.$hash.'\') AND s.sessiontype = \''.$type.'\';');
if(!$this->account = $result->fetch_array(MYSQLI_ASSOC)) {
unset($_GET['reset']);
die($this->form(LOGIN_PASSWORD_LINKEXPIRED,'reset'));
}
return 0;
}
// MySQL queries
private function query($sql) {
$result = $this->db->query($sql) or die(__LINE__.' '.$this->db->error.' '.$sql);
return $result;
}
}
?>
FILE: access.php
<?php
// Call me admin.php
$db = new mysqli('localhost','dbusr','dbpasswd','dbname'); // Change these details to your own
include_once('login.php');
$_auth = new auth($db); // Anything past here is logged in
printf('<span style="float: right; margin-right: 29px;">[ Sortir ]</span>');
?>
Extend your Auth-Class in login php with that method:
public function getUsername()
{
return isset($this->account['id']) ? $this->account['username'] : "No user found.";
}
After you login you can access that username :
<?php
// Call me admin.php
$db = new mysqli('localhost','dbusr','dbpasswd','dbname'); // Change these details to your own
include_once('login.php');
$_auth = new auth($db); // Anything past here is logged in
//Username:
$username = $_auth->getUsername();
printf('<span style="float: right; margin-right: 29px;">[ Sortir ]</span>');
?>

Calling a php variable that is within an if

Can someone explain me why I cannot call a var that is set inside an if? And how to call it? I don't understand why this come empty.
I need the vars $workshop_manha and $workshop_tarde bring the values that comes from the DB.
CODE
$id = implode(",", $id);
$sql_consulta = mysql_query("SELECT * FROM pessoa WHERE id IN($id)")
or die (mysql_error());
$linha = mysql_fetch_array($sql_consulta);
$id = $linha['id'];
$nome = $linha['nome'];
$opcoes = $linha['opcoes'];
$opcoes2 = explode(":", $opcoes);
$opcoes3 = explode("+", $opcoes2[1]);
$opcao_congresso = $opcoes3[0]; // Option Congress
if(!empty($opcoes2[2])){
$opcoes4 = explode("+", $opcoes2[2]);
$pre_workshop_manha = $opcoes4[0]; // Workshop Morning Option
if($pre_workshop_manha == 'Paul Gilbert'){
$workshop_manha = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
}
if($pre_workshop_manha == 'Daniel Rijo'){
$workshop_manha = "Daniel Rijo: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
if($pre_workshop_manha == 'Maria Salvador'){
$workshop_manha = "Maria do Céu Salvador: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
}
if(!empty($opcoes2[3])){
$opcoes5 = explode("+", $opcoes2[3]);
$pre_workshop_tarde = $opcoes5[0]; // Worhshop Afternoon Option
if($pre_workshop_tarde == 'Donna Sudak'){
$workshop_tarde = "Donna Sudak: Quando as coisas ficam difíceis: Aplicações práticas da Terapia Comportamental Dialética";
}
if($pre_workshop_tarde == 'Philipp Kendall'){
$workshop_tarde = "Philipp Kendall: Estratégias dentro de tratamentos empiricamente baseados em evidências para jovens com ansiedade";
}
}
echo "Work manhã: ".$workshop_manha; //is coming empty :(
echo "Work tarde: ".$workshop_tarde; //is coming empty :(
That's because $workshop_manha and $workshop_tarde are not defined before the if statement.
Put this before the if statement:
$workshop_manha = '';
$workshop_tarde = '';
You can use them as an array().
Empty the values at the beginning :
$workshop_manha=array();
$workshop_tarde=array();
Than use the values as :
$workshop_manha[] = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
Display them as below :
if(!empty($workshop_manha)) {
foreach ($workshop_manha as $manha) {
echo "$manha <br />";
}
}
if(!empty($workshop_tarde)) {
foreach ($workshop_tarde as $tarde) {
echo "$tarde <br />";
}
}

Php switch for multilingual websites issue

I have a problem with multilingual websites... I made some code for my site, and asked a friend for opinion, and he said that server will be much slower when more people are on my domain. He said that I should use Yii or some other framework.. But I'm not familiar with frameworks. :S
So here's my code in config.php
if(isSet($_GET['lang'])){
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
} else if(isSet($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if(isSet($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
} else {
$lang = 'hr';
}
switch ($lang) {
case 'en':
$naslovnica_naslov = 'Home';
$onama_naslov = 'About us';
$restoran_naslov = 'Restaurant';
$motel_naslov = 'Motel';
$opcenito_naslov = 'General';
$galerija_naslov = 'Gallery';
$novosti_naslov = 'News & Offers';
$rezervacije_naslov = 'Reservations';
$kontakt_naslov = 'Contact';
$rezervacija_smjestaja = "Reservation of apartment";
$kontakt_informacije = "Contact info";
$kontakt_adrese_h3 = 'Adresses';
$lokacija = 'Location';
$onama_krace = 'Ideal for fun and relaxation, Kiwi Motel is located in the breasts in the town of Gruda. From here, guests can enjoy easy access to all that the lively city has to offer ...';
$vidi_vise = 'See more...';
$svecanosti = 'Ceremonies';
$proslave = '& celebrations';
break;
case 'de':
$naslovnica_naslov = 'Startseite';
$onama_naslov = 'Über uns';
$restoran_naslov = 'Restaurant';
$motel_naslov = 'Motel';
$opcenito_naslov = 'Allgemeine';
$galerija_naslov = 'Galerie';
$novosti_naslov = 'Neuigkeiten & Angeboten';
$rezervacije_naslov = 'Reservierungen';
$kontakt_naslov = 'Kontakt';
$rezervacija_smjestaja = 'Reservierung der Unterkunft';
$kontakt_informacije = 'Kontaktinfos';
$kontakt_adrese_h3 = 'Adressen';
$lokacija = 'Stelle';
$onama_krace = 'Ideal für Spaß und Entspannung, ist Kiwi Motel in der Nähe von Stadt Grude entfernt. Von hier aus können die Gäste einen einfachen Zugang zu allem, was die lebhafte Stadt zu bieten hat ...';
$vidi_vise = 'Mehr sehen...';
$svecanosti = 'Zeremonien';
$proslave = '& Feierlichkeiten';
break;
default:
$naslovnica_naslov = 'Naslovnica';
$onama_naslov = 'O nama';
$restoran_naslov = 'Restoran';
$motel_naslov = 'Motel';
$opcenito_naslov = 'Općenito';
$galerija_naslov = 'Galerija';
$novosti_naslov = 'Novosti & ponude';
$rezervacije_naslov = 'Rezervacije';
$kontakt_naslov = 'Kontakt';
$rezervacija_smjestaja = 'Rezervacija smještaja';
$kontakt_informacije = 'Kontakt informacije';
$kontakt_adrese_h3 = 'Adrese';
$lokacija = 'Lokacija';
$onama_krace = 'Idealan za zabavu i opuštanje, Motel Kiwi smješten u Grude u području grada Grude. S ovog mjesta, gosti mogu imati lagan pristup svemu što ovaj ljupki grad može ponuditi...';
$vidi_vise = 'Vidi više...';
$svecanosti = 'Svečanosti';
$proslave = '& proslave';
}
And I implement this variables after in index.php, contact.php.. So, is there any better solution? Please help!!!
Apart from agreeding with your friend about his suggest (Yii, Laravel, Symfony, Codeigniter, etc..), you can create something like this.
After this part in your config.php:
if(isSet($_GET['lang'])){
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
} else if(isSet($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if(isSet($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
} else {
$lang = 'hr';
}
insert
$langArray = require 'lang/'.$lang.'.php';
and take off of everything following.
Then create a dir where you will create your language files, for example "lang".
Then, for every language file, you create the file needed in that dir and copy the related part took off from config.php. For example..
//lang/it.php
<?php
return array(
'name' => 'Paolo',
...
);
then another lang file
//lang/en.php
<?php
return array(
'name' => 'Paul',
...
);
i think gettext is better
http://us3.php.net/gettext
but the php extension is very bad, however there are lots of gettext classes for php. just search on github :D
yii, the framework u mentioned, has a good gettext parser
it is a very bad practice to store them directly in a file. You'd better to store them in your database with a column named "lang", then
you can set if
switch($lang) { case "en" : get_data($lang); break;}
Where get_data is a functional exclusively built for your purpose, and argument $lang is a value (en, de, fr etc) which stands for WHERE clause of mySQL query.

Extract body text from Email PHP

I am currently using an imap stream to get emails from an inbox.
Everything is working fine except I am unsure how to get the body text and title of the email. If I do imap_body($connection,$message) the base 64 equivalent of the email attachment is included in the text.
I am currently using this function to get the attachments.
http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/
Well php imap's function are not fun to work with. A user on this page explains the inconsistencies with getting emails: http://php.net/manual/en/function.imap-fetchbody.php#89002
Using his helpful information I created a reliably way to get an email's body text.
$bodyText = imap_fetchbody($connection,$emailnumber,1.2);
if(!strlen($bodyText)>0){
$bodyText = imap_fetchbody($connection,$emailnumber,1);
}
$subject = imap_headerinfo($connection,$i);
$subject = $subject->subject;
echo $subject."\n".$bodyText;
My solution (works with all types and charset) :
function format_html($str) {
// Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = str_replace(chr(10), "<br>", $str);
return $str;
}
// Start
$obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno);
// Recherche de la section contenant le corps du message et extraction du contenu
$obj_section = $obj_structure;
$section = "1";
for ($i = 0 ; $i < 10 ; $i++) {
if ($obj_section->type == 0) {
break;
} else {
$obj_section = $obj_section->parts[0];
$section.= ($i > 0 ? ".1" : "");
}
}
$text = imap_fetchbody($imapLink, $obj_mail->msgno, $section);
// Décodage éventuel
if ($obj_section->encoding == 3) {
$text = imap_base64($text);
} else if ($obj_section->encoding == 4) {
$text = imap_qprint($text);
}
// Encodage éventuel
foreach ($obj_section->parameters as $obj_param) {
if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) {
$text = utf8_encode($text);
break;
}
}
// End
print format_html($text);
You Can also try these
content-type:text/html
$message = imap_fetchbody($inbox,$email_number, 2);
content-type:plaintext/text
$message = imap_fetchbody($inbox,$email_number, 1);

Categories