Jump to content

berridgeab

Members
  • Posts

    112
  • Joined

  • Last visited

Posts posted by berridgeab

  1. Very nice ignace, the HTTPRequest class doesn't get filled but I think thats down to not being able to use variable variables with PHPs superglobals.

     

    http://php.net/manual/en/language.variables.variable.php

     

    Anyway thats a minor issue, you've gave me some ideas and a direction to follow. Thanks for your response.

     

    Edit - Updated HTTPRequest class to get around variable variable issue.

    class HttpRequest
    {
        public $get;
        public $post;
        public $cookie;
        public $session;
        public $server;
        public $files;
        public $env;
    
        public function __construct()
        {
            foreach (array('get', 'post', 'cookie', 'session', 'server', 'files', 'env') as $superGlobal)
            {
                $globals = $GLOBALS;
                if(isset($globals['_' . strtoupper($superGlobal)]))
                {
                    $this->$superGlobal = new RecursiveArrayWrapper($globals['_' . strtoupper($superGlobal)], ArrayObject::ARRAY_AS_PROPS);
                }            
            }
        }
    }
    
  2. Hi,

     

    I'm looking to create a basic superglobal class wrapper for the PHP super globals. I don't know how to go about setting nested array keys / values within the object.

     

    Here is my basic class wrapper -

    	class superGlobal 
    	{
    		protected $superGlobal;
    		
    		public function __construct(array $superGlobal)
    		{
    			$this->superGlobal = $superGlobal;
    		}
    		
    		public function set($value, $arrayKey = null)
    		{
    			if(is_scalar($arrayKey))
    			{
    				$this->superGlobal[$arrayKey] = $value;
    			}
    			else
    			{
    				$this->superGlobal[] = $value;
    			}
    		}
    		
    		public function get()
    		{
    			return $this->superGlobal;
    		}
    	}
    

    A very simple wrapper. Thanks to the addition of array literials in PHP5.5 I can access single or nested array values easily like below so no problem here.

    $nestedArray = array(
        "Unnested Array Value",
        array(
            "Nested Array Value"));
    
    $superGlobal = new \superGlobal($nestedArray);
    
    //Outputs "Unnested Array Value"
    echo $superGlobal->get()[0]
    
    //Outputs "Nested Array Value"
    echo $superGlobal->get()[1][0]

    However I have no idea how to write a "set" function that can accept a nested key . Any ideas? Currently I have to get the nested array, store it in a temporary variable like below.

    	//Create superglobal object with random nested array and output
    	$superGlobal = new \superGlobal(array());
    	$superGlobal->set(array(0 => array(0 => array(0 => "Apples"))), "nestedItem");
    
    	//Output array
    	echo "<pre>" , print_r($superGlobal->get(), 1) , "</pre>";
    	
    	//Grab array and store 
    	$temporaryStore = $superGlobal->get()['nestedItem'];
    	//Add  new value to the nested array
    	$temporaryStore[0][0][1] = "Oranges";
    	
    	//Now reset the value
    	$superGlobal->set($temporaryStore, "nestedItem");
    	
    	//Output array
    	echo "<pre>" , print_r($superGlobal->get(), 1) , "</pre>";
    

    Basically I want to cut out the step of having to store the array into a temporary variable, modify it and reassigning it. I could make the variable public, but I would prefer not to.

     

  3. Hello

     

    Windows Server 2008

    PHP 5.5.0

     

    Im confused on how PHP handles TimeZone settings, please see my example below.

     

    The Windows Server 2008 server system time is set to 2013-07-17 11:23 (Windows System TimeZone - Europe/London) which can also be written as July 17th 2013 11:23 a.m for our American friends.

     

    In my PHP.ini file I set the date.timezone to "Europe/Paris". So my Windows system TimeZone is "Europe/London", but my PHP ini file setting is "Europe/Paris".

     

    I run the following code -

     

     

    echo date("Y-m-d H:i");

     

    I would expect the output to be 2013-07-17 11:23, the same time as my system time.

     

    Its not, it is 2013-07-17 12:23, 1 hour ahead.

     

    I thought that if I set the timezone in the PHP.ini file, then PHP would think that it is 11.23 in Paris.

     

    However PHP seems to be detecting that the system is actually based in London from the windows server setting and adding on an extra hour.

     

    Is this the default behaviour? I can't find anything mentioned in the PHP manual. The only thing I can find mentioning anything about variable timeZones is here -

    http://www.php.net/manual/en/function.date-default-timezone-get.php#refsect1-function.date-default-timezone-get-description

     

    Im guessing Linux / AppleOS installations have there own timezone setting and replicate this behaviour?

  4. Hello

     

    I have a design issue that I have never really known how to approach solving. Its a generic question not related to any specific scenairo. When I need to query a database table i.e. say a generic product table, sometimes I need to restrict what rows I return. I.e. I may only want products that have not been sold.

     

    So my SQL string would look somthing like

    $query = "SELECT * FROM products WHERE status != 'Sold';
    

    Sometimes I perform more complicated queries on other tables. Say for instance I may need to join my product table to a theoretical orders table. This would result in a SQL query like

    $query = "SELECT * FROM orders LEFT JOIN products ON products_id = orders_product_id WHERE order_id = 1 AND status != 'Sold';
    

    My problem is that I now have 2 different pieces of SQL code in 2 different places. Both snippets of code have something in common

    status != 'Sold' /*This is the only bit im really interested in*/
    

    What is the best way to maintain bits of SQL code that needs to be the same across the entire site?

  5. On the surface of it, that doesn't look like the right way to do things.  I think you would be better having a single "User" class with, perhaps, a status property that defines if the user is registered or unregistered.

     

    I omitted the functions / properties to keep the example simple but I do have a basic User class. It just made sense to me that seen as a RegisteredUser has all the properties of an UnregisteredUser that the RegisteredUser should extend from that class.

     

    I could get around it doing the checks you have suggested but I can't believe there is nothing native in PHP that says "are you an instance of this particular class?".

     

    In the end I have opted for get_class($var) which allows me to check the class string name.

  6. Hello

     

    Looking for a way to check for a specific class, can't believe I can't solve something so simple.

    <?php
    class UnregisteredUser {}
    class RegisteredUser extends UnregisteredUser {}
    
    $unregisteredUser = new UnregisteredUser();
    $registeredUser = new RegisteredUser();
    
    if($registeredUser instanceof UnregisteredUser)
    {
        //Section A
    }
    elseif($registeredUser instanceof RegisteredUser)
    {
        //Section B
    }
    ?>
    

    I want to check if variable $registeredUser is an instance of RegisteredUser.

     

    With the above code, Because RegisteredUser inherits from UnregisteredUser, it executes section A (even though I don't want it too).

     

    Is there anyway I can check if a class is actually a specific class with no consideration to its inherited properties?

     

    I know instanceof doesn't work, nor does is_a().

     

    Is my class design ok?

     

    The only reason RegisteredUser inherits from UnregisteredUser is because it contains functions and properties that are common to both classes. I could seperate them but  defeats the purpose of inheritance.

  7. You need an Insert Select syntax.

     

    You only need the clientId from the other table, and Select will return strings so long as you have properly escaped them.

     

    You will need to do some of the POST keys.

    $query = "
    INSERT INTO
    Jobs (Username, ClientID, JobNumber, Description, Status)
    SELECT
    '{$_POST['someVar']}',
    clientId,
    '{$_POST['someVar']}',
    '{$_POST['someVar']}',
    '{$_POST['someVar']}'
    FROM Clients
    WHERE clientId = 2";
    

  8. Sorted, slight modification to the above code from StackOverflow finally got the desired structure.

     

    $originalArray = array(
    0 => array(0),
    1 => array(0,1),
    2 => array(0,2),
    3 => array(0,2,3),
    4 => array(0,4));
    $desiredArray = array();
    foreach($originalArray as $oneDArray)
    {
    $arrayPointer =& $desiredArray;
    foreach($oneDArray as $arrayValue)
    {
     if(!is_array($arrayPointer[$arrayValue]))
     {
    	 $arrayPointer[$arrayValue] = array();
     }
     $arrayPointer = &$arrayPointer[$arrayValue];
    }
    }
    //Output
    Array
    (
    [0] => Array
     (
    	 [1] => Array
    		 (
    		 )
    	 [2] => Array
    		 (
    			 [3] => Array
    				 (
    				 )
    		 )
    	 [4] => Array
    		 (
    		 )
     )
    )
    

  9. No not homework it is for the job I do however I'm stuck. Ive been at it for 4 hours. I haven't posted my own example code becuase nothing I have done has got close to what I want. It could be done multiple ways im just struggling to understand the logic behind it. I know I will need pointers. The closest I have got is an unrelated answer on stack overflow.

     

    $originalArray = array(0,1,2,3);
    $desiredArray = array();
    $arrayPointer =& $desiredArray;
    
    foreach ($originalArray as $arrayValue) {
    $arrayPointer[$arrayValue] = array();
    $arrayPointer	 =& $arrayPointer[$arrayValue];
    }
    
    //Output of $desiredArray
    Array
    (
    [0] => Array
     (
    	 [1] => Array
    		 (
    			 [2] => Array
    				 (
    					 [3] => Array
    						 (
    						 )
    				 )
    		 )
     )
    )
    

     

    This gives me the desired array as long as I only work on one array. As soon as I try to put it in a loop (like below) with the remaining arrays, it goes wrong.

     

    $originalArray = array(
    0 => array(0),
    1 => array(0,1),
    2 => array(0,2),
    3 => array(0,2,3),
    4 => array(0,4));
    
    $desiredArray = array();
    $arrayPointer =& $desiredArray;
    foreach($originalArray as $singleArray)
    {
    foreach ($singleArray as $arrayValue)
    {
    $arrayPointer[$arrayValue] = array();
     $arrayPointer	 =& $arrayPointer[$arrayValue];
    }
    }
    
    //Output of $desiredArray too big to show
    

  10. Hello

     

    This is kinda hard to explain. I need to take a flat 1D array full of values and turn it into a multidimensional array.

     

    This is the original array structure. The keys in $originalArray are not related to the structure of the desired array.

     

    $originalArray = array(
     0 => array(0),
     1 => array(0,1),
     2 => array(0,2),
     3 => array(0,2,3),
     4 => array(0,4));
    

     

    This is the desired array structure

     

    $desiredArray = array(
     0 => array(
    	 1 => array(),
    	 2 => array(
    		 3 => array()),
    	 4 => array()));
    

     

    Basically each sequential value in the $originalArray[X] must be nested into a new level.

     

    I.e. 0 is the outer most key. The next level will contain 1,2 and 4. The next level (of key 2) will only contain 3. This should recurse and nest for each value,

     

    Unfortunately I cannot do this. I know its something to do with references but I can't figure it out. Any ideas?

  11. You need to turn off notices or define the variable before using it. I recommend turning notices off in production seen as variable initialisation is not required in PHP.

     

    Edit: Just looked at the code gain, make sure you haven't copy and pasted the variables testing the functions, you wont need them.

  12. Hi

     

    $_FILES['uploadedfile'] is not the name of your upload field. $_FILES['uploaded file'] would be correct.

     

    //HTML
    <input type="file" name="uploaded file" />
    
    //PHP
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ". basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
    } else{
    echo "There was an error uploading the file, please try again!";
    }
    
    

     

    You also have some invalid HTML here, td cant have an action / method / enctype.

     

    <td style= "position:absolute; top:272px; left:570px" enctype="multipart/form-data" action="html_form_send.php" method="POST" >
    

     

    I suggest you do a print_r($_FILES) to see what the error is. The error will be in the array if there is one. I imagine it will work if you change the $_FILE key, your looking for a key that doesn't exist according to your HTML.

  13. Theres further stuff you can do (regnerating session ids after a certain time interval, autologout after x time of inactivity, force logoutt on ip change etc) but it depends specifically on your security needs.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.