Jump to content

Slips

Members
  • Posts

    50
  • Joined

  • Last visited

    Never

Posts posted by Slips

  1. Hello all,

     

    My knowledge in PHP is growing everyday as I try out more stuff but I really didn't understand this bit :

    "Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions. ".

     

    taken from the page : http://www.php.net/manual/en/language.operators.comparison.php

     

    From what I understood, if I was to use a ternery condition in the return statement, and return a referenced variable as a result, it

    shouldn't work?

     

    So this shouldn't work?

    $int = 10;
    
    function testReturn(&$referencedVariable) {
    return (1==1) ? $referencedVariable : FALSE;
    }
    
    echo testReturn($int);
    

     

    But it does. Anyways i'm pretty sure I didn't understand this right, so help with this is really appreciated :D

     

     

  2. Hi guys, I am trying something fairly simple but I'm not sure if this would be a good practice. Basically I am using a big class called CommonLibrary that holds common functions as methods and common variables as static variables. But I have some variables here and there like $allAlphabet = range ('a' , 'z'), that cannot be declared as a property because it gives me a parse error.

     

    I don't want to call an object for this class because instancing it is of no use. Values will never change with regards to instances. So the next best thing that I tried was declaring all static variables first, and then changing thei property values inside the class __construct with self::$variable = 'somevalue', and then using this code below to assign values to the empty static variables.

     

    $dummyObject = new CommonLibrary;
    unset($dummyObject);
    echo CommonLibrary::$staticVariable; // This property is NULL before the constructer is triggered.
    

     

    Anyone recommend any better ways of doing this?

     

    Thanks in advance!

  3. Ok firstly I cannot use file_get_contents, because I want to read the file line by line and omit the lines I don't want. Using file_get_contents() with a regex to sniff those lines out seems more complex. Also file_get_contents is not preserving line breaks, something which I'll have to add manually.

     

    Basically what I'm trying to do, is remove entries for a web project on prompt from the /etc/hosts file. I was using file handlers because I can scan the file line by line and dump only the necessary entries into a new variable and omit the unwanted entries. This 'new' config will then overwrite the previous hosts file.

     

    Here is what my code must do :

     

    Create new variable that will hold the new overwriting config

    Open hosts file

    Scan entires in it line by line and dump lines that are needed into the variable we created

    Overwrite the old config text with the new config txt in the variable with fwrite()

  4. Hello all,

     

    I'm trying to open a file, take some text from it conditionally, and paste the newly edited text back into the same file.

     

    At first I used a seperate  fopen($handle, 'r') handler to open the file to read it, get its contents CONDITIONALLY, close the read handler, and open a new write handler to overwrite the file.

    In short, I need to extract the text from the file after ignoring some amount of text , and then rewrite the file with the newly altered text.

     

    I was trying out r+ and w+ options when using fopen(), but w+ is working in a way thats leaving me confused. Here is my code.

     

    $file = 'test.txt';
    $fileHandle = fopen($file,'w+');
    fwrite($fileHandle, 'Newly inserted text');
    $fileContents = fread($fileHandle, filesize($file));
    echo $fileContents;
    fclose($fileHandle);
    

     

    The manual says that if the w+ option is specified then the file is opened for reading and writing. From what I understand this means that I should be able to read from the file after writing to it. But the code above displays nothing after writing to the file. The file is chmodded 777.  Can someone please explain to me why this is so :D

     

    Thanks

     

  5. Hello all, I have some piece of code that is nested like this

     

    $variable = 'This is a global argument';
    function parentFunction($variable) {
    function childFunction() {
    	echo 'Argument of the parent function is '.$GLOBALS['variable'];
    }
    childFunction();
    }
    parentFunction(5);
    

     

    What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot :D.

     

    Thanks in advance

  6. Hmmm all variables seem fine on my checking but here is the full code anyways. The script is incomplete, but with regards to creating a working HTTP config file i guess this is all that is needed for now :

     

    Don't worry about the include file, its called because it contains a function that converts a text into camelcaps.

     

    Here is a quick overview of the logic so you guys can understand this code quicker :

    1. Run script in command prompt

    2. Ask user for Full project name. User types something like "PHP Freaks"

    3. Ask user for short project name. User types something like "phpf" (Needed for naming directories)

    4. Start a foreach loop that asks user if they want a separate domain for css,jss,images files. If user types 'y' - use sprintf, and replace the customize the vhost config text (<Virtual Host:*80> ... </Virtual Host>)  with the respective subdomain name, and concantenate it to the final config text , inside each iteration.

    5. Looping and concatenation done, final config text is ready to paste with the vhost config text for 3x subdomains. Open a file and write to it.

     

     

     

    include '/var/www/common/lib/functions/all.php';
    
    // Ask for the Project full name and short name (Needed for naming conventions for files and directories etc.)
    
    fwrite(STDOUT,'Enter the full name of the Web Project please :');
    $fullProjectName = fgets(STDIN);
    
    fwrite(STDOUT, "Enter the short name for the project please : ");
    $shortProjectName = fgets(STDIN);
    
    
    
    $projectAliases = array($shortProjectName => $fullProjectName);
    
    // 1. Create a new File in sites-available folder.
    $sitesAvailableFolder = '/etc/apache2/sites-available';
    $httpConfigFile = $sitesAvailableFolder.'/'.convertToCamelCaps($projectAliases[$shortProjectName], TRUE);
    
    if(!is_file(trim($httpConfigFile))) {
    //HTTP config file does not exist, lets begin creating the config text
    echo 'HTTP Config file ', $httpConfigFile, 'not found, please follow the instructions below to create one.', PHP_EOL;
    
    $subDomainList = array('css', 'jss', 'images');
    // In the foreach loop below , using a $variable.= in the first iteration gives an error because it has nothing to concatenate to,
    // so I created 2 empty variables to concatenate to, anyone know any better ways of doing this?
    $subDomainConfig = ''; 
    $httpConfigFileText = '';
    
    foreach ($subDomainList as $index => $subDomain) {
    	fwrite(STDOUT, 'Would you like to add a subdomain for ' .ucwords($subDomain). ' files?');
    	${$subDomain.'Install'} = fgets(STDIN);
    	if (trim(${$subDomain.'Install'}) == 'y') {
    $subDomainConfig .=
    '
    <VirtualHost *:80>
    ServerAdmin webmaster@%2$s
    ServerName  %1$s.%2$s
    ServerAlias %1$s.%2$s
    # Indexes + Directory Root.
    DirectoryIndex index.html index.php
    DocumentRoot /var/www/%2$s/public_html/
    
    # CGI Directory
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Location /cgi-bin>
    	Options +ExecCGI
    </Location>
    
    
    # Logfiles
    ErrorLog  /var/www/%2$s/logs/apache/error.log
    CustomLog /var/www/%2$s/logs/apache/access.log combined
    </VirtualHost>		
    '.PHP_EOL;
    		$httpConfigFileText.= sprintf($subDomainConfig, $subDomain, $shortProjectName);
    	}
    }				
    
    
    
    
    // Take the contenated config text and write it to the file.
    
    try {
    	if ($fileHandle = @fopen($httpConfigFile, 'w')) {
    		if (!fwrite($fileHandle, $httpConfigFileText)) { 
    			throw new Exception('Failed to write the Virtual host configuration for '.$fullProjectName); 
    		} else {
    			echo 'The HTTP Config file was successfully created.', PHP_EOL;
    		}
    	} else {
    		throw new Exception('Failed to create the HTTP Config file '.$httpConfigFile);
    	}	
    } catch (Exception $e) {
    	echo 'Exception caught : ', $e->getMessage();		
    }
    
    } else {
    echo 'The file, ', $httpConfigFile, 'already exists.', PHP_EOL;
    }   
    

  7. Hello all,

     

    I am trying to create a PHP CLi Script that will help me setup new config and server files / directories for every new web project i get instead of me having to manually create everything with each project. The script accepts the project name, and y/n for whether i want to create subdomains for css, jss and image files. After it has that, it must create a new http config file under sites-available (in Linux), by pasting the config file text.

     

    Problem : If I output regular text to the file, it displays exactly in the format that I write the string variable. But when I use a printf, or try to use variables directly in the config text, it starts formatting the text in the config file in a strange way. I just want the variables to just be replaced and the text to appear in the exact format below. The text displays perfectly as i typed below in the config file if I don't use any variables.

     

    $subDomainConfig .=
    '<VirtualHost *:80>
    ServerAdmin webmaster@%1$s
    ServerName  %1$s.%2$s
    ServerAlias %1$s.%2$s
    
    # Indexes + Directory Root.
    DirectoryIndex index.html index.php
    DocumentRoot /var/www/%2$s/public_html/
    
    # CGI Directory
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Location /cgi-bin>
    	Options +ExecCGI
    </Location>
    
    
    # Logfiles
    ErrorLog  /var/www/%2$s/logs/apache/error.log
    CustomLog /var/www/%2$s/logs/apache/access.log combined
    </VirtualHost>		
    '.PHP_EOL;
    $httpConfigFileText = sprintf($subDomainConfig, $subDomain, $shortProjectName);
    

     

    The above code outputs text in this way in the file :

     

    <VirtualHost *:80>

    ServerAdmin webmaster@images

    ServerName  images.mysite

     

    ServerAlias images.mysite

     

     

    # Indexes + Directory Root.

    DirectoryIndex index.html index.php

    DocumentRoot /var/www/mysite

    /public_html/

     

    # CGI Directory

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

    <Location /cgi-bin>

    Options +ExecCGI

    </Location>

     

     

    # Logfiles

    ErrorLog  /var/www/mysite

    /logs/apache/error.log

    CustomLog /var/www/mysite

    /logs/apache/access.log combined

    </VirtualHost>

  8. Hello all,

     

    I just created this function that I want to use in CLi mode. It works perfectly in regular browser mode, but gives me this error on Cli mode if I do convertToCamelCaps('TEST STRING');

     

    PHP Catchable fatal error:  Argument 1 passed to convertToCamelCaps() must be an instance of string, string given in file...

     

    if (!function_exists('convertToCamelCaps')) {
    function convertToCamelCaps(string $string, $initialCaps=FALSE) {
    	if ($words = explode(' ',$string)) {
    		foreach ($words as $index => &$word) {
    			$word = strtolower($word);
    			if($index==0 && $initialCaps===FALSE) { continue; }
    			$word = ucwords($word);
    		}
    		return implode('',$words);
    	}
    	return FALSE; 				
    }
    }
    

     

    If I remove the string datatype requirement in the function before the function argument list, it works fine in CLi mode.

  9. Hello all, I was just reading the PHP manual and came across this example that doesn't work right for me. Anyone know why this is so? Tried looking through the manual for this but found nothing about it..

     

    $s = 'monkey';
    $t = 'many monkeys';
    
    printf("[%s]\n",      $s); // standard string output
    printf("[%10s]\n",    $s); // right-justification with spaces
    printf("[%-10s]\n",   $s); // left-justification with spaces
    printf("[%010s]\n",   $s); // zero-padding works on strings too
    printf("[%'#10s]\n",  $s); // use the custom padding character '#'
    printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters
    

     

    The above example will output:

     

    [monkey]

    [    monkey]

    [monkey    ]

    [0000monkey]

    [####monkey]

    [many monke]

     

     

     

     

     

    But when i tried this for myself, 

    printf("[%10s]\n",    $s);

    does not left pad the output as so : [    monkey].Instead it outputs [ monkey].

     

    But adding a 0 as so : 

    printf("[%010s]\n",    $s);

    , pads it with 4 0's, outputting :

    [0000monkey] . Is there some other way to make it pad spaces that i'm missing?

     

    Running PHP 5.3.2

     

  10. Hello,

     

    Not really a major issue, just something that's coming in the way here and there.

     

    Basically i created a user with ALL privileges only on user_% database and absolutely no GLOBAL privileges.

     

    The problem is that i'm able to execute the CREATE DATABASE command under that user but i'm not able to do a DROP DATABASE statement in phpMyAdmin (Gives me a javascript dialog box that says "DROP STATEMENTS are disabled!", and i'm not able to delete it from the phpMyAdmin GUI under the Databases tab (Checkbox to select is missing).It works without any issues if i do it in the Mysql console. I'm continuing to work on the Mysql, but now and then when i need to get into phpMyAdmin its annoying , not being able to do this.

     

    Mysql Version : 5.1.41-3ubuntu12.7

    phpMyAdmin Version : 3.3.2deb1

     

    Thanks in advance!

  11. Sorry didn't quite understand what you meant there. The code you provided just proves that you can change array values without writing the code as foreach ($array as $key => &$value).  Thats what my code proves aswell, but the question i meant to ask was, why does the manual say that the original array value needs to be referenced with a & in the foreach statement, when clearly we can change original array values without it. Thanks again, for the help.

  12. Hello, I've been stuck on this code for nearly 3 days and i still am not able to understand this too well.

     

    The PHP manual says "Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it."

     

    Right , so from what i understand from that,if i want to modify an array inside a foreach , i need to reference the array.

     

    This example was given in the PHP manual to demonstrate this reference requirement

     

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    // $arr is now array(2, 4, 6, 
    unset($value); // break the reference with the last element
    ?>
    

     

    But, when i try this code :

    <?php
    $array = array('Ibanez');
    foreach ($array as $guitar) {
    $array['guitar'] = $array[0];
    unset($array[0]);
    
    $array['guitar'] = 'Gibson';
    }
    print_r($array);
    ?>
    

     

    The output of the array outside the foreach shows the changed array and not the original anymore. So doesn't this mean that the foreach CAN indeed operate on the array itself without the array being referenced? The reason i'm stuck with this code is that i'm trying to use another slightly bigger array which needs to have its keys modified within the foreach statement, but the changes refuse to leave the foreach loop. But when i tested this small piece of code above, changes are indeed getting reflected without any reference. I'm really confused now about how this works. Help is greatly appreciated :)

  13. Hmmm i thought about that as one a the reasons right from the start, but when i put it to the test , the array variable outside the foreach loop reflected changes in it.

     

    $array = array('Apple','Watermelon');
    foreach ($array as $names) {
    $array['red'] = $array[0];
    unset($array[0]);
    $array['green'] = $array[1];
    unset($array[1]);
    break;
    }
    
    print_r($array);
    
    

     

    That code displays this as Array ( ['red'] => Apple ['green'] => Watermelon ).

    If the foreach makes a copy of the array for its use shouldn't i just be able to see the original array?

  14. Hello,

     

    I'm a new  building my career as a web developer/designer and i'm attempting to create an array that holds different attributes of all the web projects.

     

    Site1 => array('www.siteurl.com','hostAccountName','Offline domain name',) ,

    Site2 => array('www.site2url.com','hostAccoun2tName','Offline domain2 name') ,

    Site3 => array('www.site2url.com','hostAccount3Name','Offline domain3 name') ,

     

    I have many sites in the multidimensional array BUT each has the same format of attributes. I store this entire array in one file that gets included, and based on some logic later , the script will decide which site i'm currently working on and thus that site's attributes must be used, since i will just use one variable where these attributes are needed and leave it upto some logic to decide which site's attributes to use.

     

     

    Objective of the code : To change the array keys of each site's attributes from 0,1,2 etc to more readable strings for later use to directly access values. I'm creating an array with the values first and then running some code to change the keys later because i might decide to change the key names later and i can't manually edit it for each of the array values because the array might grow much larger.

     

    Site1 => array ([0] => 'www.siteurl.com',

                              [1] => 'username@hostserver',

                              [2] => 'siteOfflineDomain');

     

    must change into

     

    Site1 => array (['siteUrl] => 'www.siteurl.com',

                              ['hostingUserName'] => 'username@hostserver',

                              ['OfflineVirtualHost'] => 'siteOfflineDomain');

     

    And this must happen in a foreach loop and go through all the sites to change all the default 0,1,2 indices, to the index names i provide.

     

     

    Code :

    $siteList = array (
    		'site1'     => array
    					(
    						'www.site1.com',
    						'site1@host',
    						'site1_offline'
    				      ),
    				  
    		'site2' => array 
    					(
    						'www.site2.com',
    						'site2@host',
    						'site2_offline'
    
    					),
    
    		'site3'  => array
    					(
    						'www.site3.com',
    						'site3@host',
    						'uttarkar_offline'
    					)					  
    		);
    
    
    
    foreach ($siteList as $sitePrefix => $siteAttributes) {
    foreach ($siteAttributes as $oldIndex => $attribute) {
    	switch ($oldIndex) {
    		case 0 :
    			$siteAttributes['siteUrl'] = $siteAttributes[$oldIndex];
    			unset($siteAttributes[$oldIndex]);
    			break;
    		case 1 :
    			$siteAttributes['hostserverUserName'] = $siteAttributes[$oldIndex];
    			unset($siteAttributes[$oldIndex]);
    			break;
    		case 2 :
    			$siteAttributes['offlineDomainName'] = $siteAttributes[$oldIndex];
    			unset($siteAttributes[$oldIndex]);								
    			break;
    	}
    }
    
    echo 'The newly edited attributes array for ',$sitePrefix,'is '.print_r($siteAttributes),'<br><br>';
    }
    

     

    Problem : This script works great, and the indices for the attributes get changed as expected, as you will see in the echo statement. But if i do a echo $siteList['site1']['siteUrl'] after the code, it says 'unknown index siteUrl'. Then i check the entire array with print_r($siteList) , and all the index keys are back to being 0,1,2!. My guess is that theres something i'm missing here to make them stick, but i spent 3 hours trying to figure it out, and i was getting a bit impatient, so can i get some help on this one please :), thanks.

  15. It doesn't seem like you understand what the include/require functions actually do.  When you include a PHP file, basically what happens is PHP copies the contents of the file right into the script that's including them.  Include/require will ALWAYS succeed if the file is present, the only question you should have is whether or not the PHP inside the included file is valid.  This is something you have to ensure by writing good code in your include files, not by wrapping them in a validator.

     

    Include files shouldn't "return" anything to the parent file, because they're designed to operate as if the code is IN the parent file to begin with.

     

    -Dan

     

    yep yep, i get it now, all this while i mistook require/include for a function because of the () that it uses.

  16. @ManiacDan : I need the require to happen successfully or return an error. If i use file_exists, won't i need to use a require after that to include the file (bringing us back to check if the require will happen successfully).

     

    Ahh, i get it now , all this while echo include(filename); would always return 1, fooling me into thinking its the boolean return, when its actually the return value in filename. Adding a return false in the included file proved this for me. Thanks thorpe :D

  17. Hi sorry for the trouble guys but i'm really stuck on this one, and i've tried everything i can. (I've been using php only for sometime now)

     

    I'm stuck at this code and can't figure out why this is failing.

     

    Objective of the script :

    To try and include BOTH files or throw and exception if even one fails.

     

    I tried :

    Including just one at a time. Its fine, so i know the path is correct.

    I tried a if (! (expr1 && expr2) )  statement to check if the syntax is correct to create a everything or nothing logic.

     

    $offlineLibraryPath = '/var/www/common/lib';
    // Attempt to include the files
    try {
    if(!
        (	
        	require_once($offlineLibraryPath.'/variables/all.php') &&
        	require_once($offlineLibraryPath.'/functions/all.php')
        )
      ) 
         { throw new Exception ('Including all the common library files failed.'); }
    } catch (Exception $e) {
    echo '<b>Error</b> :'.$e->getMessage();
    }
    

     

    I get this error :

    Warning: require_once(1): failed to open stream: No such file or directory in /var/www/common/lib/startupIncludes.php on line 18 Fatal error: require_once(): Failed opening required '1' (include_path='/var/www/common/lib/: /var/www/culturesque/lib/: /var/www/mine/lib/') in /var/www/common/lib/startupIncludes.php on line 18

     

     

    Thanks in advance for the help!

×
×
  • 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.