DevSael Blog. C, CPP, C++, PHP, .NET Programming BLOG! advanced, MySQL, MongoDB, RDBMS.

Browsing "Older Posts"

Browsing Category "novice coding"


Q. PHP Session variable value is not transfering?

So, you are having trouble with php session variables! Well, Let see how can it being solved! If you didn't read about PHP Session variables then have a look on the manual!

Well let see what is happening...

PHP file: <test1.php>

<?PHP
session_start();

header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json; charset=UTF-8");

//some code to determine $approvedToSet
$approvedToSet = true;
if(isset($approvedToSet))
{
$_SESSION["userName"] = 'MyName'; 
echo " Session variable is set." .$_SESSION["userName"];
} 
else { 
echo "User name is not set";} 

?>

PHP file: <test2.php>

<?PHP
echo $_SESSION["userName"];

ERROR:

Notice: Undefined index: userName in /var/www/xyz on line 30


[Solution:]

Correct Your file and ensure session_start(); function is on the top of your page.

PHP file: <test2.php>

<?PHP
session_start()
echo $_SESSION["userName"]; ?>

  1. Stop your apache2 or http server and start it again!
  2. Ensure session.save_path has been set.
  3. Must be Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?phptag.
  4. After the header redirect, end the current script using exit(); (Others have also suggestedsession_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
  5. Make sure cookies are enabled in the browser you are using to test it on.
  6. Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
  7. Make sure you didn't delete or empty the session.
  8. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
  9. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  10. Make sure your file extension is .php (it happens!).
  11. If you use a connection script, dont forget to use start_session(); at the connection too, had some trouble before noticing that issue.
iu

[SOLVED] PHP Session variable value doesn't retrieved to another page

By Game Changer → Friday, May 5, 2017
We have two PHP5 objects and would like to merge the content of one into the second. There are no notion of subclasses between them so the solutions described in the following topic cannot apply.

Remarks:

  • Remember these are objects, not classes.
  • Objects will contain quite a lot of fields so a ``foreach`` would be quite slow.
  • So far we consider transforming objects A and B into arrays then merging them using array_merge() before re-transforming into an object but we can't say we are proud if this.
If your objects only contain fields (no methods), this works:
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)

Another Way:

foreach($objectA as $k => $v) $objectB->$k = $v;

  • Specify reference or clone
  • Specify first or last entry to take precedence
  • Multiple (more than two) object merging with syntax similarity to array_merge
  • Method linking: $obj->f1()->f2()->f3()...
  • Dynamic composites: $obj->merge(...) /* work here */ $obj->merge(...)
class Compositor {

    protected $composite = array();
    protected $use_reference;
    protected $first_precedence;

    /**
     * __construct, Constructor
     *
     * Used to set options.
     *
     * @param bool $use_reference whether to use a reference (TRUE) or to copy the object (FALSE) [default]
     * @param bool $first_precedence whether the first entry takes precedence (TRUE) or last entry takes precedence (FALSE) [default]
     */
    public function __construct($use_reference = FALSE, $first_precedence = FALSE) {
        // Use a reference
        $this->use_reference = $use_reference === TRUE ? TRUE : FALSE;
        $this->first_precedence = $first_precedence === TRUE ? TRUE : FALSE;

    }

    /**
     * Merge, used to merge multiple objects stored in an array
     *
     * This is used to *start* the merge or to merge an array of objects.
     * It is not needed to start the merge, but visually is nice.
     *
     * @param object[]|object $objects array of objects to merge or a single object
     * @return object the instance to enable linking
     */

    public function & merge() {
        $objects = func_get_args();
        // Each object
        foreach($objects as &$object) $this->with($object);
        // Garbage collection
        unset($object);

        // Return $this instance
        return $this;
    }

    /**
     * With, used to merge a singluar object
     *
     * Used to add an object to the composition
     *
     * @param object $object an object to merge
     * @return object the instance to enable linking
     */
    public function & with(&$object) {
        // An object
        if(is_object($object)) {
            // Reference
            if($this->use_reference) {
                if($this->first_precedence) array_push($this->composite, $object);
                else array_unshift($this->composite, $object);
            }
            // Clone
            else {
                if($this->first_precedence) array_push($this->composite, clone $object);
                else array_unshift($this->composite, clone $object);
            }
        }

        // Return $this instance
        return $this;
    }

    /**
     * __get, retrieves the psudo merged object
     *
     * @param string $name name of the variable in the object
     * @return mixed returns a reference to the requested variable
     *
     */
    public function & __get($name) {
        $return = NULL;
        foreach($this->composite as &$object) {
            if(isset($object->$name)) {
                $return =& $object->$name;
                break;
            }
        }
        // Garbage collection
        unset($object);

        return $return;
    }
}

Usage:

$obj = new Compositor(use_reference, first_precedence);
$obj->merge([object $object [, object $object [, object $...]]]);
$obj->with([object $object]);

Example:

$obj1 = new stdClass();
$obj1->a = 'obj1:a';
$obj1->b = 'obj1:b';
$obj1->c = 'obj1:c';

$obj2 = new stdClass();
$obj2->a = 'obj2:a';
$obj2->b = 'obj2:b';
$obj2->d = 'obj2:d';

$obj3 = new Compositor();
$obj3->merge($obj1, $obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj2:a, obj2:b, obj1:c, obj2:d
$obj1->c;

$obj3 = new Compositor(TRUE);
$obj3->merge($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, obj1:c, obj2:d
$obj1->c = 'obj1:c';

$obj3 = new Compositor(FALSE, TRUE);
$obj3->with($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, #obj1:c, obj2:d
$obj1->c = 'obj1:c';

The best method to merge PHP objects

By Game Changer → Wednesday, December 9, 2015

Both kinds of enclosed characters are strings. One type of quote is conveniently used to enclose the other type of quote. "'" and '"'. The biggest difference between the types of quotes is that enclosed identifier references are substituted for inside double quotes, but not inside single quotes.


Single quoted

The simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.
Example:
echo 'Start with a simple string';
echo 'String\'s apostrophe';
echo 'String with a php variable'.$name;

Double quoted

Use double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces{} to include variables if you do not want to use concatenation (.) operator) in string.
Example:
echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";

Is there a performance benefit single quote vs double quote in PHP?

Yes. It is slightly faster to use single quotes.
PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there is any variables in there.


But Remember: PHP strings can be specified not just in two ways, but in four ways.
  1. Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. Only exception is to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\
  2. Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you what to echo "The $types are" That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.
  3. Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.
  4. Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'No parsing is done in nowdoc.

Single-quoted and double-quoted strings in PHP, finding difference

By Game Changer → Saturday, December 5, 2015
PHP accepts request. Sometimes we work with string that should clean. Novice coder often having trouble with it. think you have got a string like that.

Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D

(?) Do you need to get a clean output like that:
Adaptasi morfologi adalah penyesuaian... =&onLoad=[type Function]

[Solution]

Use urldecode() function:

<?PHP
$string = "Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D";
//$string = $_GET['variable'];
$rString = urldecode($string);
echo $rString;

PHP Remove % from string in URL

By Game Changer →