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

Browsing "Older Posts"

Browsing Category "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

Date and time manipulation is an unavoidable part of programming; there will inevitably be a part of a project that requires a date to be modified. While, on the surface, echoing a date in the future brings a small bit of accomplishment, it can be quickly eradicated when one is tasked with manipulating that date.
Without being aware of the arsenal of tools PHP provides you with regards to working with dates, you might find yourself writing kludges that convert strings into timestamps for various comparisons.
Today we’re going to dissect the PHP DateInterval class, a power tool for dealing with dates in a web app.
But before learning about the DateInterval object, one needs to first understand what an interval is.

What is an Interval?

Simply put, an interval is a duration of time.
When we converse about the topic of duration, we wouldn’t say, "Honey, I’ll be home on Dec 3rd, 2015 15:19pm".
Instead, we would simplify and say "I’ll be home in 5 minutes". Although this is ideal when conversing with another person, this is not so great as a data construct.
So how do we define "in 5 minutes" for a web app?
Fortunately, there’s an ISO for that.
ISO 8601 is the international standard that defines how to use, store, and transfer date, time, and duration information.
The specific string to define durations is an easy-to-remember pattern:
PYMDTHMS
  • P: period
  • Y: years
  • M: months
  • D: days
  • T: time
  • H: hours
  • M: minutes
  • S: seconds
Except for P, each designator is optional.
Immediately preceding each designator is the quantity of time you want to store.
Below is a table showing samples of different date and time ranges:
StringEquivalent to…
P1Y1 year
P1M1 month
P1D1 day
P30D30 days
PT1H1 hour
PT5M5 minutes
PT35S35 seconds
P1Y6M29DT4H34M23S1 year, 6 months, 29 days, 4 hours, 34 minutes, 23 seconds

Creating a DateInterval Object

Now that we understand what an interval is — it’s simply a duration of time — and that ISO 8601 defines our duration’s format, we can start playing around with the PHP DateInterval class.
Let’s define a predictable duration, create a DateInterval object, and output the result to the screen.
We’ll start with "1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds".
$Duration = new DateInterval( "P1Y2M3DT4H5M6S" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 1
[m] => 2
[d] => 3
[h] => 4
[i] => 5
[s] => 6
...
)
You will notice that the constructor for the DateInterval class has parsed your duration and stored the individual values in its own properties. $Duration->ymatches the 1Y from the duration string you passed in.
Let’s try another more practical duration: 1 month. You’ll notice that any undefined durations are automatically defaulted to 0.
$Duration = new DateInterval( "P1M" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 0
[h] => 0
[i] => 0
[s] => 0
...
)
So now we know what’s happening, but what do we really have? What’s so great and tangible about this?
The real benefit to what we have here is that the $Duration object itself represents a duration of time. We don’t need to know a source or destination date; $Duration is simply 1 month.
Note: It’s important to note that creating a DateInterval with 13 months (P13M) will not roll over and provide you with "1 year 1 month".
That makes sense because we don’t have a source or destination date. Imagine the case of 61 days:
  • On October 1, it’s 2 months
  • On December 1, it’s only 1 month and 30 days
  • On February 1, it’s 2 months and 2 days (or only 2 months and 1 day on leap years)

Manipulating Dates with Durations

Durations tame the manipulation of PHP DateTime objects.
The PHP DateTime class has three methods that work with a DateIntervalobject:
  • add
  • sub
  • diff
Both add and sub will modify a DateTime object by a DateInterval, while diffwill compare two DateTime objects and return a DateInterval.
$Now = new DateTime();
echo $Now->format('Y-m-d'); // 2014-06-12

$Duration = new DateInterval('P1M'); // 1 month
$Now->add( $Duration );
echo $Now->format('Y-m-d'); // 2014-07-12

$Duration = new DateInterval('P2M'); // 2 months
$Now->sub( $Duration );
echo $Now->format('Y-m-d'); // 2014-05-12
In the above example you can see how date manipulation becomes much easier and more predictable by using DateInterval objects to modify DateTime objects.
The diff method is just as easy to use, but provides an extra piece of information:total days. This is important because when using the DateTime object to find a difference, we have a source and destination date, and therefore we can reduce the units of time into larger denominations. However, having the total number of days in between is a valuable piece of information.
$Year = new DateInterval('P1Y');
echo $Year->days; // 0

$Date1 = new DateTime();
$Date2 = new DateTime();
$Date2->add( $Year );

$Difference = $Date1->diff( $Date2 );
echo $Difference->days; // 365

Reading Durations and Extracting Intervals

There are inevitably going to be times where you want to extract portions of the stored interval (much the same as you would a date).
The DateInterval class has a handy format method. PHP docs has a table for the format method that is a useful reference.
You use the format method like this:
$Duration = new DateInterval('P345D');
echo $Duration->format('I am %d days'); // I am 345 days
Note: It’s important to note, for those familiar with the strftime method, that the recognized characters are completely different. For example, theDateInterval::format method interprets %a as total days while strftimeinterprets it as a textual representation of the day (i.e. "Sun").
Oddly enough, DateInterval doesn’t natively have a way to extract the entire interval spec without the zero values. This leaves you with two options:
  1. Extract it with 0 elements, which is perfectly acceptable
  2. Extend the DateInterval class
The second option, extending the DateInterval class, brings upon it’s own difficulties that we won’t touch on here today.
To extract the interval spec with the 0 elements intact, you can use the same format method like so:
$Duration = new DateInterval('P345D');
echo $Duration->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
If you want to confirm the above, simply create a new DateInterval with the result of the first:
$interval_spec = 'P345D';
$Duration1 = new DateInterval( $interval_spec );
echo $Duration1->format('%d'); // 345

$interval_spec = $Duration1->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
$Duration2 = new DateInterval( $interval_spec );
echo $Duration2->format('%d'); // 345
You should now have a grasp on using the PHP DateInterval class, and it’s capabilities.
Hopefully you’re able to apply this current and future web app projects.

PHP DateInterval Class

By Game Changer → Friday, December 11, 2015


Finally You have fethed the error. Is it?

Warning: fopen(/path/to/file.ext) [function.fopen]: failed to open stream: Permission denied

NOTE: You are opening a file. Make sure the correct file permissions you have.

In Ubuntu the php user group is www-data:www-data and for centos is apache:apache
- Ensure your user www-data is a member of root
adduser www-data root
Then use this command in terminal
chmod g+rw /path/to/file/

Try with php fopen again:

$myFilePath = "/path/to/file.ext";
$file_handle = fopen( $myFilePath, 'r+' );
Also! You can chmod 775 for you directory.
chmod 0775 /path/to/file/

Check the followings:

  • The directory has the correct file permissions (755) and the correct ownership. This is true all the way up the path to /home.
  • Ensure correct directory as confirmed by getcwd()
  • The test PHP script hash the same ownership as the path trying to write to and correct permission (644).
  • PHP safe mode is disabled in php.ini.
  • fopen is not a disallowed PHP function.
  • The use of open_basedir is disabled.
  • A parent directory has the wrong permissons.

Yet Not?

Remember that in order to reach a file, ALL parent directories must be readable by www-data. You strace output seems to indicate that even accessing /var/log/apache2/writetest is failing. Make sure that www-data has permissions on the following directories:
  • / (r-x)
  • /var (r-x)
  • /var/log (r-x)
  • /var/log/apache2 (r-x)
  • /var/log/apache2/writetest (rwx)
  • /var/log/apache2/writetest/writetest.log (rw-)

Yet Not Again?

Could be a SELinux issue, even if Debian doesn't ship it in the default installation your provider could have enabled it. Look for messages in /var/log with
grep -i selinux /var/log/{syslog,messages}
If that's the cause and you need to disable it, here are instructions: look for file /etc/selinux/config, here it's default content. Change SELINUX directive to disabled and reboot the system.
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#   enforcing - SELinux security policy is enforced.
#   permissive - SELinux prints warnings instead of enforcing.
#   disabled - SELinux is fully disabled.
SELINUX=disabled
# SELINUXTYPE= type of policy in use. Possible values are:
#   targeted - Only targeted network daemons are protected.
#   strict - Full SELinux protection.
SELINUXTYPE=targeted

[Solved] PHP fopen() Error: failed to open stream: Permission denied

By Game Changer → Monday, December 7, 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
Actually it is impossible to answer and has been brought up many many times before. It depends on whether you prefer a dynamic scripting language or a strongly-typed modular language. I'd suggest you start with PHP though as then you don't have to deal with more advanced Asp.net concepts like events, controls, viewstate, class libraries, e
tc. You can pick those things up easy enough once you've got to grips with the syntax and programming for the web.
ASP and PHP are similar in that both tend to put their code in with the HTML, and so the logic can be quite similar.
But, ASP.NET will be very different from PHP in design, as there is a strong incentive to use code-behind in ASP.NET, where you basically have the html template and all the code is in another separate file
Depending on what you are doing, how busy your site is, you may find that the speed difference is inconsequential, though one is compiled and the other isn't.
PHP is probably going to be faster to develop, as you can more easily code a little and test, than you can with ASP.NET, but ASP and PHP are similar in how you can develop.
If you don't know any of these languages then PHP may be the easier one to learn, as the php manual is so well written, with lots of comments from users, and ASP.NET has replaced ASP, so learning ASP for a new project, IMO, is of limited use.
If you go with ASP.NET then you are learning a new syntax and one of the .NET languages, but depending on your background, C# may be relatively easy to learn.
With ASP or ASP.NET you are stuck with using IIS for your server, but with PHP you can use IIS or Apache, so there is considerable flexibility there.
With ASP.NET you will find more options to help with code development, as they now have the classic ASP.NET and ASP.NET MVC (http://www.asp.net/%28S%28d35rmemuuono1wvm1gsp2n45%29%29/mvc/), both with pros and cons, but I believe this site is still written in the latter.
So, which would be better depends on what you are going to be doing with it, and what languages or frameworks you have already gained experience with.

ASP.net is quite cheap - you can use free ide like visual studio web developer express edition - the only thing you lose is things like source control and some other features available from professional edition onwards.
ASP.NET can do threads, while PHP cannot. Honestly that's about it. Someone will come and nit-pick about some other complicated task that PHP can't do, but PHP is a pretty robust and dynamic language overall.
If you are starting now and have never done C# or VB development, I would do PHP instead. It's much easier to pick up and has far fewer rules compared to C#. Yes, it can lead to bad coding practices because it is so loose and open. However, the documentation is phenomenal and you'll be moving much more quickly than you would in ASP.NET with no C# or VB experience.
Frankly speaking, once you are into professional development, the benefit of going for VS professional edition far outweighs the costs associated with it.
Apart from the tooling costs you have to consider the following costs and benefits
  1. Windows server - though you can run this on mono, I rarely see people choosing ASP.net for the specific case of running on mono. Windows server and IIS is a far better option to run ASP.net and the cost is justified due to easier management of Windows
  2. Cost of training - this is only if your current team is not trained in ASP.net
  3. Cost of development - here you actually stand to gain a little because the tooling for .net platform is by far the best. You will see productivity of even average developers improve a lot and good developers too can benefit from all kinds of features. Debugging capabilities, advanced intellisense, and overall better integration with other tools like VSTS make this a worthwhile investment.
  4. SQL Server - in case you decide to go for the paid editions, then there is a cost associated - again its not necessary, for most applications, an express edition might be quite sufficient. I must say that there are many features I have gotten used to in SQL server that are not present in MySQL and Postgresql. Merge replication is one of them, but there are others as well. Do your own research to see if the cost is worthwhile for your application.
PHP will run on essentially any server, for free. That's a fairly compelling feature for many folks.
There are lots of pros and cons of both, and it certainly doesn't boil down to scripting vs. compiled (incidentally, opcode caches like APC and things like Facebook's HipHop even the score on that point).
I'd say if someone's recommending PHP over ASP.NET, they code primarily in PHP. If they're recommending ASP.NET over PHP, they code primarily in ASP.NET. There's probably not much more to it than that in the responses you're getting.

ASP and PHP are similar in that both tend to put their code in with the HTML, and so the logic can be quite similar.
But, ASP.NET will be very different from PHP in design, as there is a strong incentive to use code-behind in ASP.NET, where you basically have the html template and all the code is in another separate file
Depending on what you are doing, how busy your site is, you may find that the speed difference is inconsequential, though one is compiled and the other isn't.
PHP is probably going to be faster to develop, as you can more easily code a little and test, than you can with ASP.NET, but ASP and PHP are similar in how you can develop.
If you don't know any of these languages then PHP may be the easier one to learn, as the php manual is so well written, with lots of comments from users, and ASP.NET has replaced ASP, so learning ASP for a new project, IMO, is of limited use.
If you go with ASP.NET then you are learning a new syntax and one of the .NET languages, but depending on your background, C# may be relatively easy to learn.
With ASP or ASP.NET you are stuck with using IIS for your server, but with PHP you can use IIS or Apache, so there is considerable flexibility there.
With ASP.NET you will find more options to help with code development, as they now have the classic ASP.NET and ASP.NET MVC (http://www.asp.net/%28S%28d35rmemuuono1wvm1gsp2n45%29%29/mvc/), both with pros and cons, but I believe this site is still written in the latter.
So, which would be better depends on what you are going to be doing with it, and what languages or frameworks you have already gained experience with.

ASP.NET OR PHP?

By Game Changer →