Comparing URL strings in PHP - php

I'm trying to use the query from a GET url to determine the content of a page.
This is what I have (sentences edited for clarity):
<?php
//decalre variables
$title ='';
$welcome = '';
$params = '';
$params = $_SERVER['QUERY_STRING'];
echo $_SERVER['QUERY_STRING'];
echo $params;
if ($params='') {
header('start.html') ;
} else {
if ($params === "selection=republic") {
//echo $params;
//echo 'Republic';
$title = "Private";
$welcome = "Our .";
$signoff = "The Republic will strike back!";
}
else if ($params === "selection=rebels") {
//echo $params;
//echo 'Rebels';
$title = "Comrade";
$welcome = "Hey comrade, welcome to the Underground Network!";
$declaration="You see,o's!";
$signoff = "Rebel!!";
}
else if ($params === "selection=robots"){
//echo $params;
//echo 'Robots';
$title = "Bit";
$welcome = "Our data ";
$declaration="Knowledge w.";
$signoff = "ed now.";
}
else {
echo 'There was an error - please go back.';
}
}
The first echo shows the correct URL, but the comparison gets stuck at the third option.
Help!

This comes from the triple = sign, that compares the value and the type. You should see the difference here.
I suggest you only use two equals and by the way, you could ease your code by using the $_GET['selection'] variable instead:
<?php
//decalre variables
$title ='';
$welcome = '';
$params = '';
$params = $_SERVER['QUERY_STRING'];
echo $_SERVER['QUERY_STRING'];
echo $params;
if (!isset($_GET['selection']) { // Check whether selection is set
header('start.html') ;
} else {
if ($_GET['selection'] == "republic") {
//echo $params;
//echo 'Republic';
$title = "Private";
$welcome = "Our .";
$signoff = "The Republic will strike back!";
}
else if ($_GET['selection'] == "rebels") {
//echo $params;
//echo 'Rebels';
$title = "Comrade";
$welcome = "Hey comrade, welcome to the Underground Network!";
$declaration="You see,o's!";
$signoff = "Rebel!!";
}
else if ($_GET['selection'] == "robots"){
//echo $params;
//echo 'Robots';
$title = "Bit";
$welcome = "Our data ";
$declaration="Knowledge w.";
$signoff = "ed now.";
}
else {
echo 'There was an error - please go back.';
}
}

There are way better ways of parsing the query string than $SERVER['QUERY_STRING'], specifically you can use $_GET to access a specific parameter. Example: www.example.com?name=Dave&age=30...
to get the name, you can do $_GET['name'] and it will return Dave. I think a better way to do this would be something like:
$selection = $_GET['selection'];
if (empty($selection)) {
header('start.html') ;
}
else {
$vars = array(
'republic'=>array('title'=>'Private', 'welcome'=> 'Our .', 'declaration'=>'', 'signoff' => 'The Replublic will strike back'),
'rebels'=>array('title'=>'Comrade', 'welcome' => "Hey comrade, welcome to the Underground Network!", 'declaration'=>"You see,o's!",'signoff' => "Rebel!!"),
'robots'=>array('title'=>'Bit', 'welcome'=>'Our data', 'declaration'=>'Knowlegge W', 'signoff'=>'Ed now')
);
list($title, $welcome, $declaration, $signoff) = $vars[$selection];
}

Related

Shoutcast Script Does Not Work with Names that Have an Apostrophe

Please help me I don't know what to do. Tried urlencode but does not work
UTF-8 does not works. I need the script can read apostrophe for display image but nothing to do I am not a programmer and now I need your help for solve this problem.
<?php
$cover_d = 'http://metalrockpopradio.caramania.com/blackblack.gif';
$sc_url_ip = "69.175.13.131";
$sc_url_port = "8050";
function getNowPlaying($sc_url_ip,$sc_url_port) {
$open = fsockopen($sc_url_ip,$sc_url_port,$errno,$errstr,'.5');
if ($open) {
fputs($open,"GET /7.html HTTP/1.1\nUser-Agent:Mozilla\n\n");
stream_set_timeout($open,'1');
$read = fread($open,200);
$text = explode(",",$read);
if($text[6] == '' || $text[6] == '</body></html>') {
$msg = ' live stream ';
} else {
$msg = $text[6];
}
$text = $msg;
} else {
return false;
}
fclose($open);
return $text;
}
$current_song = getNowPlaying($sc_url_ip,$sc_url_port);
$current_song = iconv('ISO-8859-1', 'UTF-8', $current_song);
$singinfo = explode(" - ",$current_song);
$artist = urlencode($singinfo[0]);
$titel = urlencode(strip_tags($singinfo[1]));
$imgurl = #file_get_contents("http://api.depubliekeomroep.nl /anp/albumart.php?artiest=".$artist."&titel=".$titel."&size=extralarge");
if ($imgurl != "") {
print "<img src=\"" . $imgurl . "\">";
} else {
print "<img src=\"" . $cover_d . "\">";
}
?>
We are talking about ASCII 39 yes? I mean this even works...
<?php
$artist = "Tom Petty";
$title = "I won't back down";
$uri = "http://api.depubliekeomroep.nl/anp/albumart.php?artiest={$artist}&titel={$title}&size=extralarge";
var_dump(file_get_contents($uri));
'https://lastfm-img2.akamaized.net/i/u/300x300/05600d9c77a9288add89fac53d3482e7.png'
(length=82)
Maybe provide an example of the actual string giving you trouble?
While the above works for me it might be dependent on underlying wrapper.
Best practice would be:
$title = urlencode("I won't back down");

How to add usernames to this code?

I'm a complete newb in PHP, and the only reason I got this far was because I was trying to guess what everything does. I guess I was lucky that it worked this far.
So basically, I'm using the PHP Wake On LAN code that I found here to make a simple page that I log into, to remotely turn on my computer. I decided to add a username, rather than just a password, so maybe I could have multiple users. I've done everything successfully so far except one thing. When I log in, check my computer, and hit "Wake all selected", it logs me out immediately and doesn't send the magic packet. Any tips on what I could change to fix this? As soon as I remove the 'and' and the username bit in the if statement that checks for both user and pass to be correct, it works. But then there's no user and pass verifying going on. The if statement I'm talking about is the second if under the === Test for password protection === part.
You can demo the code on my site to see the issue in action here: http://trivisionzero.com/wol/
Just use 'user', 'pass'. (to recreate it, select any computer and press wake button)
Full code so far:
<center>
<br><br><br><br><br>
<?php
/* ============================== Configuration settings ====================================== */
/* List of PCs that may be woken */
$config_network_data_array[] = array("name" => "Shane-EPC", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
$config_network_data_array[] = array("name" => "Demo", "MAC" => "changed for security", "IP" => "changed for security", "WakeIP" =>
"changed for security");
// Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
$socket_number = "7";
$my_password = 'pass';
$my_username = 'user';
$html_title = '<H2>TrivisionZero PC Waker</H2>';
$config_table_columns = array('name', 'IP', 'MAC', 'links');
# The following function is copied (with some edits, to suppress output and return TRUE or an error message) from:
# http://www.hackernotcracker.com/2006-04/wol-wake-on-lan-tutorial-with-bonus-php-script.html
# Wake on LAN - (c) HotKey#spr.at, upgraded by Murzik
# Modified by Allan Barizo http://www.hackernotcracker.com
flush();
function WakeOnLan($addr, $mac,$socket_number) {
$separator = ':';
if (strstr ( $mac, '-' ) ) {
$separator = '-';
}
$addr_byte = explode($separator, $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
// send it to the broadcast address using UDP
// SQL_BROADCAST option isn't help!!
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false) {
// echo "Error creating socket!\n";
// echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
return "Error creating socket!\nError code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_erro
($s));
// return FALSE;
}
else {
// setting a broadcast option to socket:
$opt_ret = socket_set_option($s, 1, 6, TRUE);
if($opt_ret <0) {
// echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
return "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
// return FALSE;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
// echo "Magic Packet sent successfully!";
socket_close($s);
return TRUE;
}
else {
// echo "Magic packet failed!";
return "Magic packet failed!";
// return FALSE;
}
}
}
/* ============================== some predefined texts ====================================== */
$display_sent = 'Magic Packet sent successfully!';
$button_text = 'Wake!';
$button_text2 = 'Wake all selected';
//this is where I added my username part
$username_element = "<P>Username: <input type=\"text\" name=\"username\" />";
$password_element = "<P>Password: <input type=\"password\" name=\"password\" /><input type=\"submit\" name=\"submit\" value = \"Login\" />";
$table_html = "<TABLE border=\"2\">\n";
$logout_html = '';
/* ========================= Test for password protection ==================================== */
$wake_MAC_array = array();
if (!isset ($_POST['logout'])) {
$input_password = $_POST['password'];
$input_username = $_POST['username'];
}
//($my_password === '') is if you want no password
if (($input_password === $my_password) and ($input_username === $my_username)) {
$logged_in = TRUE;
$hidden_login = "<input type=\"hidden\" name=\"password\" value=\"$my_password\"/>";
if ($my_password !== '') {
$logout_html = "\n<P><input type=\"submit\" name=\"logout\" value=\"Log Out\"/>\n";
}
if ( (isset ($_POST['tickbox'])) and (is_array($_POST['tickbox']) ) ) {
$checkbox_array = $_POST['tickbox'];
foreach ($checkbox_array as $mac_address => $tickbox_setting) {
$wake_MAC_array[$mac_address] = $tickbox_setting;
}
}
} else {
$logged_in = FALSE;
$hidden_login = '';
$table_html_user = $username_element;
$table_html = $password_element;
}
/* ================================ LOGGED-IN users only ===================================== */
/* ======================= construct table for listing of devices ============================ */
if ($logged_in == TRUE) {
$table_row = "\n<TR>";
foreach ($config_table_columns as $key => $column_heading) {
$table_row .= '<TD>' . $column_heading . '</TD>';
}
$table_row .= '<TD>Wake Up!</TD>';
$table_row .= '<TD>status</TD>';
$table_html .= $table_row . "</TR>\n";
foreach ($config_network_data_array as $device_key => $device_values) {
$table_row = "\n<TR>";
$mac = $device_values['MAC'];
$device_name = $device_values['name'];
$status_cell = '<TD> </TD>';
foreach ($config_table_columns as $key => $column_heading) {
if (isset ( $device_values[$column_heading])) {
$value = $device_values[$column_heading];
if ($column_heading == 'MAC') {
/* special coding for MAC address column; prepare clickable button */
$this_MAC = $value;
$value = "<input type=\"submit\" name=\"wake_MAC\" value = \"$value\" />";
if (( $_POST['wake_MAC'] === $this_MAC ) or (array_key_exists ($this_MAC,
$wake_MAC_array))) {
$status = WakeOnLan ($device_values['WakeIP'], $this_MAC, $socket_number) ;
if ( $status === TRUE ) {
$status = $display_sent;
}
$status_cell = "<TD>$status</TD>";
}
}
} elseif ($column_heading == 'links') {
/* special coding for links column; prepare clickable links from $config_network_links_array */
$value = '';
if (isset ( $config_network_links_array[$device_name])) {
foreach ($config_network_links_array[$device_name] as $link_title => $link_URL) {
if ( $value !== '') {
$value .= '<BR />';
}
$value .= '' . $link_title . '';
}
}
} else {
$value = '';
}
if ($value === '') {
$value = ' ';
}
$table_row .= '<TD>' . $value . '</TD>';
}
/* now add a checkbox to wake up this device */
$table_row .= '<TD>' . "<input type=\"checkbox\" name=\"tickbox[$this_MAC]\" />" . '</TD>';
/* now add the status message (if applicable) for the attempt to send a packet to this device */
$table_row .= $status_cell;
$table_html .= $table_row . "</TR>\n";
}
$table_html .= "</TABLE>\n";
$table_html .= "<P><input type=\"submit\" name=\"wake all\" value = \"$button_text2\" />\n";
}
/* =========================================================================================== */
/* ======================= Now output the html that we've built ============================== */
echo $html_title;
echo "<FORM name=\"input\" action=\"" .$_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo '<P>';
echo $table_html_user;
echo $table_html;
echo $hidden_login;
echo $logout_html;
echo "</FORM>\n";
?>
</center>
When you are logged in and then submit the form to wake a machine, you are passing the password in a hidden field, but not the username.
As you are not passing the username, $input_username = null and thus the check if (($input_password === $my_password) and ($input_username === $my_username)) becomes if (('pass' === 'pass') and (null === 'user')) which is false and this is why you get logged out.

?url= does not work

I am coding for a site which use admin panel and member panel both panels files are located in two separate folders named master and member. Both have main.php file which are header files from those files i redirect to other files, Both main.php use same function file to redirect url by ?url= .
Now problem is admin main.php redirect to correct url but member main.php returns back without showing errors.
function.php is
<?php
function logout($destinationPath)
{
if(count($_SESSION))
{
foreach($_SESSION AS $key=>$value)
{
session_unset($_SESSION[$key]);
}
session_destroy();
}
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
function validation_check($checkingVariable, $destinationPath)
{
if($checkingVariable == '')
{
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
}
function realStrip($input)
{
return mysql_real_escape_string(stripslashes(trim($input)));
}
function no_of_record($table, $cond)
{
$sql = "SELECT COUNT(*) AS CNT FROM ".$table." WHERE ".$cond;
$qry = mysql_query($sql);
$rec = mysql_fetch_assoc($qry);
$count = $rec['CNT'];
return $count;
}
//drop down
function drop_down($required=null, $text_field, $table_name, $id, $name, $cond, $selected_id=null)
{
$qry = mysql_query("SELECT $id, $name FROM $table_name WHERE $cond ORDER BY $name ASC");
$var = '';
if(mysql_num_rows($qry)>0)
{
$var = '<select id="'.$text_field.'" name="'.$text_field.'" '.$required.'>';
$var .='<option value="">--Choose--</option>';
while($r = mysql_fetch_assoc($qry))
{
$selected = '';
if($selected_id==$r[$id]){
$selected = 'selected="selected"';
}
$var .='<option value="'.$r[$id].'" '.$selected.'>'.$r[$name].'</option>';
}
$var .='</select>';
}
echo $var;
}
function uploadResume($title,$uploaddoc,$txtpropimg)
{
$upload= $uploaddoc;
$filename=$_FILES[$txtpropimg]['name'];
$fileextension=strchr($filename,".");
$photoid=rand();
$newfilename=$title.$photoid.$fileextension;
move_uploaded_file($_FILES[$txtpropimg]['tmp_name'],$upload.$newfilename);
return $newfilename;
}
function fRecord($field, $table, $cond)
{
$fr = mysql_fetch_assoc(mysql_query("SELECT $field FROM $table WHERE $cond"));
return $fr[$field];
}
function get_values_for_keys($mapping, $keys) {
$output_arr = '';
$karr = explode(',',$keys);
foreach($karr as $key) {
$output_arr .= $mapping[$key].', ';
}
$output_arr = rtrim($output_arr, ', ');
return $output_arr;
}
function getBaseURL() {
$isHttps = ((array_key_exists('HTTPS', $_SERVER)
&& $_SERVER['HTTPS']) ||
(array_key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER)
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
);
return 'http' . ($isHttps ? 's' : '') .'://' . $_SERVER['SERVER_NAME'];
}
function request_uri()
{
if ($_SERVER['REQUEST_URI'])
return $_SERVER['REQUEST_URI'];
// IIS with ISAPI_REWRITE
if ($_SERVER['HTTP_X_REWRITE_URL'])
return $_SERVER['HTTP_X_REWRITE_URL'];
$p = $_SERVER['SCRIPT_NAME'];
if ($_SERVER['QUERY_STRING'])
$p .= '?'.$_SERVER['QUERY_STRING'];
return $p;
}
preg_match ('`/'.FOLDER_NAME.'(.*)(.*)$`', request_uri(), $matches);
$tableType = (!empty ($matches[1]) ? ($matches[1]) : '');
$url_array=explode('/',$tableType);
?>
In main.php
<li><a href='?url=epin/used.php'><span>Used e-Pin</span></a></li>
is used to redirect url
http://localhost/abcd.biz/secure/master/main.php?url=epin/used.php is working
and http://localhost/abcd.biz/secure/member/main.php?url=epin/used.php is not working
Both main.php files are using same function file so I can't get the reason please help to get out of it, thanks in advance, try to clarify it also.
I am not using any htaccess file

Storing array in sessions

I am trying to store some data as an array in the session but the function does not seem to be working.it does not throw any error but every time i add data to it, it just overwrites the previous data. I am using yii and here is the action
public function actionStoreProducts($name)
{
$name=trim(strip_tags($name));
if(!empty($name))
{
if(!isset(Yii::app()->session['_products']))
{
Yii::app()->session['_products']=array($name);
echo 'added';
}
else
{
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['products'] = $myProducts;
echo 'added';
}
}
Can anyone suggest me how can i achieve the desired result?
Please correct your code like this .
public function actionStoreProducts($name) {
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
Yii::app()->session['_products'] = array($name);
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['_products'] = $myProducts;
echo print_r(Yii::app()->session['_products']);
echo 'added';
}
}
}
session property read-only
i think the correct aproach is :
function actionStoreProducts($name) {
$session = new CHttpSession; //add this line
$session->open(); //add this line
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
$session->add('_products', array($name)); //replace this line
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
$session->add('_products', $myProducts); //replace this line
echo 'added';
}
}
}
first get an variable into $session['somevalue'] ,then sore in array variable, Use Like IT:-
$session = new CHttpSession;
$session->open();
$myval = $session['somevalue'];
$myval[] = $_POST['level'];
$session['somevalue'] = $myval;

how to test if form is post or get?

how will i do this? i have the code:
public function executeListmatches(sfWebRequest $request)
{
$form_values = $request->getParameter('match_form', array());
if (isset($HTTP_POST_VARS))
{
$gender_id = $form_values['gender_id2'];
$age1 = $form_values['age1'];
$age2 = $form_values['age2'];
$province_id = $form_values['id'];
}
else
{
echo $gender_id = $request->getParameter('gender2');
echo $age1 = $request->getParameter('age1');
echo $age2 = $request->getParameter('age2');
echo $province_id = $request->getParameter('id');
}
$this->pager = $this->setupPager($gender_id,$age1,$age2,$province_id);
return sfView::SUCCESS;
}
but the line if (isset($HTTP_POST_VARS)) is not correct
thank you
You can check the method with sfWebRequest::isMethod($name);.
So use: if ($request->isMethod('POST')).
HTTP_POST_VARS & HTTP_GET_VARS are both deprecated. Your first condition is usisng POST data

Categories