PHP - How Does This Code Work?
I am trying to work out why the answer to a PHP quiz question is what it is.
The code below prints out: b,c,A,B,C, I just can't seem to get my head round how it works, would anyone be able to talk me through it quickly? Code: Code: [Select] <?php class Magic { public $a = "A"; protected $b = array("a" => "A", "b" => "B", "c" => "C"); protected $c = array (1,2,3); public function __get($V) { echo "$V,"; return $this->b[$V]; } public function __set($var, $val) { echo "$var: $val,"; echo $this->$var = $val; } } $m = new Magic(); echo $m->a . "," . $m->b . "," . $m->c . ","; ?> Similar TutorialsThis one requires lots of up front information: I have a page, for this example that I will call page.php. It takes get parameters, and for this example I'll call the parameter "step". So I have a URL like this: page.php?step=1 This page has a form with an action of page.php?step=1. The code on the page validates the posting information. If the information is bad, it returns the user to page.php?step=1; if it is good, it takes the user to page.php?step=2 via header( "location:page.php?step=2" ). So redirection is done by relative path, not full URLs. This all works as expected. Now what I've done is set .htaccess to be HTTPS for this page, via this code: # Turn SSL on for payments RewriteCond %{HTTPS} off RewriteCond %{SCRIPT_FILENAME} \/page\.php [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] This works (initially). However, once you try to post the form, it just redirects back to the step=1 version of the page. I really don't know how or why that would be. I'm not sure how else I can explain this or what other information you may have. But it's frustrating to not get a page working in HTTPS that works in HTTP. Very odd. Any suggestions? (I don't even really know the best location to figure out when/why it's redirecting back to the original page.) I have the following code is a included file on my main page Code: [Select] class usersOnline { var $timeout = 600; var $count = 0; var $error; var $i = 0; function usersOnline () { $this->timestamp = time(); $this->ip = $this->ipCheck(); $this->new_user(); $this->delete_user(); $this->count_users(); $this->browser = $this->useragentbrowser(); $this->os = $this->useragentos(); } // start user function useragentbrowser(){ $agent = getenv('HTTP_USER_AGENT'); $browserArray = array( 'Windows Mobile' => 'IEMobile', 'Android Mobile' => 'Android', 'iPhone Mobile' => 'iPhone', 'Firefox' => 'Firefox', 'Google Chrome' => 'Chrome', 'Internet Explorer' => 'MSIE', 'Opera' => 'Opera', 'Safari' => 'Safari' ); foreach ($browserArray as $k => $v) { if (preg_match("/$v/", $agent)) { break; } else { $k = "Browser Unknown"; } } $browser = $k; return $browser; } function useragentos(){ $agent = getenv('HTTP_USER_AGENT'); $osArray = array( 'Windows 98' => '(Win98)|(Windows 98)', 'Windows 2000' => '(Windows 2000)|(Windows NT 5.0)', 'Windows ME' => 'Windows ME', 'Windows XP' => '(Windows XP)|(Windows NT 5.1)', 'Windows Vista' => 'Windows NT 6.0', 'Windows 7' => '(Windows NT 6.1)|(Windows NT 7.0)', 'Windows NT 4.0' => '(WinNT)|(Windows NT 4.0)|(WinNT4.0)|(Windows NT)', 'Linux' => '(X11)|(Linux)', 'Mac OS' => '(Mac_PowerPC)|(Macintosh)|(Mac OS)' ); foreach ($osArray as $k => $v) { if (preg_match("/$v/", $agent)) { break; } else { $k = "Unknown OS"; } } $os = $k; return $os; } // end user function ipCheck() { if (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); } elseif (getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_X_FORWARDED')) { $ip = getenv('HTTP_X_FORWARDED'); } elseif (getenv('HTTP_FORWARDED_FOR')) { $ip = getenv('HTTP_FORWARDED_FOR'); } elseif (getenv('HTTP_FORWARDED')) { $ip = getenv('HTTP_FORWARDED'); } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } function new_user() { $insert = mysql_query ("INSERT INTO ******(timestamp, ip, browser, os) VALUES ('$this->timestamp', '$this->ip', '$this->browser', '$this->os')"); if (!$insert) { $this->error[$this->i] = "Unable to record new visitor\r\n"; $this->i ++; } } function delete_user() { $delete = mysql_query ("DELETE FROM ***** WHERE timestamp < ($this->timestamp - $this->timeout)"); if (!$delete) { $this->error[$this->i] = "Unable to delete visitors"; $this->i ++; } } function count_users() { if (count($this->error) == 0) { $count = mysql_num_rows ( mysql_query("SELECT DISTINCT ip FROM *******")); return $count; } } } The problem I have is that $browser and $os are not being inserted into the db, but everything else is. Can anyone help? Thanks James Hi, I'm creating a chat-box application and I'm trying to add IP bans, where the php code checks if the user is banned or not and then insert the chat, but even if the IP address is banned it will still insert the chat. Code: [Select] $ipsql = mysql_query("SELECT * FROM bans WHERE ip='$user_ip'" or die (mysql_error())); $bancheck = mysql_num_rows($ipsql); if($bancheck <= 0){ $sql = mysql_query("INSERT INTO chats (user_ip, user_name, chat_body, date_time) VALUES('$user_ip','$user_name','$chat_body',now())") or die (mysql_error()); } Thanks, Soccerjunki I have this code that changes an image on the hour, of a random hour and stays changed for 2 minutes, regardless of refreshes etc etc, and it has to be the exact same hour and 2 minutes for everyone. I know at the minute it is going to change at 4pm, it is only for testing purposes, I am doind the random time bit later. <?php $minute = date(i); $hour = 16; if ($hour == date(H) && $minute < 3) $buttonimage = "buttonon.png"; else $buttonimage = "buttonoff.png"; ?> <table width="200" border="1"> <tr> <td><img src="<?php echo($buttonimage); ?>" /></td> </tr> </table> Code: [Select] <?php require "global.php"; if ($_POST) { $name = $_POST['name']; $data = sprintf("INSERT INTO forums VALUES (DEFAULT,'$name')"); mysql_query($data); $fid = mysql_insert_id(); header( 'Location: viewforum.php?fid='.$fid); exit; } echo ' <form action="" method="POST"> <table> <tr><td>Forum Name: </td><td><input name="name" /></td></tr> </table> <input type="submit" value=" Add Forum " /> </form>'; ?> This added forums whenever I made one to my MySQL database in the table "forums" For whatever reason, whenever I make a forum, it makes it end in ".php?fid=0" and does not create the forum on the database. Any ideas? Thanks! Hi everybody! I'm creating a site and none of my php-code works. I tried to do a simple php-code to test it but it doesn't work either. The simple php-code: <?php echo "hello"; ?> Hi, guys. I'm have a website setup on my localhost. It's not yet LIVE. However, i'm setting up a cron job to work with the code below. Will this code work fine? $sql = "SELECT * FROM users WHERE subscription <> 0"; $result = mysql_query($sql); if(mysql_num_rows($result)) { while($row = mysql_fetch_assoc($result)){ $subscription = $row['subscription'] - 1; $sql = "UPDATE users SET subscription = '$subscription' WHERE subscription <> 0"; $result=mysql_query($sql) or die(mysql_error()); } } $query = "SELECT * FROM users WHERE subscription = 0"; $update = mysql_query($query); if(mysql_num_rows($update)) { while($row1 = mysql_fetch_assoc($update)){ $subscription = 0; $query = "UPDATE users SET disable = 1 WHERE subscription = '$subscription'"; $update=mysql_query($query) or die(mysql_error()); } } Also, how will i have to write the cron job to meet the needs of this script and update it at 12am every day? Hello I am getting the following error when accessing this page... test.php Code: [Select] <?php $url = "http://www.howtogeek.com"; $str = file_get_contents($url); function get_url_contents($url){ $crl = curl_init(); $timeout = 5; curl_setopt ($crl, CURLOPT_URL,$url); curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); $ret = curl_exec($crl); curl_close($crl); return $ret; } ?> Easy right??? I am getting the following error. Code: [Select] Parse error: syntax error, unexpected ':' in /home/username/public_html/tools/crawler/test.php on line 2 The above example code was taken from How To Geek. http://www.howtogeek.com/howto/programming/php-get-the-contents-of-a-web-page-rss-feed-or-xml-file-into-a-string-variable/ I have tried single quotes, removed the http:// part, a few other small things but I just don't understand. Can anyone shed some light on it? Thanks! Guys i wrote one pinging script but i don't know it works or not... Someone help me about it works or not? <?php site1("http://site.com/sitemap.xml"); site2("http://site2.com/sitemap.xml"); function site1($url){ @file_get_contents("http://www.google.com/webmasters/tools/ping?sitemap=" . $url); @file_get_contents("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=YahooDemo&url=" . $url); @file_get_contents("http://www.bing.com/webmaster/ping.aspx?siteMap=" . $url); @file_get_contents("http://submissions.ask.com/ping?sitemap=" . $url); } Print "Pinging1 success"; function site2($url){ @file_get_contents("http://www.google.com/webmasters/tools/ping?sitemap=" . $url); @file_get_contents("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=YahooDemo&url=" . $url); @file_get_contents("http://www.bing.com/webmaster/ping.aspx?siteMap=" . $url); @file_get_contents("http://submissions.ask.com/ping?sitemap=" . $url); } Print "<br>Pinging2 success"; ?> Hello; I'm new to php and to programming in general, but i want to do a little app to help a process on my work, you know, just being pro-active (hoping it doesnt come and byte me in the a** in the future, you know.. "you did it now our life depend on it and you fix it right now!!). So.. I have this really simple piece of code, but its not working and i cant figure out why. I'm trying to use echo to print a couple of link but when i put in the second line everything messes up. the code is: (note the "test lines" i just added them to try to understand what is doing) <?php $client = $_GET['client']; echo "Client " . $client . "<br />"; echo "test line 1"; echo "<a href=\"link1.php?client=".$client.">Link 1</a><br>"; echo "test line 2"; echo "test line 3"; echo "<a href=\"link2.php?client=".$client.">Link 2</a><br>"; ?> When i open the page on firefox i get: === Client myclient test line 1Link 2 === Where the link (underlined) text is "Link 2" but the it points to something totally different (a mix of the rest of the code). If I remove the second link, like he <?php $client = $_GET['client']; echo "Client " . $client . "<br />"; echo "test line 1"; echo "<a href=\"link1.php?client=".$client.">Link 1</a><br>"; echo "test line 2"; echo "test line 3"; ?> I get what i'd expect: === Client myclient test line 1Link 1 test line 2test line 3 === Im totally lost, im not sure if its a browser issue, a server issue or just the code My setup: WAMP 2.1 (Apache) I'm opening the "site" with Firefox 3.6.15 and IE6, both show the same result Windows XP (dont know if it matters) The file is saved as php tried changing "echo" with "print", same result Umm.. thats it... Please let me know if you need any more info Thanks everyone edit: typo on subject edit: yet another typo Hi, I am having difficulties with the login section on a website. I have tried to update the old funtion names which have been deprecated, but when I do this the login will not work. This is the log.php file, (this is required by index.php on the restricted directory to access the page). Code: [Select] <?php session_start(); ?> <?php $hostname = ".."; $username = ".."; $password = ".."; $database = ".."; $link = MYSQL_CONNECT($hostname,$username,$password); mysql_select_db($database); ?> <?php if($_GET['action'] == "login") { $conn = mysql_connect("..","..","..); $db = mysql_select_db(".."); //Your database name goes in this field. $name = $_POST['user']; $ip=$_SERVER['REMOTE_ADDR']; $var = mysql_real_escape_string($var); $country = file_get_contents('http://stonito.com/script/geoip/?ip='.$ip); $q_user = mysql_query("SELECT * FROM customer WHERE username='$name'"); ?> <?php $insert_query = ("INSERT INTO login(username, ip, country) VALUES ('$name','$ip','$country');"); mysql_query($insert_query) or die('Error, insert query failed'); ?> <?php if(mysql_num_rows($q_user) == 1) { $query = mysql_query("SELECT * FROM customer WHERE username='$name'"); $data = mysql_fetch_array($query); if($_POST['pwd'] == $data['password']) { session_register("name"); header("Location: ../index.php?un=$name"); // This is the page that you want to open if the user successfully logs in to your website. exit; } else { header("Location: .."); exit; } } else { header("Location: .."); exit; } } // if the session is not registered if(session_is_registered("name") == false) { header("Location: login.php"); } ?> The two old code parts. causing the problems are session_register("name"); session_is_registered . When I change update elements in the code block shown below, it will not work. Can anyone tell me why please? Code: [Select] <?php if(mysql_num_rows($q_user) == 1) { $query = mysql_query("SELECT * FROM customer WHERE username='$name'"); $data = mysql_fetch_array($query); if($_POST['pwd'] == $data['password']) { $_SESSION['name']; header("Location: ../download/index.php?un=$name"); // This is the page that you want to open if the user successfully logs in to your website. exit; } else { header("Location: .."); exit; } } else { header("Location: .."); exit; } } if(!isset($_SESSION['name'])) { header("Location: http://www.myurl.com"); } Any help would be very gratefully received. I have this little code that I cannot get to work Code: [Select] $sql_buildings = ("SELECT castle, treasury, huts, [b]leader_id[/b] FROM teams WHERE team_id=[b]".$_GET['t']." [/b]"); $rsbuildings = mysql_query($sql_buildings); if($rsbuildings[".$_GET['t']."] == 'leader_id' ){ The problem is this part: Code: [Select] if($rsbuildings[[b]".$_GET['t']."[/b]] == '[b]leader_id[/b]' ){ How can I write it to have these to values work? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=356031.0 The first piece of code, "screenshot_1", works perfectly but of course is open to SQL injection. If I use prepared statements as per "screenshot_2", and change $result from $con->query($query) to $result= $query->execute()it doesn't work and gives the error, "Fatal error: Uncaught Error: Call to a member function fetch() on bool ". I have read somewhere that this is caused because the 'Select' statement has failed.I am amazed that three lines of code (copied from a php manual) has caused the whole issue to fail. Where have I gone wrong? ,
So I am trying to create a table where users can be disabled and enabled with the press of a radio button. So for the most part it works but for some reason it only allows me to disable a user it wont let me enable them and I can't seem to figure out why. I've checked that all the names were correct with the database and I have also tried both single ' quotes and double " quotes on the prepared statements to see if that makes a difference... it did not These are the functions to disable and enable users function inactive($userId){ $conn = db_connect(); $disable_user = pg_prepare($conn, 'disable', "UPDATE users SET Enabled = false, Status = 'd' WHERE Id = $userId"); $result = pg_execute($conn, 'disable', array()); } //Create a function to activate a salesperson function active($userId){ $conn = db_connect(); $enable_user = pg_prepare($conn, 'enable', "UPDATE users SET Enabled = true, Status = 'a' WHERE Id = $userId"); $result = pg_execute($conn, 'enable', array()); } $id = (array_keys($_POST['active'])[0]); $status = $_POST['active'][$id]; if($status == "t"){ active($id); } else{ inactive($id); } And this is where it gets put into action ^^
In the database I have a boolean for enabled which is either true or false and then I have a varchar for status which is either 'd' or 'a'
Any help would be greatly appreciated
Thanks in advance Somebody please tell me why this wont work. Didnt wont to put my email in their. <?php $user = $_POST['subject']; $email = $_POST['email']; $message = $_POST['message']; //To, Subject, Message mailto(''); mailsubject('$user Sent you a message'); mailfrom('From: ' . $user . ' <' . $email . '>'); ?> In a nutshell here is what I am wishing to do. The user clicks on a link. The link has an ID# embedded in it. For this example, we will assume that the Link ID (lid) = 4-1-1 Now I have 2 tables: Table 1 Columns: ID | contact_fname | contact_lname 10 Bl4ck Maj1k Table 2 Columns: ID | contact_id | link_id 1 10 4-1-1 I need to display the contact's First and Last name if he is associated with the current link. The way I thought to track that was via table joins. I have attempted a code but it doesnt work. I basically want to make it so whenever Table 1 has a person with an ID equal to the Contact ID of table 2 AND whenever the Link ID in our URL (which I am capturing via a $_GET function and storing in a variable) is equal to the Link ID in our table with the associated contact in it, I want to then display the First Name and Last Name. Below is my failed attempt at this. Weird thing is, I have done this several times before. I don't see myself doing anything different but I must be because it simply doesn't work. Any help would be greatly appreciated... Code: [Select] <?php $link_id = $_GET['lid']; $query = "SELECT table1.id, table1.contact_fname, table1.contact_lname, table2.contact_id, table2.link_id FROM table1, table2 WHERE table1.id = table2.contact_id AND table2.link_id = $link_id"; $sql = mysql_query($query); while($row = mysql_fetch_array($sql)) { $contact_fname = $row['contact_fname ']; $contact_lname = $row['contact_lname ']; echo '' . $contact_fname . ' ' . $contact_lname . '' ; } ?> Please let me know what I am doing wrong here! Thanks boys and girls :-) Bl4ck Maj1k This topic has been moved to Other Web Server Software. http://www.phpfreaks.com/forums/index.php?topic=331514.0 mysql_connect('', '', ''); mysql_select_db(''); if (isset($_POST['submit'])) { $user = mysql_real_escape_string($_POST['user']); $pass = mysql_real_escape_string($_POST['pass']); $sql = "SELECT id FROM login WHERE username = '$user' && `password` = MD5('$pass')"; if ($result = mysql_query($sql)) { if (mysql_num_rows($result)) { // $user & $pass are valid echo "You Logged In $user"; } else { // $user || $pass invalid echo "Invalid Login"; } } } |