I have an Ubuntu php7.0 server and I am trying to use a php Mailparse script I found here
However I confirmed that composer is installed on the server and mailparse is also on the server. However the below script returns a 500 error and I tracked it down to the top two lines of code that is causing it and not sure how to resolve it.
So what I mean is when I comment out the two lines that say
require_once __DIR__.'/vendor/autoload.php';
$Parser = new PhpMimeMailParser\Parser();
Then the script will load but of course the mail parse wont work??
//load the php mime parse library
require_once __DIR__.'/vendor/autoload.php';
$Parser = new PhpMimeMailParser\Parser();
//Include the AWS SDK using the Composer autoloader.
require 'awssdk/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'pipedemail';
$IAM_KEY = '******';
$IAM_SECRET = '******';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-1'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
// Use the high-level iterators (returns ALL of your objects).
$objects = $s3->getIterator('ListObjects', array('Bucket' => $bucketName));
foreach ($objects as $object)
{
$objectkey = $object['Key'];
$path = "https://s3.amazonaws.com/pipedemail/$objectkey";
//lets get the raw email file to parse it
$Parser->setText(file_get_contents($path));
// Once we've indicated where to find the mail, we can parse out the data
$to = $Parser->getHeader('to'); // "test" <test#example.com>, "test2" <test2#example.com>
$addressesTo = $Parser->getAddresses('to'); //Return an array : [[test, test#example.com, false],[test2, test2#example.com, false]]
$from = $Parser->getHeader('from'); // "test" <test#example.com>
$addressesFrom = $Parser->getAddresses('from'); //Return an array : test, test#example.com, false
$subject = $Parser->getHeader('subject');
}
Related
For many years my PHP application has used the AWS SDK 2 for PHP and now we are considering switching to SDK 3.
However, looking in the SDK documentation we couldn't find any simple example, they all talk about multipart and other things that are very different from what we have today.
The code below is what we have for SDK 2, how would a simple object be uploaded to a bucket using SDK3?
<?php
define('S3_KEY', '');
define('S3_SECRET', '');
define('S3_BUCKET_NAME', '');
$s3 = S3Client::factory(array(
'key' => S3_KEY,
'secret' => S3_SECRET
));
$filename = 'example/001/1.jpg';
try {
$resource = fopen($origin, 'r');
$return = $s3->upload(S3_BUCKET_NAME, $filename, $resource, 'public-read');
return $return['ObjectURL'];
} catch (S3Exception $e) {
return false;
}
In AWS SDK for PHP Version 3, ObjectUploader can upload a file to Amazon S3 using either PutObject or MultipartUploader, depending on what is best based on the payload size.
Below is the sample code, you can use to upload objects into the S3 bucket:-
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\ObjectUploader;
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-2',
'version' => '2006-03-01'
]);
$bucket = 'your-bucket';
$key = 'my-file.zip';
// Using stream instead of file path
$source = fopen('/path/to/file.zip', 'rb');
$uploader = new ObjectUploader(
$s3Client,
$bucket,
$key,
$source
);
do {
try {
$result = $uploader->upload();
if ($result["#metadata"]["statusCode"] == '200') {
print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
}
print($result);
} catch (MultipartUploadException $e) {
rewind($source);
$uploader = new MultipartUploader($s3Client, $source, [
'state' => $e->getState(),
]);
}
} while (!isset($result));
fclose($source);
From Version 3 of the SDK Key differences:
Use new instead of factory() to instantiate the client.
The 'version' and 'region' options are required during
instantiation.
I'm trying to set up amazon SES with PHP. I've scoured the internet and the documentation for AWS PHP SDK but I only see outdated scripts on how to include the actual library and send e-mail. Does anyone here have a working script for using Amazon SES with PHP?
This is the closest I've found to test the script but it doesn't work:
require 'src/aws.phar';
use Aws\Common\Enum\Region;
use Aws\Ses\SesClient;
try {
$ses = SesClient::factory(array(
'key' => 'AKIAJ4ERVU6XXXXXXX',
'secret' => 'kMgagzJmB4Xjw7UD+Md0KNgW+CTE2jCXXXXX/',
'region' => Region::US_EAST_1
));
$ses->verifyEmailIdentity( array(
'EmailAddress' => 'jason#aol.com'
));
}
catch( Exception $e )
{
echo $e->getMessage();
}
First, you would want to disable/delete and generate new keypairs so that you would not have to face bad situation as there are scrapers/bots and people who might misuse your access key-pairs.
As for your original question, you didn't describe what didn't work for you. Anyway, since you wanted a working version, check the source code of this: https://github.com/daniel-zahariev/php-aws-ses which will give you enough idea to get yours working.
This is the working code that i got for you, let me know if this helps
<?php
require 'aws.phar';
use Aws\Ses\SesClient;
$client = SesClient::factory(array('region'=>'us-east-1','version'=>
'latest','credentials' => array('key' => 'xxxxx','secret' => 'xxxxxx',)));
$msg = array();
$msg['Source'] = $message['from'];
$msg['Destination']['ToAddresses'][] = $to_address;
$msg['ReplyToAddresses'][] = $from;
$msg['Message']['Subject']['Data'] = $subject;
$msg['Message']['Subject']['Charset'] = "UTF-8";
$msg['Message']['Body']['Html']['Data'] = $body;
$msg['Message']['Body']['Html']['Charset'] = "UTF-8";
try{
$result = $client->sendEmail($msg);
$logmsg = "Passed ".from." - ".to_address;
} catch (Exception $e) {
$logmsg = "Failed ".$message['from']." - ".$to_address;
error_log('Failed Email '.from." - ".$to_address);
}
This is the simple code I`m using to upload an image in my rackspace account with PHP :
<?php
$api_username = 'lolcat';
$api_key = 'sexyapi';
require 'cloudfiles.php';
$auth = new CF_Authentication($api_username, $api_key);
$auth->authenticate();
$connection = new CF_Connection($auth);
$images = $connection->create_container("pitch");
$url = $images->make_public();
echo 'The url is '.$url;
$file = 'sherlock.jpg';
$img = $images->create_object($file);
$img->load_from_filename($file)
?>
Also everytime it gives diffrent errors. Like:
"Strict standards: Only variables should be passed by reference in C:\wamp\www\cloudfiles.php on line 1969 "
" Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\cloudfiles_http.php on line 1249"
A sample of errors (imgur image)
Please help I`ve been trying this simple thing for 2 hours now.
Php-cloudfiles bindings are deprecated. I suggest you to give php-opencloud a try. I shouldn't be hard to port your code. Here's a quick example:
<?php
require 'vendor/autoload.php';
use OpenCloud\Rackspace;
$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array(
'username' => 'foo',
'apiKey' => 'bar'
));
$service = $client->objectStoreService('cloudFiles', 'DFW');
$container = $service->createContainer('pitch');
$container->enableCdn();
$cdn = $container->getCdn();
//Print "Container SSL URL: " . serialize($cdn);
$files = array(
array(
'name' => 'file_1.txt',
'body' => fopen('files/file_1.txt', 'r+')
)
);
$container->uploadObjects($files);
You can find php-opencloud docs at: https://github.com/rackspace/php-opencloud/blob/master/docs/getting-started.md
I've spent the last few hours following tutorials for implementing file uploads to Amazon S3 using php. I uploaded the most recent version of Donovan Schönknecht's S3 class to my server (as S3.php) and I am trying to use the following code to test upload capability. I know this code will work because I've seen numerous examples in action.
<?php
require('S3.php');
$s3 = new S3('KEY', 'SECRET KEY');
//insert into s3
$new_name = time() . '.txt';
S3::putObject(
'upload-me.txt',
'bucketName',
$new_name,
S3::ACL_PUBLIC_READ,
array(),
array(),
S3::STORAGE_CLASS_RRS
);
?>
I get an error 500 server error when I attempt to load this page. Additionally, every other reputable tutorial of this nature has given me the same error 500.
I verified that my key and secret key are valid by connecting to S3 with Cyberduck.
Does anyone have a clue as to what I could be doing incorrectly?
Thanks,
Sean
As it turns out, I was missing the cURL extension for PHP and this was causing an issue as the S3 class I was using required the use of cURL. All is working now.
You should also consider using the official AWS SDK for PHP. Examples for using S3 with the SDK can be found in their S3 user guide.
You can download most recent version of Amazon PHP SDK by running following composer command
composer require aws/aws-sdk-php
Further configuration to upload file on Amazon s3 are following
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// Set Amazon s3 credentials
$client = S3Client::factory(
array(
'key' => "your-key",
'secret' => "your secret key"
)
);
try {
$client->putObject(array(
'Bucket'=>'your-bucket-name',
'Key' => 'your-filepath-in-bucket',
'SourceFile' => 'source-filename-with-path',
'StorageClass' => 'REDUCED_REDUNDANCY'
));
} catch (S3Exception $e) {
// Catch an S3 specific exception.
echo $e->getMessage();
}
Get step by step details from here Amazon S3 File Upload Using PHP
Following example worked for me:
<?php
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$client = S3Client::factory([
'version' => 'latest',
'region' => 'us-west-1',
'credentials' => [
'key' => "<scret-key>",
'secret' => "<my-secret>"
]
]);
try {
$client->putObject([
'Bucket' =>'<my-bucket-name>',
'Key' => '<file-name>',
'SourceFile' => '<file-path-on-server>', // like /var/www/vhosts/mysite/file.csv
'ACL' => 'public-read',
]);
} catch (S3Exception $e) {
// Catch an S3 specific exception.
echo $e->getMessage();
}
Getting security credentials:
https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
https://console.aws.amazon.com/iam/home?#/security_credential
Getting region code
https://docs.aws.amazon.com/general/latest/gr/rande.html
Use this one to Upload Images using a form and it's working Fine for me
you may try using it with your code
$name = $_FILES['photo']['name'];
$size = $_FILES['photo']['size'];
$tmp = $_FILES['photo']['tmp_name'];
//////Upload Process
// Bucket Name
$bucket = 'bucket-name';
require_once('S3.php');
//AWS access info
$awsAccessKey = 'awsAccessKey';
$awsSecretKey = 'awsSecretKey';
//instantiate the class
$s3 = new S3($awsAccessKey, $awsSecretKey);
$s3->putBucket($bucket, S3::ACL_PUBLIC_READ);
//Rename image name.
$actual_image_name = time();
//Upload to S3
if($s3->putObjectFile($tmp, $bucket , $actual_image_name, S3::ACL_PUBLIC_READ) )
{
$image='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
}else{
echo 'error uploading to S3 Amazon';
}
I never found a updated Script with Amazons latest sdk. i have made it by myself. it woks as a php commandline interpreter script. give it a try :
https://github.com/arizawan/aiss3clientphp
I'm not familiar with S3 API, but i used it as the storage with https://github.com/KnpLabs/Gaufrette. Gaufrette is a library that provides pretty nice abstraction layer above S3 and other file services/systems.
Here is sample code to upload images on Amazon S3.
// Bucket Name
$bucket="BucketName";
if (!class_exists('S3'))require_once('S3.php');
//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'ACCESS_KEY');
if (!defined('awsSecretKey')) define('awsSecretKey', 'ACCESS_Secret_KEY');
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putBucket($bucket, S3::ACL_PUBLIC_READ);
if($s3->putObjectFile($tmp, $bucket , $image_name_actual,S3::ACL_PUBLIC_READ) )
{
$message = "S3 Upload Successful.";
$s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
echo "<img src='$s3file'/>";
echo 'S3 File URL:'.$s3file;
}
else{
$message = "S3 Upload Fail.";
}
}
Below is the best solution. Its using multipart upload.Make Sure to install Aws SDK for PHP before using
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;
try {
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => 'AKIAUMIZJR5U5IO7M3',
'secret' => 'BmcA3vFso1bc/9GVK7nHJtFk0tQL6Vi5OoMySO',
],
]);
// Use multipart upload
$source = 'https://b8q9h6y2.stackpathcdn.com/wp-content/uploads/2016/08/banner-for-website-4.png';
$uploader = new MultipartUploader($s3Client, $source, [
'bucket' => 'videofilessandeep',
'key' => 'my-file.png',
'ACL' => 'public-read',
]);
try {
$result = $uploader->upload();
echo "Upload complete: {$result['ObjectURL']}\n";
} catch (MultipartUploadException $e) {
echo $e->getMessage() . "\n";
}
} catch (Exception $e) {
print_r($e);
}
Trying to upload files using the PHP SDK of s3. Uploading the file to the existing Bucket, pops up the error.
<?php
error_reporting(-1);
// Set plain text headers
header("Content-type: text/plain; charset=utf-8");
// Include the SDK
require_once '../sdk.class.php';
//%**********************************%*/
// UPLOAD FILES TO S3
// Instantiate the AmazonS3 class
$s3 = new AmazonS3();
$s3->path_style = true;
$bucket = 'photossss1.abc.com';
$name = "picture.jpg" ;
$response = $s3->create_object($bucket, 'picture2.jpg', array(
'fileUpload' => 'picture.jpg'
));
if($response->isOk()){
echo " Done" ;
} else {
//var_dump($response);
echo "error: create_object error.";
}
What is the error in the above code..?
Debug:
print_r($response->body);
=>
CFSimpleXML Object
(
[Code] => PermanentRedirect
[Message] => The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
[RequestId] => DACD5C54BC4BD82
[Bucket] => photossss1.abc.com
[HostId] => QUBlZEZKh0Ujzk6UyGG7LjC0vMCWDlOPszTZru/+OpWidBH84VXor1
[Endpoint] => photossss1.abc.com.s3.amazonaws.com
)
You need to set region after class initialization
// Initialize the class
$s3 = new AmazonS3();
$s3->set_region( AmazonS3::REGION_EU_W1 );
...
Related page on SDK Documentation
What is the result of:
<?php
print_r($response->body);
This should give you a proper error message from S3.
in services/s3.class.php;
replace this part:
const REGION_US_E1 = 's3.amazonaws.com';
to:
const REGION_US_E1 = 's3-eu-west-1.amazonaws.com';