PHP - Making The Value Of A Variable Not Relevant To The Rest Of The Php Code?
So what i mean is if i set a variable to "[" ($some_variable = "[") the rest of my code is now going to go CRAZY because there is an open [. Is there a way I can just make everything inside the first set of "" not relevant to the code? thanks!
Similar TutorialsGood evening, Im using GenRandomString, and wondered how I can get $confirm to keep its first value throughout my script. I have put comments on the lines that use $confirm. Do I need to change $confirm to a constant and how can I go about this? $firstname = $_GET['firstname']; $lastname = $_GET['lastname']; $companyname = $_GET['companyname']; $doornumber = $_GET ['doornumber']; $street = $_GET ['street']; $town = $_GET['town']; $postcode = $_GET['postcode']; $useremail = $_GET ['usermail']; $telephone = $_GET['telephone']; $shortcode = substr($postcode,0,2); function genRandomString() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))];} return $string;} $confirm = genRandomString(); //creating a random number $query =mysql_query ("INSERT INTO treesurgeons (firstname, lastname, companyname, doornumber, street, town, postcode, useremail, telephone, Id) VALUES ('$firstname', '$lastname', '$companyname','$doornumber', '$street', '$town', '$postcode', '$useremail', '$telephone', '$confirm')");//1st Value echo mysql_error(); echo "<p>Thankyou for submiting your details.\r\n Please check your inbox and click on your confirmation link.</p>"; $message = "The following details have been submited to the tree directory and are awaiting confirmation; \r\n Please click on the link below to confirm these details are correct\r\n '$firstname', '$lastname', '$companyname','$doornumber', '$street', '$town', '$postcode', '$usermail', '$telephone' <a href='http://www.mywebsite.co.uk/confirmed.php?Id=$confirm'>"; //2nd Value $subject = "Your tree directory details"; $to = "$useremail"; $email = "$emailad"; mail( "$to", "$subject","$message", "$headers"); ?></body></html> I havent really played around with constants before, so please an advice appreciated! Im guessing im using DEFINE but im unsure how I would combine this with GenRandomString in my code. $link = ?><a href="post?id=<?php echo $id; ?>&title=<?php echo $slug_title; ?>"><?php echo $title; ?></a><?phpBasically what I am trying to do is get a url link of a current page that I'll be sending in an email. I have all the $_GET variables I need to duplicate the current url. For some reason it's giving me an error. Can you please fix what is shown above into something that'll work? Thanks. Edited by man5, 15 July 2014 - 07:09 PM. I run these functions to find the key of a given element inside an array. Like so; $ban_ip_file = file("ip_file.txt"); foreach($ban_ip_file as $key => $value) { $value = trim($value); if($value == $ip_from_form)// passed to page by a form $set = $key; } How do I make $set available for testing and file writing further down the script? Tried assigning global $set; just above the $set=$key; ----but it did not work. Hi, I want to be able to generate visitor statistics for a blog I'm creating. I'm going to be collecting numerous pieces of data when a post is viewed, including a time stamp of the visit. I need to be able to select timestamps that were within the current day, the previous day, the day before that ect.. So that I can generate the statistics. Show it for the current week (current day and 6 previous days). So it would be the entries where the timestamp was made on the days: 11/1, 10/1, 9/1, 8/1, 7/1, 6/1, 5/1. For example. Not quite sure how I could do this. Thanks. I have an array ( $exifdata ) which contains the relevant bits that I require, read from exif data, as in the var_dump below. array 0 => string 'Caption' (length=7) 1 => string 'Copy' (length=4) 2 => string 'Camera' (length=6) 3 => string 'Shutter' (length=7) 4 => string 'fNo' (length=3) 5 => string 'ISO' (length=3) 6 => string 'Date' (length=4) 7 => string 'Time' (length=4) 'copy' => string 'Alf Thomas' (length=10) 'caption' => string 'Blue Sky over Auld Reekie' (length=25) 'camera' => string 'Canon PowerShot G9' (length=18) 'shutter' => string '1/800' (length=5) 'fNo' => string 'f/5.6' (length=5) 'iso' => int 200 'date' => string '07:10:2011' (length=10) 'time' => string '09:05:26' (length=8 What I am trying to do is echo each key followed by its relevant data, and thought something like this would work:- Code: [Select] foreach( $exifdata as $key => $value){ echo "$key :, $value <br />"; } The output I get from the above is as below:- 0 :, Caption 1 :, Copy 2 :, Camera 3 :, Shutter 4 :, fNo 5 :, ISO 6 :, Date 7 :, Time copy :, Foucquet caption :, Blue Sky over Auld Reekie camera :, Canon PowerShot G9 shutter :, 1/800 fNo :, f/5.6 iso :, 200 date :, 07:10:2011 time :, 09:05:26 Which more or less does what I want except that what I actually would like is this:- Copy - Foucquet Caption - Blue Sky over Auld Reekie Camera - Canon PowerShot G9 Shutter - 1/800 fNo - f/5.6 ISO - 200 Date - 07:10:2011 Time - 09:05:26 What I can't quite understand is why I am getting the two lists as an output, which simply seems to be identical to the output of the var_dump. Okay, really newbie question, but for this code... Code: [Select] <!-- Gender --> <label for="gender">Gender:</label> <select id="gender" name="gender"> <option value="">--</option> <option value="F">Female</option> <option value="M">Male</option> </select> 1.) How do I assign a variable to this? 2.) How do I make this "sticky"? Here is how I have usually done other form types... Code: [Select] <!-- First Name --> <label for="firstName">First Name:</label> <input id="firstName" name="firstName" type="text" maxlength="30" value="<?php if(isset($firstName)){echo htmlentities($firstName, ENT_QUOTES);} ?>" /><!-- Sticky Field --> <?php if (!empty($errors['firstName'])){ echo '<span class="error">' . $errors['firstName'] . '</span>'; } ?> Oh, by the way, at the top of my PHP file I have this code... Code: [Select] if ($_SERVER['REQUEST_METHOD']=='POST'){ // Form was Submitted (Post). // Initialize Errors Array. $errors = array(); // Trim all form data. $trimmed = array_map('trim', $_POST); Thanks, Debbie Hi all, i have no idea where to start with this.. I do however have some code i am assured will pull the data.. What i need to know is can and will you help me.. I understand if not.. Just rather ask before i jump in. Jamie I have such lines of code: $link["beF1LP"]="https://www.site.com"; $link["beN1LP"]="https://www.site.com"; I know I can simplify it like this: $link["beF1LP"]=$link["beN1LP"]="https://www.site.com"; But I wanted something like this: $link["be(F|N)1LP"]="https://www.site.com"; Which did not work. How do I get it working for the string inside the brackets and under the quotes while using OR and/or other operators?
Thank you Can anyone help me make this more secure? I want to link the info to .inc instead of pulling this info straite from the page // cPanel info $cpuser = 'userhere'; // cPanel username $cppass = 'passwordhere'; // cPanel password $cpdomain = 'mysite.com'; // cPanel domain or IP $cpskin = 'x'; // cPanel skin. Mostly x or x2. // See following URL to know how to determine your cPanel skin // http://www.zubrag.com/articles/determine-cpanel-skin.php // Default email info for new email accounts // These will only be used if not passed via URL $epass = 'hispassword'; // email password $edomain = 'mysite.com'; // email domain (usually same as cPanel domain above) $equota = 20; // amount of space in megabytes The only time it pulls the info is in this line // Create email account $f = fopen ("http://$cpuser:$cppass@$cpdomain:2082/frontend/$cpskin/mail/doaddpop.html?email=$euser&domain=$edomain&password=$epass"a=$equota", "r"); if (!$f) { $msg = 'Cannot create email account. Possible reasons: "fopen" function allowed on your server, PHP is running in SAFE mode'; break; } $msg = "<h2>Email account {$euser}@{$edomain} created.</h2>"; Thank you for the h elp once again $info[130] is the random code, but how do i go about making sure the code is not used on any other row.... (even thou it would be unlikely even with this code, it is still possible) Code: [Select] <?php # IF THE USER DOES NOT HAVE A UNIQUE CODE, CREATE ONE if ($info[130] == "0") { function randomPassword() { $salt = "abchefghjkmnpqrstuvwxyz0123456789"; srand((double)microtime()*1000000); $i = 0; while ($i <= 14) { $num = rand() % 33; $tmp = substr($salt, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } $info[130] = randomPassword(); } ?> This question includes MySQL, but I have a feeling the answer will involve PHP so putting it here for now. If it should be moved, feel free Say I have a for loop that iterates through a certain amount of times and updates a value in my database EACH ITERATION thru the loop. In other words, we're connecting to the database multiple times. Seems very inefficient, so I'd like to see if there is a better way. Here is a basic example of the "bad" way (FYI, this code is basically reordering items after one of them moves down in the list)... Code: [Select] for ($a=$oldvalue+1; $a<=$othervalue; $a++) { $sql = "UPDATE tablewithids SET id=id - 1 WHERE id=$a"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { } So if $othervalue happened to be 80, then it would be 80 separate connections to the database! I imagine it would make a lot more sense to gather the data first (into an array I presume) and then make one connection to the database an update that way, but I'm having trouble wrapping my head around how to do it based on this type of example. Can anyone offer suggestions to help make this type of for loop code more efficient? I have a option in my profile settings for users to beable to "hide" there friends list this si my code to show there friends on there profile Code: [Select] $this->to_print .= <<< LOL <fieldset><legend>$Friends</legend> <div class="padding4"> $Friends2 LOL; while( $r = $DB->fetch_row() ){ if ( $r['last_activity'] > (time() - 900) ) $r['status'] = "<span style=float:right;><span class=desc4><b>Online</b></span></span>"; else $r['status'] = "<span style=float:right;><span class=desc4>Offline</span></span>"; $column++; if ($ibforums->member['settings']['2'] or (!$ibforums->member['id'])){ $color = "{$r['color']}"; $colors = explode(",", $color); if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ){ { $r['color'] = ($r['color']) ? "style=\"padding:1px 1px 1px 2px;color:#{$colors[0]};filter:Glow(color=#{$colors[1]},strength=3)\"":""; } }else{ $r['color'] = ($r['color']) ? "style=\"color:#{$colors[0]};text-shadow:#{$colors[1]} 2px 1px 1px\"":""; } } $test = explode(";", $info['pdata']); $r['avatar'] = ($r['avatar']) ? "<img src={$r['avatar']} width=64 height=64>" : ""; $r['star'] = ($r['star']) ? "<img class=top3 src=style_images/1/icons/{$r['star']}.png>":""; $r['name'] = "<a href=?i={$r['friendid']}>{$r['name']}{$r['star']}</a>"; $this->to_print .= <<< LOL <dl class="LOL LEFT flm" style="margin-right:5px"><dt2>{$r['name']}</dt2><dd class=padding4>{$r['avatar']}<div class="RIGHT">{$r['status']}</div></dd></dl> LOL; } $this->to_print .= <<< LOL </div> </fieldset> now I will be using this code to make it hidden based on a variable (they set in there settings) Code: [Select] //Hide Friends if ($display[0] == "1"){ $friend = ""; }else{ $friend = 'show that function here above code'; } how can I pull all that info into my $friend variable to make it easy? See then I could just echo out $friend and it will show that code above, or not (if they hidden it in settings)? Help ty Hey Everyone, I writing on here because I am taking a course on PHP and learning it by using the textbook PHP 6 Fast & Easy Web Development by Julie Meloni and came across a problem on an assignment that I dont know how to fix. Any who, in the assignment I was working on I wrote a script that shows data I have in a table in my broswer (which btw works) BUT it always gives me the following message: Notice: Undefined variable: display_block in 127.0.0.1\sel_byid.php on line 29. I have checked my code over and and am sure I copied it right but still get the notice. Here's the code: Code: [Select] <?php $db_name = "testDB"; $table_name = "my_music"; $connection = @mysql_connect("localhost", "brenda", "mouse") or die(mysql_error()); $db = @mysql_select_db($db_name, $connection) or die(mysql_error()); $sql = "SELECT * FROM $table_name ORDER BY title"; $result = @mysql_query($sql, $connection) or die(mysql_error()); while($row = mysql_fetch_array($result)) { $id = $row['id']; $format = $row['format']; $title = stripslashes($row['title']); $artist_fn = stripslashes($row['artist_fn']); $artist_ln = stripslashes($row['artist_ln']); $rec_label = stripslashes($row['rec_label']); $my_notes = stripslashes($row['my_notes']); $date_acq = $row['date_acq']; if($artist_fn != "") { $artist_fullname = trim("$artist_fn $artist_ln"); }else{ $artist_fullname = trim("$artist_ln"); } if($date_acq == "0000-00-00") { $date_acq = "[unknown]"; } $display_block .= "<P><strong>$id. $title</strong>on $rec_label, by $artist_fullname<br>$my_notes<em>(acquired: $date_acq, format: $format)</em></P>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>My Music (Ordered by Title)</title> </head> <body> <H1>My Music: Ordered by Title</H1> <?php echo "$display_block"; ?> <P><a href="my_menu.html">Return to Menu</a></P> </body> </html> I've been trying to fix it for like a week now and the only thing I understand from the notice is that this line: Code: [Select] $display_block .= "<P><strong>$id. $title</strong>on $rec_label, by $artist_fullname<br>$my_notes<em>(acquired: $date_acq, format: $format)</em></P>"; is trying to concatentate to a variable which does not exist ($display_block) and I dont know how to fix it... Can anyone help me? Hey guys im making a PHP page using PHP So i have this ##################################################### # Make the PHP page # ##################################################### $PHPCode = " <?php //Title of page used to select the correct record from the database $Title = '".$Name."'; //Use the database information stored in this file include ($_SERVER['DOCUMENT_ROOT'].'/MySQL/Lighthouses-Database-Connection-Information.php'); //Take the information from the database using the method in this file include ($_SERVER['DOCUMENT_ROOT'].'/MySQL/Retrieve-Information.php'); //Process the information using the methods in this file include ($_SERVER['DOCUMENT_ROOT'].'/MySQL/Processing.php'); //Use the layout HTML held in this file include ($_SERVER['DOCUMENT_ROOT'].'/MySQL/PageCode-Lighthouse-Information-Page.php'); //Display the page code made. Resulting in the page displayed. echo $pagecode; ?> "; However, i keep getting syntax errors, possibly due to the fullstops. How shall i get round this?! Danny Hi guys. I'm new to php and struggleing with the REST POST for some reason.... I need to insert a contact into this accouting system http://help.saasu.com/api/#toc-http-post search for Example: Insert Contact. the data strcutre looks like: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <tasks> <insertContact> <contact uid="0"> <salutation>Mr.</salutation> <givenName>John</givenName> <familyName>Smith</familyName> <organisationName>Saasy.tv</organisationName> <organisationAbn>777888999</organisationAbn> <organisationPosition>Director</organisationPosition> <email>john.smith@saasy.tv</email> <mainPhone> 02 9999 9999 </mainPhone> <mobilePhone> 0444 444 444 </mobilePhone> <contactID>XYZ123</contactID> <tags>Gold Prospect, Film</tags> <postalAddress> <street>3/33 Victory Av</street> <city>North Sydney</city> <state>NSW</state> <postCode>2000</postCode> <country>Australia</country> </postalAddress> <otherAddress> <street>111 Elizabeth street</street> <city>Sydney</city> <state>NSW</state> <postCode>2000</postCode> <country>Australia</country> </otherAddress> <isActive>true</isActive> <acceptDirectDeposit>false</acceptDirectDeposit> <directDepositAccountName>John Smith</directDepositAccountName> <directDepositBsb>000000</directDepositBsb> <directDepositAccountNumber>12345678</directDepositAccountNumber> <acceptCheque>false</acceptCheque> <customField1>This is custom field 1</customField1> <customField2>This is custom field 2</customField2> <twitterID>Contact twitter id</twitterID> <skypeID>Contact skype id</skypeID> </contact> </insertContact> </tasks> I only have to insert 3 mandatory fields whcih are in the below code snipit im using but nothings working... Code: [Select] //set POST variables $service_url = 'https://secure.saasu.com/webservices/rest/r1/tasks?wsaccesskey=<key removed>'; $curl = curl_init($service_url); $fileds = array( 'insertContact' => array( 'contact' => array( 'givenName' => urlencode('John'), 'familyName' => urlencode('Smith'), 'organisationName' => urlencode('Saasy.tv') ) ) ); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); $curl_response = curl_exec($curl); curl_close($curl); $xml = new SimpleXMLElement($curl_response); Please help, I'm not sure what I'm doing wrong.... Here is the scenario. I created a niche market API which provides environmental data. The data is obtained by industrial controllers which don't monitor anything by default, and the API has additional endpoints which are used to instruct the industrial controllers to start monitoring some parameter so the API can then start storing the trend data. The API primarily responds with JSON, however, a couple of endpoints support CSV data. For humans/webclients to access the data, I also created a webserver application which can be added to a Concrete5 (C5) CMS. I tried to make as many of its endpoints do nothing except receive the webclient's request, add a JSON Web Token to it which contains a unique identifier, forward it to the API using cURL, and return the response as is to the webclient. To limit the scope which needed to be created for the C5 application, the API has endpoints to return JSON which is used by JavaScript on the webclient for client-side validation, endpoints (actually, a different domain) to return static JavaScript/CSS/etc, and endpoints to restructure the JSON data to some more suitable format. I now am looking at creating different applications which does not use C5, but either are 100% custom or use some other CMS such as Drupal, etc. While I tried to limit the scope implemented on the C5 application, I have much more than I desire and will need to duplicate much for any future application. The primary scope I would like to remove from the webserver application relates to the HTML views and consists of templates which create HTML from JSON, the JavaScript which interacts with the HTML, and to a lesser degree controllers to determine the type of view (i.e. a list of records or one specific detail record). While the API will only be managed by myself, the intent is that the C5, 100% custom, etc webserver apps are installed and managed by others. Ideally, there is some existing Composer package for transforming JSON to HTML which is CMS agnostic, however, I don't know whether such exists. Also, while not 100% necessary, ideally this functionality could exist on my server and not the individual web application's server. Whether I build it myself or use some existing package, I expect it will need to do something like the following: The various webserver apps will have some routing table to proxy the request either to my JSON API server (complete) or my new "HTML API Server" (remaining discusses this portion). This HTML API server would generate the content either by making a cURL request to the main JSON API, or better yet since likely located on the same server have routing functional to make direct calls to the JSON API's methods, and return something like the following: { "html": "<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pharetra massa massa ultricies mi quis hendrerit dolor. Leo integer malesuada nunc vel risus commodo viverra.</div>", "javascript_files": [ "https://resources.myserver.com/someFile.js", "https://resources.myserver.com/someOtherFile.js" ], "css_files": [ "https://resources.myserver.com/someFile.css", "https://resources.myserver.com/someOtherFile.css" ] } The various applications would then take the HTML and resource files and insert them using their proprietary methods. EDIT. Also, thinking of using an IFRAME, however, definitely have concerns with doing so. My day job has nothing to do with software, however, am hoping to make it so. Before embarking on this task, I would like to know whether some existing framework exists and if not what general strategy (organization, caching, etc) I should take to develop it. Thanks Edited January 18 by NotionCommotionAdded IFRAME idea I want to create a REST API for my website. What I want to do is to display advertisements from my database on websites that I sell to clients. Their website will call my database for advertisements to display on their websites. Also, I am performing a site validity check where the client's site would send the site URL, site name, and site token to my database for validation. If it returns false then the site will not display as it will be invalid according to my database. I've been Googling this topic all day, but cannot seem to get my head around it. I want to set an API key on my website so that not just anybody can be querying my database. For the advertisement query, no parameters need to be sent from the client websites to my database. Can anyone offer some advice on how to do this? <?php $myData = file_get_contents(""); $myObject = json_decode($myData); $myObjectMap = $myObject->result; ?> can i somehow build in that it only request every 5 minutes because if there are many users on the site it request too much? <?php $pageTitle='Edit Profile'; require_once ("header.php"); ?> How can I pass a variable like that through header.php? I know it doesn't work the way I have it. |