Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

eHacked posted:

How do I extract information from XML?

Say I have this:

code:
<?xml version="1.0"?>
<previewroot>
<category>
  <item Id="6691" websiteid="0" category="2" contentgroup="1"/>
  <item Id="6690" websiteid="0" category="3" contentgroup="1"/>
  <item Id="6689" websiteid="0" category="4" contentgroup="1"/>
</category>
<sites>
  <item Id="117" websiteid="0" siteid="8" contentgroup="1"/>
</sites>
<content>
  <names>
    <name name="jpg" num="520" filesize="87222276"/>
    <name name="thumb" num="525"/>
    <name name="full" num="1" filesize="383874155"/>
    <name name="hdwmv" num="5" filesize="573953501" movie_length="2100.707"/>
    <name name="hswmv" num="5" filesize="381170297" movie_length="2100.815"/>
    <name name="lswmv" num="5" filesize="158266517" movie_length="2100.695"/>
    <name name="mpg" num="5" filesize="305189364" movie_length="2106.967912"/>
  </names>
</content>
</previewroot>
I want whatever the first movie_length is set to:

movie_length="2100.707"

I can do a stupid PHP function to remove everything but that info ... but I know it's got to be easier than that!

Read up on this: http://us.php.net/simplexml

[EDIT] Whipped up some sample code because it's so drat easy.... this uses the XPATH function that was added to simpleXML in PHP5.2, you'll have to do it the slightly more complicated way if you are using a previous version...

php:
<?
$string = <<<XML
<?xml version="1.0"?>
<previewroot>
<category>
  <item Id="6691" websiteid="0" category="2" contentgroup="1"/>
  <item Id="6690" websiteid="0" category="3" contentgroup="1"/>
  <item Id="6689" websiteid="0" category="4" contentgroup="1"/>
</category>
<sites>
  <item Id="117" websiteid="0" siteid="8" contentgroup="1"/>
</sites>
<content>
  <names>
    <name name="jpg" num="520" filesize="87222276"/>
    <name name="thumb" num="525"/>
    <name name="full" num="1" filesize="383874155"/>
    <name name="hdwmv" num="5" filesize="573953501" movie_length="2100.707"/>
    <name name="hswmv" num="5" filesize="381170297" movie_length="2100.815"/>
    <name name="lswmv" num="5" filesize="158266517" movie_length="2100.695"/>
    <name name="mpg" num="5" filesize="305189364" movie_length="2106.967912"/>
  </names>
</content>
</previewroot>
XML;

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('/previewroot/content/names/name[@movie_length != ""]');
echo "this many nodes have 'movie_length': " . count($result) . "<br />";
echo "the first movie_length is: " .$result[0][@movie_length];
?>

Lumpy fucked around with this message at 03:21 on Apr 1, 2009

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

supster posted:

Being pretty nitpicky here, but I would use this xpath expression to be a tiny bit cleaner:
//name[@movie_length][1]

For these reasons:
1) More flexible to change in the xml schema (not dependant on /previewroot/content/names/).
2) No need to do a string comparison if we just need to test the existence of @movie_length.
3) Might as well only return the data we need (first result only).



edit: nitpicky as hell

Next time, I'll just post the link. :colbert:

I kid, I kid: You are correct on every point, I just "spelled it all out" for the learnin'

Lumpy fucked around with this message at 06:29 on Apr 1, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

booshi posted:

I am having some problems with getting this code to redirect properly after properly logging in. I've been banging my head over this and I still can't figure out what I'm not doing right (certain things edited / in caps to hide specifics):


Any idea why this won't forward correctly after a correct login?

If there is any whitespace before the second header() it won't work. For example:

code:
<?php
$var = "on noe!";
// more code blah blah blah
?>

<?php
header("Location: /wee.php");
?>
Will not work since the whitespace between the end of the first PHP tag and the start of the second was output to the browser. That might not be your problem, but you didn't give any error messages it's giving you to make any better guesses and it's 1:30am and I should have been in bed hours ago :(

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

keveh posted:

OK, this is just driving me crazy and I know somebody will be able to tell me why I'm just being stupid!

I have a class which when built gets an array for one of the variables. The array contains the last 40 messages from a database, and a function is used to loop through these messages to display them. For each message I am looping through the array again to check is any of the messages was a reply.

My problem is that in the second function to check for a reply seems to be affecting the first functions array.

That probably doesn't make sense, so here's a miniature version of the class and what I am trying to achieve.


php:
<?

class Build {
        
  var $messages = array();
    
  function Build(){
      $this->messages = $this->getMessages();
  }
  
  function displayMessages(){      
      $list = $this->messages;
      $return = "";
      foreach($list as $msg){
          $return .= 'the message was: '.$msg->message.'<br />';
          $return .= $this->checkReply($msg->msg_id)
      }
      return $return;
  }
  
  function checkReply($id){
      $replies = $this->messages;
      $return = "";
      foreach($replies as $msg){
          if($msg->reply_id == $id){
              $return = 'a reply was: '.$msg->message.'<br />';
          }
      }
      return $return;
  }
  
}

?>


The result would be:

code:
the message was: this is not working<br />
and it would stop.

So it's like that accessing and looping through the array for the second time is putting it to the end of the array.

This is confusing me, because the loops aren't accessing array directly, it's placing it in a new variable inside the two functions.

So, what am I doing that is blindingly wrong. Your help is much appreciated!

I'm not sure I understand what you are asking, but your checkReply() function can only return one reply per message since you set $return to a new value with = instead of appending with .=

Echo the length and type of $this->messages to make sure it's what you think it is. It could be you are returning the database result set, not an array of the actual results in your getMessages() method.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Crazak P posted:

this is probably a really dumb question, but I can't seem to find the answer to it. How do you make a link where when you click on it, it automatically gives the save as prompt. I'd like to do this for jpg images.

I got 9 good tutorials on it on my first Google search.

I'll copy and paste the code from the first one here:

Some website posted:

php:
<?
// Tells the browser that where going to run a PHP script.
$file = $_GET['file'];
// Get a filename from the GET parameters.
Header ("Content-type: octet/stream");
Header ("Content-disposition: attachment; filename=".$file.";");
Header("Content-Length: ".Filesize($file));
// Sends the brower headers to tell it that its sending that file back to it.
Readfile($file);
// Reads the file from the server and send it to the browser.
Exit;
?>
Call it forcedownload.Php
Then your link would be

code:
<a href="http://www.Sitelocation/mp3s/forcedownload.Php?file=download.Mp3">Song Name</a>

Please note the pasted code there has a huge security hole in it, but it should give you the gist of how to do Save As.. boxes. If you don't want a new window popping up / replacing the current one, put a tiny / invisible eyeFrame on your page, and send the download link to it.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

Am I missing something or couldn't he just use Content-disposition: inline;... to prevent the browser from leaving the page?

I have no idea.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Safety Shaun posted:

I have some returned XML data in $xml using simplexml_load_file() and I want to extract $someTitle from it from $xml->a->b->c->d->Title , how would I go about doing so?

Thanks in advance

http://us.php.net/manual/en/function.simplexml-element-xpath.php

You are welcome.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

eHacked posted:

I'm learning OOP from a pretty fantastic book (so far): PHP Object Oriented Solutions by David Powers.

Anyway, he regularly says this "-> operator". Is there a name for '->'?

How the hell do I tell someone what I am talking about in plain English?

"The thing that most other languages use a dot for" At least that's what I call it. Was interesting to learn the actual name for it. :)

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Fangs404 posted:

I'm writing a website that has a lot of PHP files that need access to a DB (almost all of them do). Now, in order to avoid having to type something like

php:
<?
$conn = pg_connect('dbname=database user=username password=password');?>
over and over again in every file and have to deal with the inevitable username/password changes (that would have to propagate into every file obviously), I came up with a different solution. I have a file called dbconnect.php and all that's it in it is the above line. All I have to do is a require_once(dbconnect.php) in each page where I want access to the DB.

My questions: Is what I'm doing a security risk (that is, could someone else do a require_once(FULL_PATH/dbconnect.php) and get access to my DB?)? How do you guys deal with this problem?

Thanks!


Put anything that stores info you don't want known outside of web root. For example, if your web site is stored at:

/blah/some/path/webRoot/

Then have your files with db passwords and other stuff at:

/blah/some/path/hideMe/

And the web server can't serve the files up at all to people.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Vedder posted:

Got a bit of a weird on here. I have a newsletter to do and normally it has around 5 articles, each on in a seperate coloured div. I have found a tutorial which tells you how to make alternate coloured table rows and I have adapted this and it works fine with two colours, however I have 4. The code looks like this:

code:
$grey = 'grey';
$blue = 'blue';
$yellow = 'yellow';
$green = 'green';

$count = 0;


while ($row = mysql_fetch_array($news))
{
$count++;
$colour = ($count % 2) ? $grey : $blue;

echo '<p>$colour</p>';
If I change the line of code from

code:
$colour = ($count % 2) ? $grey : $blue;

to

$colour = ($count % 4) ? $grey : $blue : $yellow : $green;
My IDE has a fit and tells me its a syntax error. I have also tried setting up an array of colours and doing a for each loop but that just creates the number in the array (the 4 colours) matching the articles in the database (so it will display 4 article 1's, 4 article 2's, 4 article 3's etc).

It's normally dead simple when I am involved so no doubt you will spot whats going wrong straight away.

You are using the operator horribly wrong. The () ? : ; means "If what is in the parenthesis is true, do the thing after the question mark, if not, do the thing on the other side of the colon"

You can't just add more colons :)

You want to do something like:

php:
<?
$count = 0;
$colors = array('grey','blue','yellow','green');
while ($row = mysql_fetch_array($news))
{
  $count++;
  echo "<p>{$colors[$count % 4]}</p>";
}
?>
EDIT: link to ternary operator page: http://us2.php.net/ternary

Lumpy fucked around with this message at 16:12 on Apr 22, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mercator posted:

Thank you for your post, I welcomed the laugh that resulted. :)

code:
$colours = array();

$colours[] = 'grey';
$colours[] = 'blue';
$colours[] = 'yellow';
$colours[] = 'green';


$len = len($colors);
while ($row = mysql_fetch_array($news))
{
    $count++;
    $colour = $colours[$count % $len];
    
    echo '<p>$colour</p>';
}
edit: mine's better. :mad:
Yes, but leaving off the count() made my post first! Muahahahaha....


Why do you have the same avatar as Yodzilla? Every time I see one of your posts, I get all confused :)

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

drcru posted:

Thanks, I've stopped worrying about it now.

Here's another one, what do you guys use for templating your pages? Other than Smarty that is. Do you roll your own systems or just put the HTML in with your code? I've been using Smarty personally but it seems a little too much for what I need to do.

I use the CodeIgniter framework (although I am starting to use Kohana). If smarty is too much, then these are probably way overkill for you, but wouldn't hurt to take a gander.

Kohana: http://www.kohanaphp.com/
CodeIgniter: http://www.codeigniter.com

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Sylink posted:

I am making a wiki like site (I'm not using Mediawiki because I want something simpler) but I want to use/retain a lot of the similar formatting features as far as editing pages.

What is the standard way this is done?

Such as putting <p> tags around blocks of text and converting ==Hello World== into <h2>Hello World</h2> and so on. Is it just straight up string parsing with a lot of counting involved or is this a different way?

Or would it be easier to simply allow certain html tags?

EDIT: Would it be easier for me to just use something like php markdown ? http://michelf.com/projects/php-markdown/

There are much simpler wikis out there. Why re-invent the wheel?

For the actual answer to your question, look at the source to Mediawiki and others and see how they do it.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

usingpond posted:

I'm trying to make a CMS for a Flash application that reads data from XML. I'm trying to use DOM PHP (it seemed a little more legit than SimpleXML when I started).

Reading and displaying XML with DOM is easy enough, but is there a simple way to edit it?

Use the DOM XML Methods for editing to edit it? What exactly are you having trouble figuring out what to do?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

usingpond posted:

Well basically, I wanted to edit a child from this:

code:
<root>
   <parent name="parent">
      <child>info</child>
   </parent>
</root>
To this:
code:
<root>
   <parent name="parent">
      <child>DIFFERENT INFO</child>
   </parent>
</root>
I can't seem to figure out an easy way to use the replaceChild method, or if that's even the correct method to use. All the examples I've found are part of a huge framework that are really complex, and nothing seems to simply explain how to do such a basic function.

I have no idea if you are using PHP4 or 5, here's a 4 example

php:
<?
// assume you've read in the XML to $myXML
$root = $myXML->document_element();
$parentTag = $root->first_child(); // you could skip this and do it directly below, but to be clear.
$childTag = $parentTag->first_child();
$childTag->replace_child("DIFFERENT INFO",$childTag->first_child());
?>
and since I'm such a drat nice guy, here's a PHP5 example:

php:
<?
$myXML = new DOMDocument();
$myXML->loadXML('<root><parent name="parent"><child>info</child></parent></root>');
$xpath = new DOMXpath($myXML);
$nodelist = $xpath->query('/root/parent/child');
$kidNode = $nodelist->item(0);
/* 
you could also have done:
$kidNode = $myXML->firstChild->firstChild->firstChild;
*/
$newContent = $myXML->createTextNode("DIFFERENT INFO");
$kidNode->replaceChild($newContent,$kidNode->firstChild);
echo "<PRE>";
echo htmlentities($myXML->saveXML());
echo "</PRE>";
?>

Lumpy fucked around with this message at 00:46 on May 27, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Jreedy88 posted:

I'm working on some PHP code some old guy set up here at work. I hadn't looked at anything PHP until two days ago, so I'm still fairly new to this. I came across this and it didn't look right. Also, I don't think it's working as intended. Please shed some light on this.

This function is called in one part of a file:
executefootagetransaction(false);

Here's the function signature:
function executefootagetransaction($zero, $consumeroll = false)


Firstly, if you're going to call a function, don't you need to supply both arguments? Secondly, what is that $consumeroll = false nonsense in the signature?

Firstly, no.
Secondly, that's how you make it so you don't have to supply all the arguments.

In PHP, and many other languages, you can set arguments to default values, so taht if the argument is not supplied, it's set. Here's fun made up code to learn you:

php:
<?

function blah($name="Dave",$msg="Sup d00d")
{
 echo "Hey $name, $msg";
}

blah(); // "Hey Dave, Sup d00d"
blah("Larry"); // "Hey Larry, Sup d00d"
blah("Skippy","you suck"); // "Hey Skippy, you suck"
?>

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Golbez posted:

Out of curiosity, is there any way to skip the first argument in that? So like...

php:
<?
blah(,"you suck"); // "Hey Dave, you suck"
?>
?

I do not say this with 100% certainty (but like 99.8%), but no. You can't pass over arguments.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

stoops posted:

i'm only storing the resume name in the db field.

do you know of any php scripts that will actually look and search words within a directory's files.

You can use PHPs file handling abilities to read each file in, search words, close, etc. Or you can use shell_exec() to use grep or whatever. I'd go with the latter, and make sure you are caching results or building an index of matches to avoid duplicate searches and so on.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

FeloniousDrunk posted:

Before I kill myself any further, is there something in PHP already out there that functions as a proxy? I'm working on a mobile (i.e. PDA) interface to a highly organic (since 1996 if not before) site that has all manner of crap in it, from PDFs to JSP to Perl CGI to straight (if very nonstandard) HTML. The basic operation is:

code:
[url]http://site.com/m/index.php?page=http://site.com/requested_page.html[/url]
will return http://site.com/requested_page.html with images/embeds/style/script taken out and some other minimalization and URL rewriting to point back at the minimizer/proxy. It's working pretty well, but the thing that's blocking me is cookies, it seems. I'm using curl like so:

code:
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
but the minified login page always complains that I have to turn cookies on. So, a) like I asked before, is there something like what I'm trying to do out there already, or b) am I totally wrong on that cookie business?

I have successfully done this, so I know it can be done... I'd have to dig through my work machine's backup HD to look for my stuff, but this page here might give you an "ah-hah!" until I can find my stuff or somebody else can help you out:

http://www.weberdev.com/get_example-4555.html

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Hammerite posted:

Is there a good reason to use sprintf instead of str_replace? Is it faster?

You use them for very different things in general, so it's not really an "instead" thing.

EDIT: as for the discussion du jour, I used to be an echo guy, but I have come to love the printf

Lumpy fucked around with this message at 23:58 on Sep 2, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Hanpan posted:

Does anyone have any neat methods for preparing a associative array for use in a SQL update statement? Normally I do something like this:

code:
$str = "";
foreach($values as $key=>$value)
{
   $str.= $key.'=\''.$value.'\',';
}
Then remove the last comma using substr. It's really messy, and I am sure there is a nicer way of doing it?

Use a SQL library or framework that accepts your array?

code:
$this->db->update('mytable',$array);
EDIT: fletcher!!! :argh:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

royallthefourth posted:

Why?


Hammerite posted:

I find object oriented programming style difficult to understand...

To which I ask: why?

EDIT: damnit! :argh: (I seem to be doing that a lot lately)

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

J. Elliot Razorledgeball posted:

How can I convert a number like:

code:
4.7573500000e+03
To a legitimate float?

$afloat = printf('%f',$yourVar);

Or that better way above this post. :v:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

You're having an off week, man :\ Hope it gets better.

That's what I get for trying to help people.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

WhiteHowler posted:

I tried making an array of objects, but I obviously did something very wrong...

php:
<?
class playerrankclass {
    public $rankname;
    public $rankmin;
    public $rankmax;
}

$playerrank = array();

function getplayerranks() {
    $query = "select * from tblPlayerRank";
    $rankresult = mysql_query($query);
    $ranknumrows = mysql_num_rows($rankresult);

    for ($i=0; $i<$ranknumrows; $i++) {
        $thisrank = mysql_fetch_array($rankresult);
        $playerrank[] = new playerrankclass($thisrank[PlayerRankName], $thisrank[PlayerRankMin], $thisrank[PlayerRankMax]);
    }
}

getplayerranks();
?>
The query completes correctly, and the data is making it into the $thisrank object (I put in some debug code to echo the contents of $thisrank after each mysql_fetch_array).

However, I don't get anything back when I attempt to access an element of playerrank[]:

php:
<?
$i = 0;  // or whatever
echo $playerrank[$i]->rankname;
?>
This returns nothing.

I'll admit I'm kind of in over my head here. I haven't used PHP in two or three years now, and I've obviously forgotten a lot of stuff that used to be second nature.

You need to explicitly set the class variables, unless something has changed and there's magic assignment of arguments to class member vars based or order defined or something... which might be the case, because my PHP is rusty. :)

Think of it this way: How does new playerrankclass('poop',1,3) know what do to with the string 'poop' and the numbers 1 and 3?

You either need to make a constructor function in your class that takes arguments, or set them then add to your array:

php:
<?
$tmp = new playerrankclass();
$tmp->rankname = 'poop';
$tmp->rankmin  = 1;
$tmp->rankmax = 3;
$plyerrank[]= $tmp;
?>

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

WhiteHowler posted:

Oh, that makes sense.

I swear I used to know all of this. :sigh:

Thanks for the help; I have a feeling this will make it work just fine.

Edit:
It's still not working quite right.

I added the constructor to the class. However, trying:
php:
<?
foreach ($playerrank as $rankvalue) {
    echo "Array value: ".$rankvalue->rankname."<br>";
}
?>
...gives me thirteen lines of:
code:
Array value: 
Obviously $playerrank is being created with 13 elements (this is the correct number of rows in the table), but I'm not really sure that the values are correct/accessible.

Edit #2:
count($playerrank) is also showing 13 elements. Am I just attempting to access the values incorrectly?

what does print_r($playerrank); output?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Xarthor posted:

Hopefully this doesn't need it's own thread.

Here's my situation: I just started a website using Word Press (http://www.intensivepurposes.net). At the top of the page you'll notice I have a text banner. I'd like to change that into a .jpg graphic banner, but I can't seem to figure out how to do it.

Everything on the right side of the page (from the Twitter brid down) is controlled by sidebar.php.

There is a topbanner.php, but all it contains is

code:
<?php if(get_theme_option('topbanner') != '') {
	?>
	<div style="text-align: center; padding: 10px;">
		<?php echo(get_theme_option('topbanner')); ?>
	</div>
<?php } ?>
I'm trying to figure out:
1) What the dimensions of a graphic banner would be (to me it looks around 600x200)
2) Where I would insert the <img src=> HTML.

If it matters, I'm using the Modern Style Theme, which you can view/download at http://flexithemes.com

Thanks in advance!

The fine folks in the Wordpress Thread could probably help you out better than us slobs.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Fruit Smoothies posted:

This isn't a pure PHP question per se, but I hope you guys can help.

Basically, I'm working on a system where users own a variety of different items. For the purpose of this example, I'll make an analogy with a shop: Users can own bread, cars or TVs. The table structure is set out such that each item type exists in two tables: `item` and `useritems` (EG: `types_of_bread`, `userbread`)

That's all gravy, but each item can have a series of modifiers. Essentially, these can either add stats to the item (for example enhance the car's maximum speed) or change the item completely (bread -> toast)

In either case the modification needs two (pseudo)"events" -> "onapply" and potentially "onremove" that fire when the user activates the modification. I am wondering how to implement this. A rather messy solution, would be to put raw PHP in the DB, and eval() it, but that stinks of bad design and potentially horrific debugging.
code:
| ID	| name	| onapply		| onremove		|
-----------------------------------------------------------------
|0	|toast	|<? removeItem(bread, 	| <? //Not applic ?>	|
|	|	|$user); addItem(Toast,	|			|
|	|	|$user);		|			|
|	|	|?>			|			|
|	|	|			|			|
-----------------------------------------------------------------
Then I thought about writing the events in SQL and querying them with PHP.

Does anyone have a better solution to this problem. Ideally, I would love to over-engineer the problem by writing my own language :P

Serialize can store objects / classes in a db, but I'm not sure that's what you need, because I'm not sure I fully understand your problem.

Does one user change ALL bread to toast, or just his own bread?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Amethyst posted:

Hey guys, I'm helping my GF write her honours thesis with a simple php scraper of a vBulletin board (not SA).

I'm not particularly proficient with php and an just making the very first steps. What I need help with is how to get php to "log in" so it can view content available to members. Is there a way to load cookies into php before using file_get_contents($url)?

http://php.net/manual/en/function.file-get-contents.php

Crazy what they put in the documentation these days. Example 4.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

drcru posted:

How would I go about making sure something happens 75% or n% of the time?

If that didn't make sense, how can I make a random event happen n% of the time whenever a page is loaded.

I tried this but this doesn't seem right.

php:
<?
$r = rand(1,100);
if($r <= 75)
    echo "hit";
else
    echo "miss";?>
Thoughts?

Did you initialize the random number generator at some point? [EDIT] looks like you don't need to do this since 4.2, but I dunno what version you are on....

php:
<?
srand( time() );
$num = rand(1,100);
printf("I generated %d", $num);
if( $num <= 75 )
{
 // yippie!
}else
{
 // boo
}
?>

Lumpy fucked around with this message at 07:51 on Dec 17, 2009

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

KuruMonkey posted:

Edit: they have a variable caled $ok2...its an array!

To be fair, the keystrokes you save are well worth the slight loss in clarity of having to type out $okAsWell every time.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

supster posted:

Or it could just be named something that is meaningful in context of what the variable represents...

You don't "get" jokes, do you.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Hammerite posted:

Oh ok. I wouldn't go to that trouble. You could instead do the following
code:
if ( isset($_GET['id']) ) {
    $mystring = '';
    $id = (string)$_GET['id'];
    $numbers = array('0','1','2','3','4','5','6','7','8','9');
    for ( $i=0; $i<strlen($id); $i++ ) {
        if ( in_array($id[$i],$numbers) ) { $mystring .= $id[$i]; }
    }
    if ( strlen($mystring) ) {
        include ('./pages/'.$id.'.html'); // *
    } else {
        include ( your default error page goes here );
    }
} else {
    include ( your default error page goes here );
}
NB. I have reinvented the wheel with the above code, because I couldn't remember how to match start and end characters of a string using a regex (there is some worry to do with unintentionally matching new lines I think), and I couldn't be bothered to work out the right google search terms to look it up.

* It occurred to me also that there should really be a line of code here that checks whether the requested page actually exists, and just gives an error page in response if it doesn't. Otherwise what will happen if the file isn't there is PHP will give an error message of its own, which will look much more crude to your users.

Are you really casting it to a string then checking against an array of strings that happen to also be the digits 0 - 9 to check to see if the input is a number? :wtf:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Hammerite posted:

That's right. The reason I'm doing something so convoluted is because I wasn't sure what behaviour PHP exhibits if you ask it whether a non-numeric single-character string is equal in value to integer zero. i.e. I wasn't sure whether for example 'X' == 0 or '.' == 0 evaluate to true or false. I wanted to make sure only digits can get through. While the code I posted is rather stupid, I believe it's secure. I didn't want to post insecure code for the guy. As I mentioned, if I could have been bothered to look up the right way to do it with a regex I would have done that instead.

php:
<?
if(preg_match('/^\d+$/', $_GET['id']) )
{
  // hooray!
} 
?>

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Tivac posted:

Did I miss something? Why wouldn't you use PHP's built-in (since 5.2) input filtering?

php:
<?
$clean = filter_input(INPUT_GET, "id", FILTER_SANITIZE_NUMBER_INT);
?>

Because id=2132+323213 would still get through.

php Manual posted:

FILTER_SANITIZE_NUMBER_INT : Remove all characters except digits, plus and minus sign.

EDIT:

To see, I whipped this up:
code:
  1 <html>
  2 <body>
  3 <p>CLEAN is:
  4 <?php
  5 $clean = filter_input(INPUT_GET, "id", FILTER_SANITIZE_NUMBER_INT);
  6 echo $clean;
  7 ?>
  8 </p>
  9 <p> Regex test:
 10 <?php
 11 if(preg_match('/^\d+$/', $_GET['id']) )
 12 { 
 13   echo "Passed!";
 14 }else
 15 { 
 16   echo "Failed";
 17 }
 18 ?>
 19 </p>
 20 </body>
 21 </html>
and added ?id=43-43 to the URL, and it output:

code:
CLEAN is: 43-43

Regex test: Failed
What's odd is that it seems to remove '+' characters, but not '-'... :iiam:

Lumpy fucked around with this message at 20:26 on Jan 8, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Firequirks posted:

I just started using CodeIgniter a couple days ago, but I see that the thread has gone to archives.

In the CI "Create a Weblog in 20 Minutes" tutorial, the coder takes form data for submitting a comment and uses a single line of code to insert into the database. This happens at about 1:10 in the video.
code:
$this->db->insert('comments', $_POST);
This is highly attractive -- one line to insert into the DB? drat, I'm living in a whole new world!

Except I can't get it to work for me. The insert function is not stripping the form submit button from the $_POST data. I would prefer to not have to pick apart each element of the form data if possible. So what I'm asking is, what do regular users of CI do? Most of the tutorials I've found basically involve going through each form element and saving it separately from $_POST, then passing the whole thing to insert. This seems like wasted effort, but is there a good reason why I don't see people working that way? The CI docs even mention that the insert function automatically escapes the data, and I don't see any tutorial adding any extra security, so I'm wondering if there's a good reason. The video is two years old; maybe the functionality has changed?

Did you set up scaffolding? oops, I read you wrong...

Seems like he's got the field names in the form lined up with the field names on the DB table, is yours set up the same way? And yes, using Active Record cleans data IIRC.

Lumpy fucked around with this message at 22:31 on Jan 16, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Firequirks posted:

Yes, that's all correct. The only issue is that it's not stripping out the name and value for the Submit button from the $_POST array when inserting. The error specifically mentions that I'm trying to add a row to my ingredients table with a 'submit' column that doesn't exist:
code:
A Database Error Occurred

Error Number: 1054

Unknown column 'submit' in 'field list'

INSERT INTO `ingredients` (`name`, `price`, `quantity`, `quantity_type`, `submit`) 
VALUES ('pepsi', '0.99', '330', 'mL', 'Add Ingredient')

Don't give your SUBMIT button a name?

EDIT: Yeah, I looked at his code in the video you posted, and there's no NAME attribute on the SUBMIT button.

Lumpy fucked around with this message at 22:39 on Jan 16, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Firequirks posted:

I had been using the Form Helper functions to make my form
code:
<?php echo form_submit ('submit', "Add Ingredient"); ?>
so I tried it the video way by just writing out the HTML and not including the name. But without the name, it causes another problem:
code:
if ($this->input->post('submit')) {
    $this->Ingredient_model->add();
}
That if statement will never be true, because the name is relied upon for the post function. :(

Edit: Perhaps I should do it entirely like the video, where he has written a no-view insert function?

Yeah, his code is far from best practice, as it's a hack job to show how fast things can be in a hypothetical best-case world.

You can cheat if you really want the "simplicity" by either manually making the submit button, leaving the name off and changing your if statement:

code:
if( $this->input->post('some_other_field_name') )
{
  // blah
}
or you can do it the way you are doing it, and unset 'submit' before you process:

code:
if( $this->input->post('submit') )
{
  unset( $_POST['submit'] );
  // blah
}
EDIT: you can also see what <?php echo form_submit (false, "Add Ingredient"); ?> does to use the helper and still have no name attribute.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

electricHyena posted:

This might be the easiest question in here, as I know nothing about PHP. I just installed ZenPhoto on my site and I'm having some issues with the code.

My problem right now is that the page with all the images on it displays the actual text "view slideshow" as the link to the slideshow page. I would really prefer it to be a button instead, but have no idea how to make it insert an image in that spot.

I'm pretty sure this is the line that does it:
code:
<?php if (function_exists('printSlideShowLink')) printSlideShowLink(gettext('View Slideshow')); ?>
This seems like it would be really simple but I have no idea where to begin.

There will be a function called "printSlideShowLink()" somewhere in ZenPhoto. It looks like it takes a string argument, which is being obtained form some sort of localization function 'gettext()'

I'm guessing this function spits out a string like:

code:
'<a href="/' + someDynamicThing + '">' + the StringArgument + '</a>'
You will want to change it to spit out somethign like:

code:
'<a href="/' + someDynamicThing + '"><img src="/myCoolViewGalleryButton.gif" /></a>'
Search for the string "function printSlideShowLink(" in the source code of ZenPhoto to find it's definition.

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

KuruMonkey posted:

Just a little aside:

http://php.net/manual/en/book.gettext.php

Its PHP's built in localisation.

Ahh, cool. I use my framework's localization stuff, had no clue PHP even had that built in. One of these days I should actually just spend some time reading the manual. I picked up PHP as a "solve this specific problem" tool, so I know the parts of it I've used well, but never really looked around at the rest of it much. Then again, I don't do all that much PHP any more. :effort:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply