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

Browsing "Older Posts"

PHP isset() equiv JavaScript isset() funciton:

Often I am get asked from junior developers that, Is there any isset() function in Javascript? Ha ha ha. I ignore them, but let them try to create a custom function to do this job.
Ok no more words...Let get it...
/**
 * 
 * @returns {Boolean}
 * Original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * Improved by: FremyCompany
 * Improved by: Onno Marsman
 * Improved by: Rafał Kukawski
 * Example-1: isset( undefined, true);
 * Returns: false
 * Example 2: isset( 'Kevin van Zonneveld' );
 * Returns: true
 */
function isset ()
{

  var a = arguments,
    l = a.length,
    i = 0,
    undef;

  if (l === 0)
  {
    throw new Error('Empty isset');
  }

  while (i !== l)
  {
    if (a[i] === undef || a[i] === null)
    {
      return false;
    }
    i++;
  }
  return true;
}
But........
The problem is this will raise an exception when calling isset(abc.def.ghi) in case if abc.defis undefined. However by combining this solution with the one that accepts a variable name in a form of a string, it will be identical to the PHP version

You can use this function as PHP isset() given to use.

var a;

a = {
    b: {
        c: 'e'
    }
};

function isset (obj, path) {
    var stone;

    path = path || '';

    if (path.indexOf('[') !== -1) {
        throw new Error('Unsupported object path notation.');
    }

    
    path = path.split('.');
    
    do {
        if (obj === undefined) {
            return false;
        }

        stone = path.shift();
        
        if (!obj.hasOwnProperty(stone)) {
            return false;
        }
        
        obj = obj[stone];
        
    } while (path.length);

    return true;
}

console.log(
    isset(a, 'b') == true,
    isset(a, 'b.c') == true,
    isset(a, 'b.c.d') == false,
    isset(a, 'b.c.d.e') == false,
    isset(a, 'b.c.d.e.f') == false
);

Another Way to do isset() function using javascript.

if(typeof(data.length) != 'undefined')
    {
       // do something
    }

    if(empty(data))
    {
        // do something
    }

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }

JavaScript isset() equivalent PHP isset()

By Game Changer → Thursday, December 17, 2015


From the terminal:
Hristo$ sudo /usr/local/mysql/support-files/mysql.server start
Starting MySQL
.....................................................................
ERROR! Manager of pid-file quit without updating file.
so I checked the status:
Hristo$ sudo /usr/local/mysql/support-files/mysql.server status
Password:
/usr/local/mysql/support-files/mysql.server: line 418: pidof: command not found
 ERROR! MySQL is not running
Again tried this?
Hristo$ /usr/local/mysql/bin/mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

mysql.err:
100706 11:38:36 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
100706 11:38:36 [Warning] '--log' is deprecated and will be removed in a future release. Please use ''--general_log'/'--general_log_file'' instead.
100706 11:38:36 [Warning] '--log_slow_queries' is deprecated and will be removed in a future release. Please use ''--slow_query_log'/'--slow_query_log_file'' instead.
100706 11:38:36 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql/data/ is case insensitive
100706 11:38:36 [Note] Plugin 'FEDERATED' is disabled.
100706 11:38:36  InnoDB: Started; log sequence number 0 69987
100706 11:38:36 [ERROR] Can't start server : Bind on unix socket: Permission denied
100706 11:38:36 [ERROR] Do you already have another mysqld server running on socket: /var/mysql/mysql.sock ?
100706 11:38:36 [ERROR] Aborting

100706 11:38:36  InnoDB: Starting shutdown...
100706 11:38:41  InnoDB: Shutdown completed; log sequence number 0 69987
100706 11:38:41 [Note] /usr/local/mysql/bin/mysqld: Shutdown complete


Solution:

Configure correctly your my.cnf file.
[mysqld]
#
# * Basic Settings
#

user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
skip-external-locking

#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 127.0.0.1

[Solved] MySQL Error on Snow Leopard

By Game Changer → Friday, December 11, 2015
PHP scripts to send the e-mail messages for contact form via SMTP. Already found several articles and PHPMailer tutorials? but a lot of them didn’t worked for you?

Why GMail for sending mail messages?

Obviously! it’s FREE! Sure most website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use GMail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day, check this information from the Google help pages.

Requirements

You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.

Trouble sending e-mails with your “normal” GMail account? If you own a domain name, you can register for a Google Apps account or check below the tutorial update about an alternative SMTP service!

PHPMailer tutorial for GMail and Google Apps

Check that your web hosting provider has opened the port 465 (TCP out), if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', 'you@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):
function smtpmailer($to, $from, $from_name, $subject, $body) { 
 global $error;
 $mail = new PHPMailer();  // create a new object
 $mail->IsSMTP(); // enable SMTP
 $mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
 $mail->SMTPAuth = true;  // authentication enabled
 $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
 $mail->Host = 'smtp.gmail.com';
 $mail->Port = 465; 
 $mail->Username = GUSER;  
 $mail->Password = GPWD;           
 $mail->SetFrom($from, $from_name);
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->AddAddress($to);
 if(!$mail->Send()) {
  $error = 'Mail error: '.$mail->ErrorInfo; 
  return false;
 } else {
  $error = 'Message sent!';
  return true;
 }
}
Most of the settings inside the function are required by GMail. While searching for PHPmailer tutorials I found articles with different settings for the port and security. My advice is to use the settings from this tutorial. Call the function within your code:
smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:
if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
 // do something
}
if (!empty($error)) echo $error;
Advanced setup with fall-back SMTP server Because of the e-mail message limit it might be useful to use a secondary SMTP server if the GMail option is unable to send the message. For this functionality you need to replace the part with the SMTP settings. First create login/server variables for the second SMTP server:
define('SMTPUSER', 'you@yoursmtp.com'); // sec. smtp username
define('SMTPPWD', 'password'); // sec. password
define('SMTPSERVER', 'smtp.yoursmtp.com'); // sec. smtp server
Next we need to create an if/else statement using the variables for the second server (replace).
function smtpmailer($to, $from, $from_name, $subject, $body, $is_gmail = true) { 
 global $error;
 $mail = new PHPMailer();
 $mail->IsSMTP();
 $mail->SMTPAuth = true; 
 if ($is_gmail) {
  $mail->SMTPSecure = 'ssl'; 
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = 465;  
  $mail->Username = GUSER;  
  $mail->Password = GPWD;   
 } else {
  $mail->Host = SMTPSERVER;
  $mail->Username = SMTPUSER;  
  $mail->Password = SMTPPWD;
 }        
 $mail->SetFrom($from, $from_name);
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->AddAddress($to);
 if(!$mail->Send()) {
  $error = 'Mail error: '.$mail->ErrorInfo;
  return false;
 } else {
  $error = 'Message sent!';
  return true;
 }
}
And next use the modified PHPMailer function as followed:
$msg = 'Hello World';
$subj = 'test mail message';
$to = 'to@mail.com';
$from = 'from@mail.com';
$name = 'yourName';
 
if (smtpmailer($to, $from, $name, $subj, $msg)) {
 echo 'Yippie, message send via Gmail';
} else {
 if (!smtpmailer($to, $from, $name, $subj, $msg, false)) {
  if (!empty($error)) echo $error;
 } else {
  echo 'Yep, the message is send (after doing some hard work)';
 }
}
Both examples are very simple and demonstrate only how-to send e-mail messages using PHPmailer with the SMTP server provided by GMail. Of course you can extend the code to handle HTML messages and attachments etc. If you have any issues with these examples, just let me know. UPDATE: Alternate SMTP service Since this tutorial was published, I got several messages that the free GMail account doesn’t allow you to send a lot of e-mail messages from your own websites. Your can use this PHPmailer example code for any other SMTP server or service. I suggest to use ElasticEmail, a premium e-mail service provider in the cloud. Signup for a free account which is good for the first 25.000 mail messages and 10.000 contacts every month. If you use the tutorial code with ElasticEmail you need to replace this part of code
 if ($is_gmail) {
  $mail->SMTPSecure = 'ssl'; 
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = 465;  
  $mail->Username = GUSER;  
  $mail->Password = GPWD;   
 } else {
  $mail->Host = SMTPSERVER;
  $mail->Username = SMTPUSER;  
  $mail->Password = SMTPPWD;
 } 
with this code
 $mail->Host = 'smtp.elasticemail.com';
 $mail->Port = 2525; 
 $mail->Username = 'your username';
 $mail->Password = 'your password';
Optional: Remove the “$is_gmail” attribute from the function.
Tags:

Sending e-mails using SMTP with PHPMailer and GMail

By Game Changer →

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 →
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



Choosing a database wrapper in you development project.

Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.

Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.
PDO is the standard, it's what most developers will expect to use. mysqli was essentially a bespoke solution to a particular problem, but it has all the problems of the other DBMS-specific libraries. PDO is where all the hard work and clever thinking will go.

Here are the results of the tests. Lower values are better, of course.

PDO results for 0.1M SQL queries

Query Time in seconds
insert 15.23874929331
select 18.29382394421
update 14.93284923728
delete 17.92102038303
MySQLi results for 100k queries

Query Time in seconds
insert 21.98739839490
select 26.01564064026
update 27.35169916153
delete 21.15891308745

PDO results for 1M queries
Query Time in seconds
insert 139.2347803431
select 207.1249543506
update 151.2345734537
delete 141.3245435434
MySQLi results for 1M queries

Query Time in seconds
insert 204.2342353454
select 291.4354655432
update 221.0213423434
delete 231.1456456456

PDOMySQLi
Database support12 different driversMySQL only
APIOOPOOP + procedural
ConnectionEasyEasy
Named parametersYesNo
Object mappingYesYes
Prepared statements 
(client side)
YesNo
PerformanceFastFast
Stored proceduresYesYes
This is another important feature that PDO has; binding parameters is considerably easier than using the numeric binding:
$params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);
     
$pdo->prepare('
    SELECT * FROM users
    WHERE username = :username
    AND email = :email
    AND last_login > :last_login');
     
$pdo->execute($params);
...opposed to the MySQLi way:
The question mark parameter binding might seem shorter, but it isn't nearly as flexible as named parameters, due to the fact that the developer must always keep track of the parameter order; it feels "hacky" in some circumstances.
Unfortunately, MySQLi doesn't support named parameters.

MySQLi vs PHP Object Mapping


Both PDO and MySQLi can map results to objects. This comes in handy if you don't want to use a custom database abstraction layer, but still want ORM-like behavior. Let's imagine that we have a User class with some properties, which match field names from a database.

class User {
    public $id;
    public $first_name;
    public $last_name;
     
    public function info()
    {
        return '#'.$this->id.': '.$this->first_name.' '.$this->last_name;
    }
} 

API Case:

Both offer an object-oriented API, but MySQLi also offers a procedural API - which makes it easier for newcomers to understand. If you are familiar with the native PHP MySQL driver, you will find migration to the procedural MySQLi interface much easier. On the other hand, once you master PDO, you can use it with any database you desire!

Summery:

After the whole reviewing, PDO wins this battle with ease. With support for twelve different database drivers (eighteen different databases!) and named parameters. We can ignore the small performance loss, and get used to its API. Also from a security point.

PDO or MySqli: The pros and cons

By Game Changer → Tuesday, December 8, 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

Do you need call a dynamic function?

Defined in your script.. Need Calling Dynamically?

Use call_user_func() instead:
//for normal function 
call_user_func($myVar);
// if hello() is in the current namespace
call_user_func(__NAMESPACE__.'\\'.$myVar);

// if hello() is in another namespace
call_user_func('mynamespace\\'.$myVar);

Dynamic function names and namespaces

Just to add a point about dynamic function names when using namespaces.
If you're using namespaces, the following won't work except if your function is in the global namespace:
namespace greetings;
function hello()
{
    // do something
}

$myvar = "hello";
$myvar(); // interpreted as "\hello();"


Dynamic Writing?

Following code can help to write dynamic function in PHP. now the function name can be dynamically change by variable '$current_page'.
$current_page = 'home_page';
$function = @${$current_page . '_page_versions'};
$function = function() {
    echo 'current page';
};
$function();

Call PHP function from string stored in a Variable

By Game Changer → Sunday, December 6, 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 →


Differences in ASCII:

URLENCODE:
  • Calculates a start/end length of the input string, allocates memory
  • Walks through a while-loop, increments until we reach the end of the string
  • Grabs the present character
  • If the character is equal to ASCII Char 0x20 (ie, a "space"), add a + sign to the output string.
  • If it's not a space, and it's also not alphanumeric (isalnum(c)), and also isn't and _-, or .character, then we , output a % sign to array position 0, do an array look up to the hexcharsarray for a lookup for os_toascii array (an array from Apache that translates char to hex code) for the key of c (the present character), we then bitwise shift right by 4, assign that value to the character 1, and to position 2 we assign the same lookup, except we preform a logical and to see if the value is 15 (0xF), and return a 1 in that case, or a 0 otherwise. At the end, you'll end up with something encoded.
  • If it ends up it's not a space, it's alphanumeric or one of the _-. chars, it outputs exactly what it is.
RAWURLENCODE:
  • Allocates memory for the string
  • Iterates over it based on length provided in function call (not calculated in function as with URLENCODE).
Note: Many programmers have probably never seen a for loop iterate this way, it's somewhat hackish and not the standard convention used with most for-loops, pay attention, it assigns x and y, checks for exit on len reaching 0, and increments both x and y. I know, it's not what you'd expect, but it's valid code.
  • Assigns the present character to a matching character position in str.
  • It checks if the present character is alphanumeric, or one of the _-. chars, and if it isn't, we do almost the same assignment as with URLENCODE where it preforms lookups, however, we increment differently, using y++ rather than to[1], this is because the strings are being built in different ways, but reach the same goal at the end anyway.
  • When the loop's done and the length's gone, It actually terminates the string, assigning the \0byte.
  • It returns the encoded string.
Differences:
  • UrlEncode checks for space, assigns a + sign, RawURLEncode does not.
  • UrlEncode does not assign a \0 byte to the string, RawUrlEncode does (this may be a moot point)
  • They iterate differntly, one may be prone to overflow with malformed strings, I'm merely suggesting this and I haven't actually investigated.
They basically iterate differently, one assigns a + sign in the event of ASCII 20.

Differences in EBCDIC:

URLENCODE:
  • Same iteration setup as with ASCII
  • Still translating the "space" character to a + sign. Note-- I think this needs to be compiled in EBCDIC or you'll end up with a bug? Can someone edit and confirm this?
  • It checks if the present char is a char before 0, with the exception of being a . or -OR less than A but greater than char 9OR greater than Z and less than a but not a _OR greater than z (yeah, EBCDIC is kinda messed up to work with). If it matches any of those, do a similar lookup as found in the ASCII version (it just doesn't require a lookup in os_toascii).
RAWURLENCODE:
  • Same iteration setup as with ASCII
  • Same check as described in the EBCDIC version of URL Encode, with the exception that if it's greater than z, it excludes ~ from the URL encode.
  • Same assignment as the ASCII RawUrlEncode
  • Still appending the \0 byte to the string before return.

Grand Summary

  • Both use the same hexchars lookup table
  • URIEncode doesn't terminate a string with \0, raw does.
  • If you're working in EBCDIC I'd suggest using RawUrlEncode, as it manages the ~ that UrlEncode does not (this is a reported issue). It's worth noting that ASCII and EBCDIC 0x20 are both spaces.
  • They iterate differently, one may be faster, one may be prone to memory or string based exploits.
  • URIEncode makes a space into +, RawUrlEncode makes a space into %20 via array lookups.
Disclaimer: I haven't touched C in years, and I haven't looked at EBCDIC in a really really long time. If I'm wrong somewhere, let me know.

URLENCODE vs RAWURLENCODE

By Game Changer →