Sep 9, 2011

More PHP in this blog lately

Recently I work too much with PHP so naturally this blog will go in this direction. I’m trying to be short and at the point, with small but useful snippets of code. I hope that they will help you in some way.
I can’t write long and meaningless chunks of text and when I read developers books I tend to read only the code. In very rare occasions I read some other explanations - they are good when you talk about methodology or algorithm but examples are best when you talk about basics. Actually, this is just an excuse. The main reasons for more code than text in this blog is that I can’t write text.

How to make tar and tar.gz archives with PHP

This question is somewhat painful for me. Maybe I am too stupid. Anyway, if you want to make tar archive without using exec, for example on Windows machine without tar tool or any other stupid reason, here is how to do it with PHP. Its actually very easy if you know how to do it.

For example lets have a directory called dir and we want to make an archive with its content. The solution for our problem is Phar.

Here is the code that do the job:

<?php

// we want to archive all files from this directory
$dir = "dir/";

// the name of our new tar
$phar = new Phar("ourarchive.phar.tar");

// build from our dir
$phar->buildFromDirectory($dir);

// we are using gzip comppression
$phar->compress(Phar::GZ);

?>
Look carefully at the name of our archive - the parameter that we give when we create Phar object. It ends with phar.tar. If you use only .tar it will return error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'Cannot create phar 'ourarchive.tar', file extension (or combination) not recognised
This is not fun if you are trying to create tar and you receive this message. So using file name that ends with phar.tar will fix the problem.

If you receive error:
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Unable to add newly converted phar "/www/pro/ourarchive.phar.tar" to the list of phars, a phar with that name already exists'
most likely your tar file already exist.

Learn here how to make Zip archives with PHP

How to make Zip archives with PHP - part 1

Actually working with zip archives isn’t that obvious that it looks from the documentation. But if you want an adventure try to make tar or tar.gz. Actually in one of my next posts I will describe the procedure. Now, we are talking about zip here.

Example: Create archive and add file to it
<?php
 // the file that we want to compress
 $file = "path/filetocompress.txt";

 
 // how we want to name the file in the archive
 $name = "filename.txt";
 
 // we need to create new object
 $zip = new ZipArchive();

 
 // we are using ZipArchive::open with flag CREATE to make new zip archive
 if ($zip->open("ournew.zip", ZipArchive::CREATE) === TRUE) {

  
  // here the first parameter is the file on our system
  // the second is the name to be used for this file in our new zip 
     $zip->addFile($file, $name);

     
     // close is used for both close and save
     $zip->close();
 } else {

     echo 'Error';
 }
?>

Fast PHP example - FTP file upload

Here is one fast and simple example on how to do FTP file uploads with PHP.
<?php

$ftp_server = "ftp.server.url";

$ftp_user = "user";
$ftp_password = "password";

$file_to_upload = "localfile.txt";
$remote_location = "/location/file.txt";

// set up connection or exit with message
$flink = ftp_connect($ftp_server) or exit("Can't connect to ftp server: $ftp_server");

// login or at least try  
if(ftp_login($flink, $ftp_user, $ftp_password)) {

 
 // if login successful use ftp_put to upload the file
 // if you upload binary files use mode FTP_BINARY
 if(ftp_put($flink, $remote_location, $file_to_upload, FTP_ASCII)) {

  echo "Success! File is uploaded!";
 } else {
  echo "Can't upload file";

 }
} else {
 echo "Can't login with this user & password";

}

// close the connection
ftp_close($flink);

?>
You can get more information at http://www.php.net/manual/en/ref.ftp.php

Aug 19, 2011

PHP : Handling file uploads - easy tutorial with example

Handling file uploads with PHP is very easy task and here you will learn how to do it. And because I believe that people learn best with examples lets start with this.
Now lets upload one file to some user directory on a server. Lets create file upload_form.php on our server. It will contain mainly html code:

upload_form.php
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">

    File: <input name="ourfile" type="file" />
    <button type="submit">Upload</button>

</form>
</body>
</html>

Its very simple file with only one form. Don’t forget to add enctype="multipart/form-data" to your form when its used for file uploads. In this form we have to fields - the first is our file and the second is the submit button.
Now we need another file upload.php. Here is its content

upload.php
<?php
$dir = '/var/www/files/';

$destinationfile = $dir . basename($_FILES['ourfile']['name']);

if (move_uploaded_file($_FILES['ourfile']['tmp_name'], $destinationfile)) {

   echo "Upload successful!";
} else {
   echo "File attack!\n";

}
?>

Here we have destination directory for our uploads - $dir = '/var/www/files/'. Our file will be saved in this directory and will have the name of the uploaded file.
The function move_uploaded_file checks if the file (first parameter) is a valid uploaded file and if its valid it moves it to $destinationfile. If you just want to check the file without moving it use is_uploaded_file instead.
And that’s all. Now if you have done everything the right way you must see “Upload successful!” when you use upload_file.php and upload file.

The original of this tutorial is here http://ldeveloper.blogspot.com/2011/08/php-and-handling-file-uploads-easy.html

Aug 16, 2011

PHP: Playing with StdClass

What is StdClass and where does it live?

StdClass is a document class in PHP with no predefined members. Its the class that is created when you cast something to object like this:

$obj = (object) $something;

Sounds good but how to get its members if we don’t know about them? Actually, its very easy and we have several approaches.

First, we can iterate through its members with foreach:
foreach ($obj as $key => $value) {
   
}
Second we can cast our object to array:

$array = (array) $obj;

Or get its members as array:

get_object_vars($obj);

What else we can do with StdClass?
We can create objects and assign members:
$std = new StdClass();
$std->key = "value";
and access them:
echo $std->key;
If you see an error like this:
Catchable fatal error: Object of class stdClass could not be converted to string
the culprit is our stdClass of course. Maybe you are trying to print an object of this class.

Read how to use SOAP with PHP

Aug 11, 2011

How to use SOAP with PHP - very simple tutorial and example

Using SOAP with PHP can be very easy if you do everything right. First your PHP must be configured with --enable-soap. With Windows and WAMP you only need to check PHP > PHP extensions -> php_soap. You can read more about the configuration here http://www.php.net/manual/en/soap.configuration.php but most likely you don’t need to do anything else.

$client = new SoapClient("http://localhost/SomeSoap.wsdl");
$something = $client->SomeFunction();
var_dump($something);

And that’s all.
If you get Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in the row of
$something = $client->SomeFunction();
your problem may be in your soap configuration or something like this.

How to stop Skype from using port 80

Its very annoying when you want to use port 80 with apache for example and you must stop Skype, start the service and start Skype again.
Also its annoying when you install WAMP Server and its not working or at least apache is not working because Skype is on port 80 and you’ve totally forgotten about it. If you are little absent minded like me, you may spend even few hours looking for the problem and installing WAMP again.

Open Skype, select Tools from the menu, then Options, go to Advanced Settings and then Connection. There is a checkbox with the text
Use port 80 and 443 as alternatives for incoming connections
Uncheck it and hit Save. That’s it. You may need to restart Skype for the changes to take effect. I hope that this will help you.

PHP - Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in …

I receive this nasty error yesterday and it took me some time to figure out the problem. This line passes without any problems

$client = new SoapClient($url);

and this

var_dump($client->__getFunctions());

shows the function prototypes correctly. So it connects and gets the data but when I try to call a function I receive this error

Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in MyFile.php:23 Stack trace: #0 [internal function]: SoapClient->__doRequest('__call('myFunction', Array) #2 …

I made fast research and found that people receive this error when their php installation isn’t right or because they are trying to use it with https without the openSSL extension. So you can receive this problem with various situations. Anyway my code was right so I took a look at the service description that I received from the server and there was the problem. The server wasn’t configured right

<service name='myService'>
 ...
  <soap:address location='http://some_other_url'/>
 ..
</service>

It was configured to send invalid url and the function calls were using that invalid url. So there are two solutions - one correct and one that is almost correct but it works for testing purposes when you wait for people to fix their server. So the first is to configure the server correctly. The other is to give __doReguest the correct location.
I hope this will help somebody because founding the problem was very frustrating for me.

Popular Posts