How to delete from S3 - php

I have a PHP file upload script for putting documents onto S3, so far the User can delete the file from the SQL list but not from S3 directly. Is they a simple way I can add the delete from S3 into the same code as below
The rest of the php script includes the s3.php if that helps
$bucket = 'files';
$path = 'file/'; // Can be empty ''
if (isset($_GET['id']))
{
$id = $_GET['id'];
$path .= 'File'.$id.'/';
if (isset($_GET['action']))
{
$action = $_GET['action'];
if ($action = "deleteFile")
{
$Fileid = $_GET['Fileid'];
$query = "DELETE FROM amazon_upload WHERE Upload_File_Id='".$Fileid."'";
$result = mysql_query($query);
if (!$result)
{
die ("could not query database: <br />".mysql_error());
}
$locationHeader = "Location: http://www.website.com/upload.php?id=".$id;
header($locationHeader);
}
}
}

this works well
$s3 = new AmazonS3();
$bucket = 'velobucket';
$folder = 'mydirectory/';
$response = $s3->get_object_list($bucket, array(
'prefix' => $folder
));
foreach ($response as $v) {
$s3->delete_object($bucket, $v);
}

Try With
unlink()
E.G
$file = "test.txt";
if (!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}

Related

laravel 5.4 custom command not working

This is the first time i'm working in Laravel. I'm developing a custom command which will read a file and insert rows in database. I'm getting errors. Below is my code any help will be appreciated.
Command File.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use App\Ship;
//use DB;
class shipdata extends Command
{
protected $signature = 'ship:start';
protected $description = 'This Command will Read file and Extract data from it and will store data in database';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// $this->line('Query Working');
ShipNow::ShipNow();
}
}
Model File
public function ShipNow()
{
$dir = "d:/xampp/htdocs/lara12/IN/";
$failed_dir = "d:/xampp/htdocs/lara12/FAILED/";
$processed_dir = "d:/xampp/htdocs/lara12/PROCESSED/";
$files = array();
// Get all files which need to process
foreach (glob($dir."*.SHIP") as $file) {
$files[] = $file;
}
// If .SHIP files available in the folder then start processing
if(count($files) > 0)
{
// Start processing file
foreach($files as $file)
{
$row = 1;
$file_name = $file;
// Get file name without extension
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
// Generate new filename with extension PROC
$rename_filename = $withoutExt.".PROC";
// Rename filename
$file_proc = rename($file_name, $rename_filename);
// File processing
$error = 0;
if (($handle = fopen($rename_filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
$num = count($data);
// For header table insert
if($row==1)
{
$myparams['warehouse'] = $data[0];
$myparams['SHIPMENT_ID'] = $data[1];
$myparams['COMPANY'] = $data[2];
$myparams['CARRIER'] = $data[3];
$myparams['CARRIER_SERVICE'] = $data[4];
$myparams['CUSTOMER'] = $data[5];
$myparams['CUSTOMER_NAME'] = $data[6];
$myparams['SHIP_TO_NAME'] = $data[7];
$myparams['SHIP_TO_ADDRESS1'] = $data[8];
$myparams['SHIP_TO_ADDRESS2'] = $data[9];
$myparams['SHIP_TO_ADDRESS3'] = $data[10];
$myparams['SHIP_TO_CITY'] = $data[11];
$myparams['SHIP_TO_COUNTRY'] = $data[12];
$myparams['SHIP_TO_POSTAL_CODE'] = $data[13];
$myparams['SHIP_TO_ATTENTION_TO'] = $data[14];
$myparams['SHIP_TO_PHONE_NUM'] = $data[15];
$myparams['SHIP_TO_EMAIL_ADDRESS'] = $data[16];
$myparams = save();
/* $sql = "exec dbo.Portal_3PL_ShipmentEntry_Header '".$myparams['SHIPMENT_ID']."','".$myparams['COMPANY']."','".$myparams['CARRIER']."','".$myparams['CARRIER_SERVICE']."','".$myparams['CUSTOMER']."','".$myparams['CUSTOMER_NAME']."','".$myparams['SHIP_TO_NAME']."','".$myparams['SHIP_TO_ADDRESS1']."','".$myparams['SHIP_TO_ADDRESS2']."','".$myparams['SHIP_TO_ADDRESS3']."','".$myparams['SHIP_TO_CITY']."','".$myparams['SHIP_TO_COUNTRY']."','".$myparams['SHIP_TO_POSTAL_CODE']."','".$myparams['SHIP_TO_ATTENTION_TO']."','".$myparams['SHIP_TO_PHONE_NUM']."','".$myparams['SHIP_TO_EMAIL_ADDRESS']."'";
$sql_result = odbc_exec($conn, $sql);
if (odbc_error())
{
echo odbc_errormsg($conn);
$error = 1;
}
$ERP_ORDER_LINE_NUM = 1;
$shipment_header = odbc_fetch_array($sql_result);*/
}
// For shipment detail
else
// {
// $ITEM = $data[1];
// $QUANTITY = intval($data[2]);
// $INTERNAL_SHIPMENT_NUM = $shipment_header['INTERNAL_SHIPMENT_NUM'];
//
// $query2 = "exec dbo.Portal_3PL_ShipmentEntry_Detail '".$INTERNAL_SHIPMENT_NUM."','".$myparams['COMPANY']."',".$ERP_ORDER_LINE_NUM.",'".$ITEM."','".$QUANTITY."',NULL,'N'";
// echo $query2.PHP_EOL;
// $query_result2 = odbc_exec($conn, $query2);
// if (odbc_error())
// {
// echo odbc_errormsg($conn);
// $error = 1;
//
// }else{
// $ERP_ORDER_LINE_NUM++;
// }
// $shipment_detail = odbc_fetch_array($query_result2);
//
// echo trim($shipment_detail['Result'])."#".trim($shipment_detail['Comment'])."#".trim($shipment_detail['INTERNAL_SHIPMENT_LINE_NUM']);
// }
$row++;
}
if($error == 1)
{
$failed_file = "FAILED/".basename($withoutExt).".FAIL";
$file_to_move = "IN/".basename($rename_filename);
fclose($handle);
rename($file_to_move, $failed_file);
// $sql = "INSERT INTO qcimportlog (filename, recordprocess, status) VALUES
// ('$file_name', '$row', 'failed')";
// $result = mysql_query($sql) or die(mysql_error());
}
else
{
$processed_file = "PROCESSED/".basename($rename_filename);
$file_to_move = "IN/".basename($rename_filename);
echo $processed_file;
fclose($handle);
rename($file_to_move, $processed_file);
// $sql = "INSERT INTO qcimportlog (filename, recordprocess, status) VALUES
// ('$file_name', '$row', 'success')";
// $result = mysql_query($sql) or die(mysql_error());
}
}
}
}
else
{
echo "No files to process";
}
}
Kernel.Php
protected $commands = [
Commands\QuizStart::class,
Commands\SendWelcomeEmailCommand::class,
Commands\shipdata::class,
];
ERRORs:
D:\xampp\htdocs\lara12>php artisan ship:start
PHP Fatal error: Class 'App\Console\Commands\ShipNow' not found in D:\xampp\htdocs\lara12\app\Console\Commands\shipdata.php on line 26
[Symfony\Component\Debug\Exception\FatalErrorException]
Class 'App\Console\Commands\ShipNow' not found
ShipNow::ShipNow() should be Ship::ShipNow(), since that's the name of the Model and you call it as a static method, so it has to be a static method in the Ship file:
public static function ShipNow()
{
...

How to store audio file on server?

<?php
include("db.php");
$uploadDir = "../audioupload/";
$uid=$_POST['uid'];
$meeting_id=$_POST['meeting_id'];
$fileName = $_FILES['audio']['name'];
$tmpName = $_FILES['audio']['tmp_name'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
if($result)
{
$sql="INSERT INTO `audio`(`uid`,`meeting_id`,`audio`) VALUES ('".$uid."','".$meeting_id."','".$result."')";
$result1 = mysqli_query($conn,$sql);
if($result1)
{
$sql1="select * from `audio` where `uid`='$_POST[uid]'";
$result = mysqli_query($conn,$sql1);
$count = mysqli_num_rows($result);
}
if($count>0)
{
$emparray = array();
while($row = mysqli_fetch_array($result))
{
$emparray=array(
'success' => true,
'message' => "Audio saved Successfully!",);
}
}
}
else
{
$row = mysqli_fetch_array($result);
$emparray=array(
'success' => false,
'message' => "Incorrect Data!",
);
}
echo json_encode($emparray,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT);
mysqli_close($conn);
?>
this is my code. im creating restful api for storing audio on server.im testing this link with postman tool. it gives me correct json response on postman. and audio saves in mysql database. But it not store in folder named audioupload that is subfolder in another folder. please help me with the same

copy images from ftp location to local directory using PHP

I am trying to get images from ftp location to local directory, I have a mysql table with ID and image name as columns. I can't copy the image from ftp location to local folder.Th script gets connected to the ftp server gets the image and creates sub directories according to ID on local folder but fails to write the image.
Script:
function etCommonGetImagePath($conn, $camName, $id) {
$serverDir = $_SERVER['DOCUMENT_ROOT'];
$imagesTop = "/cam_images";
$idArray = str_split(strval($id));
$idString = implode('/', $idArray);
$webPath = $imagesTop . "/" . $camName . "/" . $idString . ".jpg";
$full_path = $serverDir . $webPath;
if (file_exists($full_path)) {
return $webPath;
}
else {
$tableName = $camName;
// Is there an image in the database?
$sql = "SELECT image, datetime, image_name FROM $tableName WHERE id=$id";
$result = $conn->Execute($sql);
if (!$result) {
print $conn->ErrorMsg();
}
$rows = $result->fields;
$imageData = $rows['image'];
$sightingDt = $rows['datetime'];
$sightingTs = strtotime($sightingDt);
$sightingFile = $rows['image_name'];
if ($imageData != NULL) {
// We have an image - copy it out to the filesystem
chdir($serverDir.$imagesTop);
if (!file_exists($camName)) {
mkdir($camName);
}y
chdir($camName);
foreach ($idArray as $dir) {
if (!file_exists($dir)) {
mkdir($dir);
}
chdir($dir);
}
$imageFh = fopen($full_path, 'w');
$numBytes = fwrite($imageFh, $imageData);--- this is where it fails.
fclose($imageFh);
}
}

Use a variable from one IF - Statement into the other IF - Statement in PHP

I have a variable $target inside an IF - Statement in my login.php. I created the folders and sub-folders based on this variable. Now i want to move the uploaded file to this location. How can I do that?
here is the code
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
}
else if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
//$target4 = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
else
{
echo "asdfg";
}
Userid and Pid comes from login.html and Image value comes from upload.html
Nest the else-if as an if in the first if. Otherwise it won't be executed.
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
}
$upload = "Your desired location";
//comes from the login.html page
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "Whatever coloumn you wish to echo from database".'<br/>';
echo $row['col1'].'<br/>'.'<br/>';
echo "Second Coloumn".'<br/>';
echo '<a href="upload.html"/>'.$row['col2'].'</a>'.'<br/>';
//create the folders and subfolders based on the data from the database
$target = $upload.'/'.$row['col1'].'/'.$row['col2'].'/'.$row['col3'].'/'.$row['col4'].'/'.$row['col5'].'/';
//for renaming the image.
$imagename = $row['col1'].'.'.$row['col2'].'.'.$row['col3'].'.'.$row['col4'].'.'.$row['col5'].'.'.'jpg';
//create the folders and subfolders
if(!file_exists($target))
{
mkdir($target,null,0777);
}
//start session and store the value of $target and $imagename in a variable
session_start();
$_SESSION['str'] = $target;
$_SESSION['img'] = $imagename;
//This comes from other HTML page but to the same PHP.
if(isset($_FILES['image']))
// image upload from upload.html
// Want the value of target here.
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
//Move the uploaded file to the desired location.
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
echo "Upload Successful";
Hope this would be helpful for all.

Problems deleting File PHP

This is my code to pull information from my sql database and then I want to delete the .txt files in each directory, but I can't seem to figure out why it won't delete the files.
<?php
session_start();
$user = $_SESSION['SESS_USERNAME'];
$id = array();
$id = $_POST['selected'];
//Include database connection details
require_once('config_order.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if (!$db) {
die("Unable to select database");
}
//Create query
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
// display query results
while ($row = mysql_fetch_array($query)) {
$c_name = $row['clientname'];
$sitestreet = $row['sitestreet'];
$inspector = $row['inspector'];
}
mysql_close($link);
$client_name = str_replace(" ", "_", $c_name);
$site_street = str_replace(" ", "_", $sitestreet);
$client_name = "{$client_name}.txt";
$site_street = "{$site_street}.txt";
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (unlink($client_path . "/" . $client_name)) {
echo 'File Deleted';
} else {
echo 'File could not be deleted';
}
?>
I think this is because your while loop is overwriting the $c_name, $sitestreet and $inspector variables. This means you will only ever delete the last file.
Is this what you were trying to do? (Edited Again...)
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` IN (".mysql_real_escape_string(implode(',',$id)).")");
while ($row = mysql_fetch_array($query)) {
$inspector = $row['inspector'];
$client_name = str_replace(" ", "_", $row['clientname']).'.txt';
$site_street = str_replace(" ", "_", $row['sitestreet']).'.txt';
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (!file_exists($client_path.'/'.$client_name)) {
echo "File $client_path/$client_name does not exist!\n";
} else echo (unlink($client_path.'/'.$client_name)) ? "File $client_path/$client_name was deleted\n" : "File $client_path/$client_name could not be deleted\n";
}
mysql_close($link);
Try some extra debugging:
$realpath = $client_path . '/' . $client_name;
if (file_exists($realpath)) {
if (is_writable($realpath)) {
if (unlink($realpath)) {
echo "$realpath deleted";
} else {
echo "Unable to delete $realpath";
}
} else {
echo "$realpath is not writable";
}
} else {
echo "$realpath does not exist";
}
On first glance, this is a problem, if $_POST['selected'] is not an array:
$id = array();
$id = $_POST['selected'];
...
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
You are instantiating $id as an empty array, then overwriting it with $_POST['selected'], so $id[0] is the first character of the string $id.
For example, if $_POST['selected'] is 12345:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'"
is equivalent to:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '1'"
Either don't try to access it with an index or do $id[] = $_POST['selected']; to add the element onto the $id array instead.
Whether that is an array or not, you do need to either sanitize that input before you insert it into the query or use prepared statements, though!

Categories