Related
I'm facing an issue where I have a request that works in SQL Developer or VsCode with the oracle DB add-on but in the php code, it returns 0 rows. PHP version is old and I can't do anything about that, 5.4.6, OracleDB is 11g (11.2.0.3.0).
Here is the request:
$sql = "SELECT
PATIENT_SOIGNE.NOM,
PATIENT_SOIGNE.PATRONYME AS NOM_NAISSANCE,
PATIENT_SOIGNE.PRENOM,
to_date(PATIENT_SOIGNE.DATENAIS,'YYYYMMDD') AS DDN,
decode(PATIENT_SOIGNE.SEXE,'F','Femme','M','Homme','Inconnu') AS SEXE,
PATIENT_SOIGNE.NIP,
S_ACTE_MED.CODEP1 || ' - ' || ( S_ACTE_MED.LIBELLE ) AS ACTE,
OPERATEUR.NOM AS NOM_OPERATEUR,
OPERATEUR.PRENOM AS PRENOM_OPERATEUR
FROM
PENSOINS.ACTE_RDV,
PENSOINS.RDV_STATUT RDV_STATUT,
PENSOINS.ACTE_RDV_GRP,
PENSOINS.S_ACTE_M S_ACTE_MED,
PENSOINS.EJ_PERSO OPERATEUR,
(
SELECT RESSOURCE_OPERATEUR.*, ACTE_RDV_RESA.NIACTERDV
FROM
PENSOINS.DXP_RESSOURCE RESSOURCE_OPERATEUR, PENSOINS.ACTE_RDV_RESA ACTE_RDV_RESA
WHERE
RESSOURCE_OPERATEUR.ID_RESSOURCE=ACTE_RDV_RESA.REF_RESSOURCE
AND
RESSOURCE_OPERATEUR.REF_TYPE_RESSOURCE=1
) TD_RESSOURCE_OPERATEUR,
PENSOINS.EJ_SRV RDV_SRV,
PENSOINS.VENUE,
(
SELECT A.NIACTERDV, A.NIVENUE, TD.NISEJMOUV, V.NIPATIENT, nvl(TD.NISEJOUR, V.NISEJOUR) as NISEJOUR, V.NISERVICE
FROM PENSOINS.ACTE_RDV A,
PENSOINS.VENUE V,
(
SELECT L.NIACTERDV, L.NIVENUE, DER.DATE_DER_MAJ, L.NISEJMOUV, M.NISEJOUR
FROM PENSOINS.LIEN_RDV_MVT L,
PENSOINS.MOUVEMEN M,
(
SELECT A.NIACTERDV, A.NIVENUE, max(nvl(L.DATE_MODIF, L.DATE_CREA)) DATE_DER_MAJ
FROM PENSOINS.ACTE_RDV A,
PENSOINS.LIEN_RDV_MVT L
WHERE A.NIACTERDV = L.NIACTERDV
AND L.RETRAIT = 'F'
GROUP BY A.NIVENUE,A.NIACTERDV
) DER
WHERE L.NISEJMOUV = M.NISEJMOUV
AND DER.NIACTERDV = L.NIACTERDV
AND DER.NIVENUE = L.NIVENUE
AND DER.DATE_DER_MAJ = nvl(L.DATE_MODIF, L.DATE_CREA)
AND L.RETRAIT = 'F'
) TD
WHERE A.NIVENUE(+) = V.NIVENUE
AND TD.NIACTERDV(+) = A.NIACTERDV
) TD_VENUE,
PENSOINS.PATIENT PATIENT_SOIGNE
WHERE
( PENSOINS.ACTE_RDV.STATUTRDV=RDV_STATUT.NI(+) )
AND ( PENSOINS.ACTE_RDV_GRP.NIACTERDV=PENSOINS.ACTE_RDV.NIACTERDV )
AND ( S_ACTE_MED.NIACTE=PENSOINS.ACTE_RDV_GRP.NIACTE and S_ACTE_MED.NISERVICE=PENSOINS.ACTE_RDV_GRP.NISERVICE )
AND ( OPERATEUR.NIUTILISAT(+)=TD_RESSOURCE_OPERATEUR.ID_DXCARE )
AND ( TD_RESSOURCE_OPERATEUR.NIACTERDV(+)=PENSOINS.ACTE_RDV.NIACTERDV )
AND ( PENSOINS.ACTE_RDV.NISERVICE=RDV_SRV.NISERVICE(+) )
AND ( PENSOINS.VENUE.NIVENUE=TD_VENUE.NIVENUE )
AND ( TD_VENUE.NIACTERDV=PENSOINS.ACTE_RDV.NIACTERDV(+) )
AND ( PATIENT_SOIGNE.NIPATIENT(+)=PENSOINS.VENUE.NIPATIENT )
AND RDV_STATUT.CODE|| ' - ' ||RDV_STATUT.LIBELLE IN ( 'R - Attribué','M - Modifié' )
AND RDV_SRV.CODE||' - '||RDV_SRV.NOM IN ( '07 - Diététique','08 - Endocrinologie','18 - Oncologie','19 - Ophtalmologie','24 - Pneumologie','30 - Rhumatologie','34 - Orthophonie','40 - Consultations externes','42 - Stomatologie','43 - HOPITAL DE JOUR MEDECINE','44 - Hématologie','20 - ORL','CE 02 - Anesthésie','CE 03 - Cardiologie','CE 04 - Chirurgie Orthopédique','CE 06 - Chirurgie Urologique','CE 07 - Chirurgie Viscérale','CE 08 - Hépato-gastro-entérologie','CE 09 - Chirurgie Plastique','CE 10 - Gériatrie','CE 11 - Gynécologie-Obstétrique','CE 12 - Médecine interne','CE 14 - Pédiatrie','CE 15 - Tabacologie','CE 16 - Chirurgie Vasculaire','16 - Néphrologie' )
AND substr(PENSOINS.ACTE_RDV.HORAIRE, 1, 8) = '".$date_next."'
GROUP BY
PATIENT_SOIGNE.NOM,
PATIENT_SOIGNE.PATRONYME,
PATIENT_SOIGNE.PRENOM,
to_date(PATIENT_SOIGNE.DATENAIS,'YYYYMMDD'),
decode(PATIENT_SOIGNE.SEXE,'F','Femme','M','Homme','Inconnu'),
PATIENT_SOIGNE.NIP,
S_ACTE_MED.CODEP1 || ' - ' || ( S_ACTE_MED.LIBELLE ),
OPERATEUR.NOM,
OPERATEUR.PRENOM";
And the code which uses it:
$date_next = date_next_day();
$db_o = connexion_oracle_dxcare();
$parsed = oci_parse($db_o, $sql);
$ru=oci_execute($parsed);
if (!$ru) { //doesn't show anything
$e = oci_error($parsed);
print htmlentities($e['message']);
print "\n<pre>\n";
print htmlentities($e['sqltext']);
printf("\n%".($e['offset']+1)."s", "^");
print "\n</pre>\n";
}
$num_rows = oci_fetch_all($parsed, $res); //returns 0 rows
var_dump($res); //show me all the column names but no datas inside
The date format is good, my function return this format 'YYYYMMDD' which is working.
The var dump shows :
array(9) { ["NOM"]=> array(0) { } ["NOM_NAISSANCE"]=> array(0) { } ["PRENOM"]=> array(0) { } ["DDN"]=> array(0) { } ["SEXE"]=> array(0) { } ["NIP"]=> array(0) { } ["ACTE"]=> array(0) { } ["NOM_OPERATEUR"]=> array(0) { } ["PRENOM_OPERATEUR"]=> array(0) { } }
I surely miss something but I can't find it. Any ideas?
EDIT:
So I tested if the problem was with the accents, but this request:
SELECT PENSOINS.EJ_SRV.NOM from PENSOINS.EJ_SRV WHERE PENSOINS.EJ_SRV.NOM LIKE 'Dié%'
worked fine (even if it's displayed with é in the browser afterward).
I changed this part :
AND substr(PENSOINS.ACTE_RDV.HORAIRE, 1, 8) = '".$date_next."'
GROUP BY
PATIENT_SOIGNE.NOM,
PATIENT_SOIGNE.PATRONYME,
PATIENT_SOIGNE.PRENOM,
to_date(PATIENT_SOIGNE.DATENAIS,'YYYYMMDD'),
multiple times, using some to_char, trunc, to_date but nothing worked.
Concerning the dates, I was able to make this statement:
SELECT PENSOINS.ACTE_RDV.HORAIRE from PENSOINS.ACTE_RDV WHERE substr(PENSOINS.ACTE_RDV.HORAIRE, 1, 8) = :date_test_bv
worked. Here :date_test_bv is a binding variable of a string like 20140415
So now I'm back at
AND RDV_SRV.CODE||' - '||RDV_SRV.NOM IN ( '07 - Diététique','08 - Endocrinologie','18 - Oncologie','19 - Ophtalmologie','24 - Pneumologie','30 - Rhumatologie','34 - Orthophonie','40 - Consultations externes','42 - Stomatologie','43 - HOPITAL DE JOUR MEDECINE','44 - Hématologie','20 - ORL','CE 02 - Anesthésie','CE 03 - Cardiologie','CE 04 - Chirurgie Orthopédique','CE 06 - Chirurgie Urologique','CE 07 - Chirurgie Viscérale','CE 08 - Hépato-gastro-entérologie','CE 09 - Chirurgie Plastique','CE 10 - Gériatrie','CE 11 - Gynécologie-Obstétrique','CE 12 - Médecine interne','CE 14 - Pédiatrie','CE 15 - Tabacologie','CE 16 - Chirurgie Vasculaire','16 - Néphrologie' )
AND substr(PENSOINS.ACTE_RDV.HORAIRE, 1, 8) = :date_bv
GROUP BY
PATIENT_SOIGNE.NOM,
PATIENT_SOIGNE.PATRONYME,
PATIENT_SOIGNE.PRENOM,
to_date(PATIENT_SOIGNE.DATENAIS,'YYYYMMDD'),
decode(PATIENT_SOIGNE.SEXE,'F','Femme','M','Homme','Inconnu'),
PATIENT_SOIGNE.NIP,
S_ACTE_MED.CODEP1 || ' - ' || ( S_ACTE_MED.LIBELLE ),
OPERATEUR.NOM,
OPERATEUR.PRENOM
Knowing that the binded string date produces a successful result and that using the accents is not a problem.
I have 0 error messages, nor from PHP or Oracle, just empty rows like the var dump I showed earlier.
At that point I really don't understand where the problem could be.
Implicit date conversion is responsible for most queries that work differently in different clients. Date formats default to the NLS_DATE_FORMAT value set at the system level, but many clients will override that value by setting the parameter at the session level.
Specifically, these two expressions could have problems:
substr(PENSOINS.ACTE_RDV.HORAIRE, 1, 8) = '".$date_next."
...
to_date(PATIENT_SOIGNE.DATENAIS,'YYYYMMDD')
Many people solve these problems by forcing all clients to change their settings, but a better permanent solution is always specify the desired format, or to avoid date conversion entirely. Assuming those two columns are date values, it would be safer to rewrite the expressions to this:
substr(to_char(PENSOINS.ACTE_RDV.HORAIRE, 1, 8), 'YYYYMMDD') = '".$date_next."'
...
trunc(PATIENT_SOIGNE.DATENAIS)
(I'm not sure how PHP works, there may be a better way to pass in the $date_next as a date instead of a string.)
Another wild guess is that the non-ASCII strings are causing problems somewhere:
RDV_SRV.CODE||' - '||RDV_SRV.NOM IN ( '07 - Diététique', ...
Take a look at the output from select sql_fulltext from gv$sql where lower(sql_fulltext) like '%07 - Di%; to ensure that the query is getting passed to Oracle correctly. If some file or process doesn't support non-ASCII characters, then you may need to store the Unicode strings like this:
RDV_SRV.CODE||' - '||RDV_SRV.NOM IN ( '07 - Di'||unistr('\00E9')|'t'||unistr('\00E9')||'tique', ...
I am writing in PHP.
What I am trying to do is something like a configurable product in Magento2 or variable product in Woocommerce. I am asking the user to enter attributes to the product, like color, size, etc'.
Think of each attribute as a attribute category which contains attributes inside it, e.g 'color' will have attributes like 'red', 'green', 'blue' and so on. Size will have attributes like 'large', 'small', 'medium' and so on.
Now, I need to make a loop which takes all sizes, colors and other chosen attributes and returns all the possible configurations. At the same time the amount of attributes to loop through isn't predefined since the user can add or remove attributes.
For example if I have this:
Color - - - - - - - - Size - - - - - - - - Shape
Red - - - - - - - - - Large - - - - - - - Square
Green - - - - - - - - Medium - - - - - - - Rounded
Blue - - - - - - - - Small - - - - - - - -
So I will have to have every color with every size and shape:
Red - Large - Square
Red - Large - Rounded
Red - Medium - Square
Red - Medium - Rounded
Red - Small - Square
Red - Small - Rounded
And the same with the other attributes.
What is the best practice to achive it?
You will need recursion for this.
function getCombinations($attributes){
$combinations = [];
buildCombinationChain($attributes,0,[],$combinations);
// encode combinations to desired string format
$result = [];
foreach ($combinations as $combination) {
$result[] = implode(' - ', $combination);
}
return $result;
}
function buildCombinationChain($attributes,$index,$chain,&$output){
if($index>=count($attributes)){
// we have reached the last attribute, stop recursion and push the current chain to the output array
$output[] = $chain;
return;
}
foreach ($attributes[$index] as $attribute) {
$new_chain = $chain; // create a copy of the current chain
$new_chain[] = $attribute; // and add the current attribute to it
buildCombinationChain($attributes,$index+1,$new_chain,$output); // continue recursively on the next attribute group
}
}
$attributes = [
['Red', 'Green', 'Blue'],
['Large', 'Medium', 'Small'],
['Square', 'Rounded']
];
echo json_encode(getCombinations($attributes));
I want to show specific values according to specific keys in a array.
there are some keys which are fetched from database then i want to show its meaningful values like:
array('12_01'=>'12:00 - 01:00','01_02'=>'01:00 - 02:00');
here is code:
<?php echo implode(',',$selected_hours); ?>
And here is Array:
$hourshow = array('12_01'=>'12:00 - 01:00',
'01_02'=>'01:00 - 02:00',
'02_03'=>'02:00 - 01:03',
'03_04'=>'03:00 - 04:00',
'04_05'=>'04:00 - 05:00',
'05_06'=>'05:00 - 06:00',
'06_07'=>'06:00 - 07:00',
'07_08'=>'07:00 - 08:00',
'07_09'=>'08:00 - 09:00',
'09_10'=>'09:00 - 10:00',
'10_11'=>'10:00 - 11:00',
'11_12'=>'11:00 - 12:00',
'12_13'=>'12:00 - 13:00',
'13_14'=>'13:00 - 14:00',
'14_15'=>'14:00 - 15:00',
'15_16'=>'15:00 - 16:00',
'16_17'=>'16:00 - 17:00',
'17_18'=>'17:00 - 18:00',
'18_19'=>'18:00 - 19:00',
'19_20'=>'19:00 - 20:00',
'20_21'=>'20:00 - 21:00',
'21_22'=>'21:00 - 22:00',
'22_23'=>'22:00 - 23:00',
'23_24'=>'23:00 - 24:00',
);
$keys = array('12_01','01_02','02_03','03_04','04_05','05_06','06_07','07_08','08_09','09_10','10_11','11_12');
$result = array();
foreach($keys as $value){
$val = explode('_',$value);
$result[$value] = $val[0].':00 - '.$val[1].':00';
}
echo '<pre>';print_r($result);exit;
You can try with this code. You will getting result in result array.
Use ksort():
$hourshow = array(...);
ksort($hourshow);
// $hourshow is now sorted according to key.
Dont know if I get your question correctly, but this should be what you are looking for
array_intersect_key($hourshow, array_flip($yourWantedHoursArray));
#Ashish Vyas Simply do it like below
<?php
$youKeysFetchedFromDb = array("12_01", "01_02"); //suppose
foreach($youKeysFetchedFromDb as $value){
echo $hourshow[$value];
}
I need to convert the "age" of an item (in days), into an hexadecimal value, where oldest item = max color = D9D8C9, and most recent = min color = FFFFFF.
items beyond age 365 get color D9D8C9.
items beneath age 7 get color FFFFFF.
According to these min and max colors, how can i find the color of any item younger than 365 days and older than 7 days?
Eventually, I'll do it in PHP but pseudocode example is fine.
Essentially, you're looking for a way to arbitrarily map one range onto another (7-365 should be mapped of FFFFFF - D9D8D9).
First things first: converting decimal to hex is quite easy:
$age = mt_rand(1,600);
if ($age > 365) $hex = 'D9D8D9';
elseif ($age < 7) $hex = 'FFFFFF';
else $hex = str_pad(dechex($age), 6, '0', STR_PAD_LEFT);
What I do is simply check if $age is greater then 365, if so, I assign the D9D8D9 constant, if it's less than 7, I assign FFFFFF. In all other cases, I simply convert the number to hexadecimal, and pad the resulting string to 6 chars, using 0, so 255 would become FF, and is padded to 0000FF.
But to map a range on a range, we'll have to find out how a step of 1 in the smallest range scales to the larger one(s). It's a simple "rule of three": calculate the equivalent of 1 in both scales, and multiply. Then apply the same range-bounds and you're there.
The colour-range you're using is FFFFFF through D9D8D9, or to put it in decimals: 16777215 through 14276809. This leaves us with a range of 2500406, versus 365-7 (or 358) days. Each single day, therefore is "worth" 6984.374301676 ((D9D8D9-FFFFFF)/(365-7)) in our colour range.
Put it all together and you have 2 options: calculate the distance from FFFFFF or D9D8D9, but as far as the result is concerned, it doesn't matter which one you choose.
<CrLowBound> - (<value>-<VLowBound>)*<CrStep>
//or
<CrHighBound> - (<VHighBound> - <value>)*<CrStep>
Both simply compute the value in the colour range that corresponds to the given value. CrLowBound and CrHighBound are FFF and D9D8D9 respectively, in much the same way: VLowBound and VHighBound are 6 and 366. CrStep is 6984.374301676. I've explained how I got these values.
$age = mt_rand(1,600);
if ($age > 365) $hex = 'D9D8D9';
elseif ($age < 7) $hex = 'FFFFFF';
else $hex = str_pad(dechex(14276809-(round((366-$dec)*6984.374301676))), 6, '0', STR_PAD_LEFT);
//Or:
$hex = str_pad(dechex(16777215-(round(($dec-6)*6984.374301676))), 6, '0', STR_PAD_LEFT);
This will more evenly spread the range of colours within the D9D8D9 to FFFFFF range: the older the item, the closer the color will be to D9D8D9, the more recent, the closer it is to FFFFFF.
For example, if the age is 117, the "colour" will be 1A6E1D:
//age (max-age)*worth hex
117 == 1732125 == 1a6e1d
Tested with the following code:
function getColour($dec)
{
if ($dec > 365) return 'D9D8D9';
if ($dec < 7) return 'FFFFFF';
return strtoupper(
str_pad(
dechex(14276809-(round((366-$dec)*6984.374301676))),
6,
'0',
STR_PAD_LEFT
)
);
}
$days = range(6,366);
$colours = array();
foreach($days as $day) $colours[$day] = getColour($day);
$out = array_chunk($colours, 8);
foreach($out as $k => $chunk) $out[$k] = implode(' - ', $chunk);
echo implode('<br>', $out);
And got this as output:
FFFFFF - B3964B - B3B193 - B3CCDB - B3E824 - B4036C - B41EB4 - B439FD
B45545 - B4708E - B48BD6 - B4A71E - B4C267 - B4DDAF - B4F8F7 - B51440
B52F88 - B54AD1 - B56619 - B58161 - B59CAA - B5B7F2 - B5D33A - B5EE83
B609CB - B62514 - B6405C - B65BA4 - B676ED - B69235 - B6AD7D - B6C8C6
B6E40E - B6FF57 - B71A9F - B735E7 - B75130 - B76C78 - B787C0 - B7A309
B7BE51 - B7D99A - B7F4E2 - B8102A - B82B73 - B846BB - B86203 - B87D4C
B89894 - B8B3DD - B8CF25 - B8EA6D - B905B6 - B920FE - B93C46 - B9578F
B972D7 - B98E20 - B9A968 - B9C4B0 - B9DFF9 - B9FB41 - BA1689 - BA31D2
BA4D1A - BA6863 - BA83AB - BA9EF3 - BABA3C - BAD584 - BAF0CC - BB0C15
BB275D - BB42A6 - BB5DEE - BB7936 - BB947F - BBAFC7 - BBCB0F - BBE658
BC01A0 - BC1CE9 - BC3831 - BC5379 - BC6EC2 - BC8A0A - BCA552 - BCC09B
BCDBE3 - BCF72C - BD1274 - BD2DBC - BD4905 - BD644D - BD7F95 - BD9ADE
BDB626 - BDD16F - BDECB7 - BE07FF - BE2348 - BE3E90 - BE59D8 - BE7521
BE9069 - BEABB2 - BEC6FA - BEE242 - BEFD8B - BF18D3 - BF341B - BF4F64
BF6AAC - BF85F5 - BFA13D - BFBC85 - BFD7CE - BFF316 - C00E5E - C029A7
C044EF - C06038 - C07B80 - C096C8 - C0B211 - C0CD59 - C0E8A1 - C103EA
C11F32 - C13A7B - C155C3 - C1710B - C18C54 - C1A79C - C1C2E4 - C1DE2D
C1F975 - C214BE - C23006 - C24B4E - C26697 - C281DF - C29D27 - C2B870
C2D3B8 - C2EF01 - C30A49 - C32591 - C340DA - C35C22 - C3776A - C392B3
C3ADFB - C3C944 - C3E48C - C3FFD4 - C41B1D - C43665 - C451AD - C46CF6
C4883E - C4A387 - C4BECF - C4DA17 - C4F560 - C510A8 - C52BF0 - C54739
C56281 - C57DCA - C59912 - C5B45A - C5CFA3 - C5EAEB - C60633 - C6217C
C63CC4 - C6580D - C67355 - C68E9D - C6A9E6 - C6C52E - C6E076 - C6FBBF
C71707 - C7324F - C74D98 - C768E0 - C78429 - C79F71 - C7BAB9 - C7D602
C7F14A - C80C92 - C827DB - C84323 - C85E6C - C879B4 - C894FC - C8B045
C8CB8D - C8E6D5 - C9021E - C91D66 - C938AF - C953F7 - C96F3F - C98A88
C9A5D0 - C9C118 - C9DC61 - C9F7A9 - CA12F2 - CA2E3A - CA4982 - CA64CB
CA8013 - CA9B5B - CAB6A4 - CAD1EC - CAED35 - CB087D - CB23C5 - CB3F0E
CB5A56 - CB759E - CB90E7 - CBAC2F - CBC778 - CBE2C0 - CBFE08 - CC1951
CC3499 - CC4FE1 - CC6B2A - CC8672 - CCA1BB - CCBD03 - CCD84B - CCF394
CD0EDC - CD2A24 - CD456D - CD60B5 - CD7BFE - CD9746 - CDB28E - CDCDD7
CDE91F - CE0467 - CE1FB0 - CE3AF8 - CE5641 - CE7189 - CE8CD1 - CEA81A
CEC362 - CEDEAA - CEF9F3 - CF153B - CF3084 - CF4BCC - CF6714 - CF825D
CF9DA5 - CFB8ED - CFD436 - CFEF7E - D00AC7 - D0260F - D04157 - D05CA0
D077E8 - D09330 - D0AE79 - D0C9C1 - D0E50A - D10052 - D11B9A - D136E3
D1522B - D16D73 - D188BC - D1A404 - D1BF4D - D1DA95 - D1F5DD - D21126
D22C6E - D247B6 - D262FF - D27E47 - D29990 - D2B4D8 - D2D020 - D2EB69
D306B1 - D321F9 - D33D42 - D3588A - D373D3 - D38F1B - D3AA63 - D3C5AC
D3E0F4 - D3FC3C - D41785 - D432CD - D44E16 - D4695E - D484A6 - D49FEF
D4BB37 - D4D67F - D4F1C8 - D50D10 - D52859 - D543A1 - D55EE9 - D57A32
D5957A - D5B0C2 - D5CC0B - D5E753 - D6029C - D61DE4 - D6392C - D65475
D66FBD - D68B05 - D6A64E - D6C196 - D6DCDF - D6F827 - D7136F - D72EB8
D74A00 - D76548 - D78091 - D79BD9 - D7B722 - D7D26A - D7EDB2 - D808FB
D82443 - D83F8B - D85AD4 - D8761C - D89165 - D8ACAD - D8C7F5 - D8E33E
D8FE86 - D919CE - D93517 - D9505F - D96BA8 - D986F0 - D9A238 - D9BD81
D9D8D9
Codepad with 2 versions of this code
I need help encoding a link. Basically, upon completion of an event, I run a function that redirects the user to a link. The link is taken directly from a PHP variable.
<?php
$url = "http://google.com/";
$mylink = "<a href=\"" . $url . "\">";
echo $mylink;
?>
My question is, how can I echo $mylink, without having the $url shown in the source code. I want the output of my link to still go to $url, but not show the value of $url ANYWHERE in my source code.
How can I achieve this?
Here is one sure way to do this: you could store in your database (or files on the server) the link and an ID. Instead of the actual url, print a link to a php script you write which passes in that ID. This page you write simply looks up the associated ID and uses a header to redirect to the link.
For Example: you write a script redirector.php then the links in the page source point to "redirector.php?id=10293". The redirector script looks up what is id 10293 and sees http://www.example.com then calls
header('Location: http://www.example.com/');
This way the links are only in the server side and never show up in your source code. As user pst suggested in the comments you could also use something like tinyurl which operates on this same principal.
Any other methods will rely on some sort of encryption which could be decrypted because the actual data (link url) is in the page source albeit obscured.
EDIT : here is an example of how you could write your two scripts -- the one which is printing the urls and the one which would redirect. Assuming a table urls exists in your MySQL db add a column called 'hash' or 'id' or something and in the script which will print the urls add the lines:
$hash = sha1($url);
mysql_query("UPDATE url_table SET hash = '$hash' WHERE url = '$url'");
$printURL = "../redirect.php?id=$hash";
print "<a href='$printURL'>click me to go somewhere you don't know yet</a>";
now in another file named redirect.php put the following code:
<?php
//connect to db or include files
$givenHash = $_REQUEST['id']; $realURL = $_SERVER['HTTP_REFERER'];
$result = mysql_query("SELECT url FROM url_table WHERE hash = '$givenHash'");
while($row=mysql_fetch_assoc($result)) {
$realURL = $row['url'];
}
header("Location: $realURL");
?>
This will either send them to the url you want if it is found in the db or drop them back to the page they were on before they clicked the link. If you only have a few links that are known in advance then you can do this trick without the use of databases by just using a look up array. Hope this helps.
You could do it with javascript, and some encryption like TEA.
Something like...
Include TEA function in javascript
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Block TEA (xxtea) Tiny Encryption Algorithm implementation in JavaScript */
/* (c) Chris Veness 2002-2010: www.movable-type.co.uk/tea-block.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Algorithm: David Wheeler & Roger Needham, Cambridge University Computer Lab */
/* http://www.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html (1994) */
/* http://www.cl.cam.ac.uk/ftp/users/djw3/xtea.ps (1997) */
/* http://www.cl.cam.ac.uk/ftp/users/djw3/xxtea.ps (1998) */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Tea = {}; // Tea namespace
/*
* encrypt text using Corrected Block TEA (xxtea) algorithm
*
* #param {string} plaintext String to be encrypted (multi-byte safe)
* #param {string} password Password to be used for encryption (1st 16 chars)
* #returns {string} encrypted text
*/
Tea.encrypt = function(plaintext, password) {
if (plaintext.length == 0) return(''); // nothing to encrypt
// convert string to array of longs after converting any multi-byte chars to UTF-8
var v = Tea.strToLongs(Utf8.encode(plaintext));
if (v.length <= 1) v[1] = 0; // algorithm doesn't work for n<2 so fudge by adding a null
// simply convert first 16 chars of password as key
var k = Tea.strToLongs(Utf8.encode(password).slice(0,16));
var n = v.length;
// ---- <TEA coding> ----
var z = v[n-1], y = v[0], delta = 0x9E3779B9;
var mx, e, q = Math.floor(6 + 52/n), sum = 0;
while (q-- > 0) { // 6 + 52/n operations gives between 6 & 32 mixes on each word
sum += delta;
e = sum>>>2 & 3;
for (var p = 0; p < n; p++) {
y = v[(p+1)%n];
mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);
z = v[p] += mx;
}
}
// ---- </TEA> ----
var ciphertext = Tea.longsToStr(v);
return Base64.encode(ciphertext);
}
/*
* decrypt text using Corrected Block TEA (xxtea) algorithm
*
* #param {string} ciphertext String to be decrypted
* #param {string} password Password to be used for decryption (1st 16 chars)
* #returns {string} decrypted text
*/
Tea.decrypt = function(ciphertext, password) {
if (ciphertext.length == 0) return('');
var v = Tea.strToLongs(Base64.decode(ciphertext));
var k = Tea.strToLongs(Utf8.encode(password).slice(0,16));
var n = v.length;
// ---- <TEA decoding> ----
var z = v[n-1], y = v[0], delta = 0x9E3779B9;
var mx, e, q = Math.floor(6 + 52/n), sum = q*delta;
while (sum != 0) {
e = sum>>>2 & 3;
for (var p = n-1; p >= 0; p--) {
z = v[p>0 ? p-1 : n-1];
mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);
y = v[p] -= mx;
}
sum -= delta;
}
// ---- </TEA> ----
var plaintext = Tea.longsToStr(v);
// strip trailing null chars resulting from filling 4-char blocks:
plaintext = plaintext.replace(/\0+$/,'');
return Utf8.decode(plaintext);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
// supporting functions
Tea.strToLongs = function(s) { // convert string to array of longs, each containing 4 chars
// note chars must be within ISO-8859-1 (with Unicode code-point < 256) to fit 4/long
var l = new Array(Math.ceil(s.length/4));
for (var i=0; i<l.length; i++) {
// note little-endian encoding - endianness is irrelevant as long as
// it is the same in longsToStr()
l[i] = s.charCodeAt(i*4) + (s.charCodeAt(i*4+1)<<8) +
(s.charCodeAt(i*4+2)<<16) + (s.charCodeAt(i*4+3)<<24);
}
return l; // note running off the end of the string generates nulls since
} // bitwise operators treat NaN as 0
Tea.longsToStr = function(l) { // convert array of longs back to string
var a = new Array(l.length);
for (var i=0; i<l.length; i++) {
a[i] = String.fromCharCode(l[i] & 0xFF, l[i]>>>8 & 0xFF,
l[i]>>>16 & 0xFF, l[i]>>>24 & 0xFF);
}
return a.join(''); // use Array.join() rather than repeated string appends for efficiency in IE
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Base64 class: Base 64 encoding / decoding (c) Chris Veness 2002-2010 */
/* note: depends on Utf8 class */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Base64 = {}; // Base64 namespace
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, no newlines are added.
*
* #param {String} str The string to be encoded as base-64
* #param {Boolean} [utf8encode=false] Flag to indicate whether str is Unicode string to be encoded
* to UTF8 before conversion to base64; otherwise string is assumed to be 8-bit characters
* #returns {String} Base64-encoded string
*/
Base64.encode = function(str, utf8encode) { // http://tools.ietf.org/html/rfc4648
utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? Utf8.encode(str) : str;
c = plain.length % 3; // pad string to length of multiple of 3
if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
// note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
for (c=0; c<plain.length; c+=3) { // pack three octets into four hexets
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>18 & 0x3f;
h2 = bits>>12 & 0x3f;
h3 = bits>>6 & 0x3f;
h4 = bits & 0x3f;
// use hextets to index into code string
e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
coded = e.join(''); // join() is far faster than repeated string concatenation in IE
// replace 'A's from padded nulls with '='s
coded = coded.slice(0, coded.length-pad.length) + pad;
return coded;
}
/**
* Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, newlines are not catered for.
*
* #param {String} str The string to be decoded from base-64
* #param {Boolean} [utf8decode=false] Flag to indicate whether str is Unicode string to be decoded
* from UTF8 after conversion from base64
* #returns {String} decoded string
*/
Base64.decode = function(str, utf8decode) {
utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? Utf8.decode(str) : str;
for (var c=0; c<coded.length; c+=4) { // unpack four hexets into three octets
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>16 & 0xff;
o2 = bits>>>8 & 0xff;
o3 = bits & 0xff;
d[c/4] = String.fromCharCode(o1, o2, o3);
// check for padding
if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
}
plain = d.join(''); // join() is far faster than repeated string concatenation in IE
return utf8decode ? Utf8.decode(plain) : plain;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Utf8 class: encode / decode between multi-byte Unicode characters and UTF-8 multiple */
/* single-byte character encoding (c) Chris Veness 2002-2010 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Utf8 = {}; // Utf8 namespace
/**
* Encode multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only)
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
*
* #param {String} strUni Unicode string to be encoded as UTF-8
* #returns {String} encoded string
*/
Utf8.encode = function(strUni) {
// use regular expressions & String.replace callback function for better efficiency
// than procedural approaches
var strUtf = strUni.replace(
/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f); }
);
strUtf = strUtf.replace(
/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f); }
);
return strUtf;
}
/**
* Decode utf-8 encoded string back into multi-byte Unicode characters
*
* #param {String} strUtf UTF-8 string to be decoded back to Unicode
* #returns {String} decoded string
*/
Utf8.decode = function(strUtf) {
// note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char!
var strUni = strUtf.replace(
/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
function(c) { // (note parentheses for precence)
var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f);
return String.fromCharCode(cc); }
);
strUni = strUni.replace(
/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
function(c) { // (note parentheses for precence)
var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f;
return String.fromCharCode(cc); }
);
return strUni;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Then for testing create an html anchor element, and set it's vale by de-crypting a pre-calculated encrypted string
document.body.innerHTML = "<a href='no_access' id='targetElement'>the link</a>"
// pre-calculated result: AAvpH77xTCdBO/qAb5yHOFVF3vlbi1XS6Dd5eA==
// By doing: Tea.encrypt('http://secret.encrypted.url/','some_password')
document.getElementById('targetElement').href=Tea.decrypt('AAvpH77xTCdBO/qAb5yHOFVF3vlbi1XS6Dd5eA==','some_password')