PHP save image from url

Download Source Code

You can save image from url in PHP you should first get thesource of the image from the url  and after that save image to your server or disk depending on where you execute the php script.

First for getting an image from url you can use three ways to do this:

1. Using file_get_contents

$contents= file_get_contents('http://mydomain.com/folder/image.jpg');

2. Using fsockopen() function

To fetch an image with fsockopen() You should specify the host name of the server and the the rest or the url where the image is stored. To understand better here is a sample function, that takes the  that returns the source code of the image:

 
function GetImg($host,$link)
{
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr (error number $errno)
\n";
} else {
$out = "GET $link HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$out .= "Accept-Language: en-us,en;q=0.5\r\n";
$out .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$out .= "Keep-Alive: 300\r\n";   
$out .= "\r\n";
fwrite($fp, $out);
$contents='';
while (!feof($fp)) {
$contents.= fgets($fp, 1024);
}
fclose($fp);
return $contents;
}
}

Example call: 

$sourceimg=GetImg("www.mywebsiteexample.com","/image.jpg");
$sourceimg=strchr($sourceimg,"\r\n\r\n");//removes headers
$sourceimg=ltrim($sourceimg);//remove whitespaces from begin of the string

3.Using CURL

function GetImageFromUrl($link)
 
{
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_POST, 0);
 
curl_setopt($ch,CURLOPT_URL,$link);
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$result=curl_exec($ch);
 
curl_close($ch);
 
return $result;
 
}

You should have installed at least  PHP 4.0.2. and libcurl installed to use curl.

Here is a function that will get the source of the image into a string variable:

You can use this code to call the function to get the source of the image:

$sourcecode=GetImageFromUrl("http://domain.com/path/image.jpg");

 

After getting the image from url you should save image from url, doing a simple save to file from  a string variable.

You can use this piece of code:

$savefile = fopen('/home/path/image.jpg', 'w');
fwrite($savefile, $sourcecode);
fclose($savefile);

Download Source Code for Saving Image From Url

Tags: ,

TIDIRC Tutorial

TIDIRC is a component of Indy Client, that can help you connect to an IRC server  channel. You can send and receive messages in order to communicate with the server.

There are some important properties which you can use it to specify the server properties:

Host - is the IRC server where you want to connect

Nickname - your nick that will appear in the channel.

ReadTimeout - the time that application should wait until the server don’t respond, it is specified in miliseconds.

RealName - the real name that will appear in the server 

Connecting to host

First you should connect to server and you should use the command:

//variable
IdIRC1: TIdIRC;// IDIRC1 is a variable of TIDIRC component.
//On button click
IDIRC1.Connect;

ON succesfull you have an even OnConnected, where you can do something after the connection is established.

After connecting you can receive each response row from the server with the event IdIRCRaw. With this event you have the row AContent which is a string and you can parse it to take the information from the server or other things that you are interested.

You can take the messages that the other users send to the server, get the status of the channel. 

 

Getting Channels

To get a list of channels you should use the property Channels and access the Items property.

 for i:=1 to idirc1.Channels.Items.count do 
  List[i] := idirc1.Channels.Items[i];//it's a TIDIRCChannel component

In TIDIRCChannel you will have the list of all channels and for every channel you have properties and events for handling a channel.
 Some time, this property will not grab the channels correctly. Here is a function to get the channels from the host. You should put it in the IDIRCRaw event and make a list of channels. This function return a channel:

//GetChannel function
 
function GetChannel(s:string):string;
var p1:integer;
    aux:string;
 begin
    p1:=pos('#',s);
    inc(p1);
    aux:='';
    if p1>1 then
    while  (s[p1]<>' ')and(p1<=length(s)) do
      begin
         aux:=aux+s[p1];
         inc(p1);
      end;
   GetChannel:=aux;
 end;
 
//calling the channel function
 channel:=GetChannel(continut);
 channel:='#'+channel;

Joining a channel

To join a channel on a server you should use the command

IDIRC1.Join(channel);

Sending message

To send a message to one of the users that are connected to the channel

TIDIRC.Say(touser,message)

Parting a channel

To part from a channel you should use the command

TIDIRC.Part(channel,reason)

You can specify an optional string parameter, what was the reason of parting.

Kick user

If you are OP of a channel you can kick a user by specifying the channel, the user to kick and a reason message why you kick it.

Other usefull functions for TIDIRC Component:

GetTopic(channel) – get the topic of the channel
SetTopic(channel,message) – if you are the  OP you can set the topic of a channel
Disconnect – disconnects from the current session.
IsOp(User:string) – test to see if a user is operator.
SetAwayMessage(message) – sets a message when you are not at the computer, to clear the message you should use ClearAwayMessage.

Thread IRC

You should use thread because when you connect to server or send a messsage the form will freeze and the user will not be able to see the form details.
To create a thread with the TIDIRC components you should use the following commands:
IDIRC1.IRCThread.Create(IDIRC1);
IDIRC1.IRCThread.Start;
To end a thread you should use stop it and dispose, like this:
IDIRC1.IRCThread.Terminate;
IDIRC1.IRCThread.Free;
Tags: ,

Why SFMMS?

I just made a simple mass mailer sender in php, which can help you to easily send mass mail to your members. It’s very simple to setup and very useful.

This is a first version of the script, if people will like it, I will make other modify to it.

What is SFMMS?

This is a simple but very usefull Mass Mailer Sender script, that you can use from your server to send mass mails.You can for example use it to send annoncements for your members, that you have an offer for them. You can also use it as mass mailer subscriber to send weekly mails to yours subcribers.

How to install it?

To install SFMMS you should unzip the sfmms.zip to a folder of your choice to your hard disk  and modify the config.php in order to fit to your needs.

$server – it’s the server of your mysql database, which is ussually ‘localhost’

$database – is the name of your database on which your table is stored from the server

$db_user – the user of the database

$db_pass – the password for the user of the database

$fromadmin – email which the users will receive in his email

$table – the table from database where the users are stored

$table_email – the name field for the email of the $table(ex. ‘email’,'Email’)

You can customize the header.php and footer.php to fit with your website.

Upload all the files to a folder from your server.

 

How to use it?

Access http://www.mywebsites.com/folder/massmail.php and put all the details you wanna send to users.

 

Subject – is the subject that will appear in email subject to users.

Message – the message that you will send to users.

Seconds between messages – time to pass between each email that is sent to users(leave it 0.1). This is used when you send lots of messages to not overload smtp server.

Download Simple Free Mass Mailer Sender PHP

Tags: ,

 

You can do allowing of doc/docx file in 2 modes: in html source with the property accept or by php code.

For uploading a doc/docx file you should first have a form where youhave all fields you need to send to server and another field that is of type file.

File:
<form enctype="multipart/form-data" method="POST">This is the code for html:
<table border="0">
<tbody>
<tr>
<td align="left">File:</td>
<td><input accept="doc/docx" name="filename" size="40" type="file" /></td>
</tr>
<tr>
<td><input name="Upload" type="submit" value="Upload" /></td>
</tr>
</tbody></table>
</form>

 

We should specify the enctype of the form to multipart/form-data in order to upload a file.

 

Here is a brief explanation on how we can write the php code to upload one file to our server:

First we should set and verify the file extensions that we will allow the user to upload. We will allow only files with doc/docx extension. We should also verify that the filesize it’s greater then 10 bytes to be sure that is a doc/dox file. If we have no errors then we can use move_uploaded_file function to upload our doc/docx file.

Php code to upload doc/docx file to the server

 

//if we clicked on Upload button
 
if($_POST['Upload'] == 'Upload')
 
  {
 
  //make the allowed extensions
 
  $goodExtensions = array(
 
  '.doc',
 
  '.docx',
 
  );  
 
 
 
  $error='';
 
  //set the current directory where you wanna upload the doc/docx files
 
  $uploaddir = '/home/uername/folderroot/';
 
  $name = $_FILES['filename']['name'];//get the name of the file that will be uploaded
 
  $min_filesize=10;//set up a minimum file size(a doc/docx can't be lower then 10 bytes)
 
  $stem=substr($name,0,strpos($name,'.'));
 
  //take the file extension
 
  $extension = substr($name, strpos($name,'.'), strlen($name)-1);
 
  //verify if the file extension is doc or docx
 
   if(!in_array($extension,$goodExtensions))
 
     $error.='Extension not allowed<br>';
 
<span> </span> //verify if the file size of the file being uploaded is greater then 1
 
   if(filesize($_FILES['filename']['tmp_name']) &lt; $min_filesize)
 
     $error.='File size too small<br>'."\n";
 
  $uploadfile = $uploaddir . $stem.$extension;
 
$filename=$stem.$extension;
 
 
 
if ($error=='')
 
{
 
//upload the file to 
 
if (move_uploaded_file($_FILES['filename']['tmp_name'], $uploadfile)) {
 
echo 'File Uploaded. Thank You.';
 
}
 
}
 
else echo $error;
 
}
Tags: , ,

Fetching results from a mysql table

To connect to a mysql database you should use the command mysql_connect .You should first setup the details of the mysql database.

$connect=mysql_connect($server, $db_user, $db_pass)    or die ("Error: could not connect to database");

$server is the server for the mysql database, usually this is localhost, but you should double check.

$db_user is the user which connects to the server

$db_pass the password for the user

If the can’t connect to the server we should display an error message with die() command.

After we connect to the database we can make a sql query on the database that we want.

//we select  all the rows from table TableName where the Field1 has a value of $value
$results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value);
 while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC))
{
  echo $resultrow['Field2'];//we show the result of the field Field1
}

After we make the query we can take each row of the result query and do whatever we want.

For closing a mysql connection we can use mysql_close($connect);

Example Code in PHP:

 
$server="localhost";//this is ussually localhost
 
$db_userName="UserName";
 
$db_password="Password";
 
$database="DatabaseName";
 
$connect=mysql_connect($server, $db_userName, $db_password  or die ("Mysql connection error");
 
$results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value);
 
while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC))
{
  echo $resultrow['Field2'];//we show the result of the field Field1
}
 
mysql_close($connect);
Tags:

Read small text files in Delphi

First we should declare a variable of type TextFile like this

var f:textfile;//defines variable for type TextFile for maintaining data from a file.

We will need also other variables to read the file:

var s:string;
ch:char;

If you wanna read contents of a file in Delphi you should first assign to a variable the name of the file you wanna read. You can use the following statement:

assignfile(f,path+'filename.txt');// where path can be the path to the directory

If the file you wanna read it’s inside the folder project then you can use the following code:

path:= ExtractFilePath(application.exename);//ExtractFilePath it's a function that returns a string with the path of an .exe

Next if you should let the compiler know that you wanna read the file.

reset(f);

Now you have more options to read a file depending on what your needs are or how bigger it’s the file from where you read.
You can use the following code to read the file character by character(this version that is not faster to read files):

while not eof(f) do
begin
read(f,ch);
s:=s+ch;
end;

You can also use

readln(f,s)

which will read a whole line from the input file.

In the end you should close the file that you opened.

closefile(f);

Complete code, function to return contents of a file:

function ReadSmallFile:string;
var freadfile:textfile;
s,path:string;
ch:char;
 
begin
path:= ExtractFilePath(application.exename);
assignfile(freadfile,path+'filename.dat');
reset(freadfile);
while not eof(freadfile) do
begin
read(freadfile,ch);
s:=s+ch;
end;
closefile(freadfile);
ReadSmallFile:=s;
end;

Read bigger file in Delphi

For reading bigger files in Delphi you should use the function BlockRead. This function is used to read blocks of data into a buffer from a file.
To declare a file you should use:

var biggerfile:file of char;
BufArray: array[1..4096] of Char;//we will read 4 KB at a time
nrcit,i,:integer;
sir:string;

You should after assign to a variable just like the type TextFile:

assignfile(biggerfile,path+'namefile.dat');
reset(biggerfile);

Here is a statement to read a bigger file of type char

repeat
blockread(biggerfile,BufArray,SizeOf(BufArray),nrcit);
for i:=1 to nrcit do
sir:=sir+BufArray[i];
until (nrcit = 0);

To close the file you should use

closefile(fis);

Here is a complete source code function to read a bigger file:

function ReadBiggerFile:string;
var biggerfile:file of char;
BufArray: array[1..4096] of Char;//we will read 4 KB at a time
nrcit,i:integer;
sir,path:string;
begin
path:= ExtractFilePath(application.exename);
assignfile(biggerfile,path+'namefile.dat');
reset(biggerfile);
repeat
blockread(biggerfile,BufArray,SizeOf(BufArray),nrcit);
for i:=1 to nrcit do
sir:=sir+BufArray[i];
until (nrcit = 0);
closefile(biggerfile);
ReadBiggerFile:=sir;
end;
Tags: , ,

A short int have 16 bits so we will need a vector of 16 bits:

short int bits[16]; // from 0 to 15

 

To convert a short int to bits you should divide the integer by 2 until he is 0. 

void ShortIntToBits(int x)
 
{
 
int nr=-1,k1;
 
for(k1=0;k1&lt;=15;k1++)
 
bits[k1]=0;
 
while (x!=0)
 
{
 
nr++;
 
bits[nr]=x%2;
 
x=x/2;
 
}
 
}

To convert a vector of bits to shortint we should iterate to the vector of bits adding to integer a value that is 2(because we have bits) at power of the position of bit.

Here is an example that have a vector  of 15 bits.

short int BitsToShortInt()
 
{
 
short int k1,p=1,x=0;
 
 
 
for (k1=0;k1&lt;=15;k1++)
 
{
 
x=x+bits[k1]*p;
 
p=p*2;
 
}
 
return x;
 
}
Tags: , ,

cURL Post Data – PHP

Introduction

In this post I will talk about using cURL to post data to a server. Curl it’s a library that you can use to get data from a server or send it back. It was created by Daniel Stenberg and it works with ftp,gopher,telnet,file,dict,ldap, http and https protocols. I am not gone write here how you can make to configure and install, I want to show you a method to post data to a server on the http protocol.

How it works? 

You need to initiate a cURL session, put the url of the server you wanna POST data, put the options for the current session, execute session and get the data you need.

 

Here is a list of cURL functions that can help you to post data:

 
curl_init – it’s is used to initiate a cURL session

curl_setopt – it helps you to pass option to cURL for the next transfer.

curl_exec – executes a cURL session

curl_error – containts the last error of cURL sesion that was executed

 

Here is a sample code for posting data in PHP:

 

function datapost($URLServer,$postdata)
{
 
 
 
$agent = "Mozilla/5.0";
 
$cURL_Session = curl_init();
 
curl_setopt($cURL_Session, CURLOPT_URL,$URLServer);<span> </span>
 
curl_setopt($cURL_Session, CURLOPT_USERAGENT, $agent);
 
curl_setopt($cURL_Session, CURLOPT_POST, 1);
 
curl_setopt($cURL_Session, CURLOPT_POSTFIELDS,$postdata);
 
curl_setopt($cURL_Session, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt($cURL_Session, CURLOPT_FOLLOWLOCATION, 1);
 
$result = curl_exec ($cURL_Session);
 
return $result;<span> </span>
 
}
 
 
 
$htmlsource= datapost("http://www.example.com/script.php","param1=value1&param2=value2")

 

 

So first we initiate the cURL sesion with curl_init() and after that we set some options for the current session with curl_setopt and after that we execute the session and get the result.

 

CURLOPT_URL,$URLServer – this option sets the target script.

CURLOPT_USERAGENT,agent – this is optional, it sends to the server an agent.

CURLOPT_POST – this should be set to 1 because we make a post to the server.

CURLOPT_POSTFIELDS – here we should pass the parameters and there values

CURLOPT_RETURNTRANSFER – should be set to 1(because we store the source of the result in a variable) otherwhise the result will be printed on page

CURLOPT_FOLLOWLOCATION – is important if the server it redirects you after you post the data. If the server redirects should be set to 1.

 

If you wanna store a cookie when you execute the sesion you should use:

 

 
curl_setopt($cURL_Session, CURLOPT_COOKIEFILE, $path_to_cookie);
 
curl_setopt($cURL_Session, CURLOPT_COOKIEJAR, $path_to_cookie);
Tags:

Description

I want to begin the first post about PHP with something easy, but very useful. Writing and reading to/from files in PHP.
Here is a short description for reading from file in PHP:

  1. Open the file for reading
  2. If the open was successful then we can read from the output file
  3. After we read from file we should close the file.

    Here is a short description for writing to files in PHP:

    • Open the file for writing
    • If the open was successful then we can Write to the output file
    • After we wrote to file we should close the file.

    OPENING

    To open a file in PHP you should use the function fopen:

    pointer fopen( string $filepath, string $mode)

    This function return a pointer resource when the $filepath exists or FALSE when the file doesn’t exist.

    $filepath is the path to the file that we want to open.
    $mode – this is the type of access when reading or writing to files

    • r – opens the file for reading only
    • r+ – open the file for reading/writing and places the file at the begining of the file
    • w – opens the file for writing only
    • w+ – opens the file for reading/writing places the pointer at the beginning of the file and truncate the size of the file to 0
    • a – places the pointer at the end of the file for writing(append)
    • a+ – places the pointer at the end of the file for reading and writing(append).
    • x – opens for writing, places pointer at the begining of the file.
    • x+ – opens for writing/reading, places pointer at the begining of the file.

    READING

    You can use more functions for reading from file after you open it:
    fread($filepointer,$nbytes)
    $filepointer – a pointer to the file
    $nbytes – number of bytes you wanna read from file. (a character have a size of a byte)

    fgets($filepointer) – reads a line from the file
    fgetc($filepointer) – reads a caracter from file

     

    WRITING

    You can used fwrite($filepointer, $datastring) to write a string to file

    CLOSING

    After you finished writing/reading from file you shuld use:
    fclose($filepointer) – to close the file

     

    Example of codes:

    For reading the first 10 caracters from a file you can use the folowing block of code:

     

    $f=fopen("c:\\path\\file.txt","r");
    $string = fread($f,10);
    fclose($f);

    Reading an entire file to a string variable character by character:

    $f=fopen("c:\\file.txt","r");
    $textstring="";
    while (!feof($f))
    {
    $c=fgetc($f);
    $textstring=$textstring.$c;
    }
    fclose($f);

    Reading a file quickly:

    $path = "c:\\file.txt";
    $f=fopen($path,"r");
    $textstring = fread($f,filesize($path));
    fclose($f);

    Writing a two lines of string to a file

    $path = "myfile.txt";
    $f = fopen($path, 'w') or die("error opening the file");
    $allstring="this is the first line of the test\nthis is the second line of the test";
    fwrite($f,$allstring);
    fclose($f);

    Additional functions that you can be useful for file handling are:

    feof($filepointer) – test if the end of file was reached.
    file_exists($filepointer) – tests if a a file exists
    die() or exit() – terminate the script that is currently executed.

    Tags:

    If you want to catch an exception with the try except statement sometimes you can get an error like “Project .exe raised exception … with message …“. This is because delphi is  setup to stop on delphi exception when you try to catch the exception. To pass this problem  you  have to deselect the option for stopping on delphi exception on the Debugger  option. To do so, go to Tools -> Debugger Options , after that select the Language Exceptions  panel and make sure you deselect the Stop on Delphi Exceptions option. Rebuild again and the  problem should be solved.

    Tags: ,
    Next posts » Back to top