file_put_contents multiple image upload through API in PHP - php

I am trying to upload multiple images through a PHP API.
When uploading, the data sending returns success, but it only uploads the names of the images to the Database and the files are not saved on the server side.
I tried to specify separate paths to decode, and then I used the file_put_contents function, but nothing uploads correctly to the server.
if($_SERVER['REQUEST_METHOD']=='POST'){
$pic = $_POST['pic'];
$random = random_word(20);
$path = "grocery/item_img/".$random.".jpg";
$actualpath = "$random.jpg";
$actualpath1 = "$random1.jpg";
$actualpath2 = "$random2.jpg";
$sql = "INSERT INTO item (`pic`, `pic1`, `pic2`)
VALUES (NULL, '$actualpath', '$actualpath1', '$actualpath2')";
class emp{}
if(mysqli_query($koneksi,$sql)){
foreach ($_POST['pic'] as $name) {
file_put_contents($path, $name);
}
echo json_encode(array( 'success' => 1,'message'=>'Item Added Successfully'));
}
else{
echo json_encode(array( 'success' => 0,'message'=>'Failed to Add Item Image'));
}
}
function random_word($id = 20){
$pool = '1234567890abcdefghijkmnpqrstuvwxyz';
$word = '';
for ($i = 0; $i < $id; $i++){
$word .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $word;

SOLVED
foreach gives Invalid argument supplied
when edits it to
foreach ((array) $pic as $image) {
...
}
error gone but still no uploads
then tried
move_uploaded_file($_FILES["pic"]["tmp_name"], $path1);
give error of :
Undefined index: pic
then edits to :
if (isset($_FILES['foto'])) {
move_uploaded_file($_FILES["foto"]["tmp_name"], $path1); }
error gone but won't upload
tried to edit the file_put_contents
to the param of pic1
it uploaded the second pic ,,,
so below is the working code which uploads the three images while storing their paths to the DB
anyway to make it neat while working
if($_SERVER['REQUEST_METHOD']=='POST'){
$pic = $_POST['pic'];
$pic1 = $_POST['pic1'];
$pic2 = $_POST['pic2'];
$random = random_word(20);
$random1 = random_word(20);
$random2 = random_word(20);
$path = "../item_img/".$random.".jpg";
$actualpath = "$random.jpg";
$actualpath1 = "$random1.jpg";
$actualpath2 = "$random2.jpg";
//upload files
$path1 = '../item_img/'.$actualpath;
$path2 = '../item_img/'.$actualpath1;
$path3 = '../item_img/'.$actualpath2;
$sql = "INSERT INTO item (`pic`, `pic1`, `pic2`)
VALUES (NULL, '$actualpath', '$actualpath1', '$actualpath2')";
class emp{}
if(mysqli_query($koneksi,$sql)){
file_put_contents($path1,base64_decode($pic));
file_put_contents($path2,base64_decode($pic1));
file_put_contents($path3,base64_decode($pic2));
}
echo json_encode(array( 'success' => 1,'message'=>'Item Added Successfully'));
}
else{
echo json_encode(array( 'success' => 0,'message'=>'Failed to Add Item Image'));
}
}
function random_word($id = 20){
$pool = '1234567890abcdefghijkmnpqrstuvwxyz';
$word = '';
for ($i = 0; $i < $id; $i++){
$word .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $word;

Related

How to delete multiple uploaded images in folder using PHP

How to delete multiple images in PHP.But Single product delete is working fine.
if (isset($_REQUEST['delete_product'])) {
$ca_in_id = $_REQUEST['delete_product'];
$where = array("ca_in_id" => $ca_in_id);
$data = $this->select_where('catalog_inventory', $where);
//$res = $data->fetch_object();
$result = $this->delete_where('catalog_inventory', $where);
if ($result) {
// (file_exists($pic1)) {
// print_r($pic1);
// exit();
while ($row = mysqli_fetch_array($data)) {
$image = $row["upload_file"];
$pic1 = ("$image");
unlink('product_images/' . $pic1);
print_r($pic1);
}
exit();
//}
?>
<script>
alert("Delete Sucess");
window.location = "list-product";
</script>
<?php
} else {
?>
<script>
alert("Delete Fails");
window.location = "list-product";
</script>
<?php
}
}
And multiple Image delete show this error :-
How to solve this issues?
THANKS.
I have Solve issues First get all values in database and using explode function use the count database columns values and use finally for loop.
This My Code:-
This code means is get values in database.
$data = $this->select_where('catalog_inventory', $where);
$res = $data->fetch_object();
$image = $res->upload_file;
$allimages = explode(",", $image);
$countallimages = count($allimages);
After get multiple values and values run the looping
for ($i = 0; $i < $countallimages; $i++) {
if (file_exists("product_images/" . $allimages[$i]) == false) {
echo "error ";
exit();
}
}
for ($i = 0; $i < $countallimages; $i++) {
$path = "product_images/" . $allimages[$i];
if (empty($path)) {
} else {
unlink($path);
}
}
Thanks ...

PHP calling Python with Base64 image data fails

I am trying to make a program for my company, that takes images and sends them to an API with relevant information.
The script takes a title, makes a directory on my system, puts the images in the directory, loops through the directory, converts each image to Base64Data, and passes the data do a python script that posts the data to the API. But for some reason, my loop stops on the first image.
UPDATED CODE: I tried to make the code a little more understandable. I am getting an invalid base64 code from the API. The function "photo" shows the format XML has to be constructed in.
UPDATED - FIX: Used cURL library in PHP instead of passing data to python script.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$count = 0;
function photo($base64, $caption, $description, $displayname, $credits){
$data = "<image xmlns='http://apiapi.com/cms' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><caption>'";
$data .= $caption;
$data .= "'</caption>";
$data .= "<credits>'";
$data .= $credits;
$data .= "'</credits><data>'";
$data .= $base64;
$data .= "'</data>";
$data .="<description>'";
$data .= $base64;
$data .= "'</description><displayname>'";
$data .= $displayname;
$data .="'</displayname><extension>JPG</extension>";
$data .= "<imageusage>SlideShow</imageusage><uploadmethod>Server</uploadmethod>";
$data .= "</image>";
return $data; }
function base64url_encode($s) {
return str_replace(array('+', '/'), array('-', '_'), base64_encode($s));
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$dirty_title = $_POST['title'];
$title = htmlspecialchars($dirty_title);
chdir('uploads');
mkdir($title, 0777, true);
chdir($title);
//echo getcwd();
foreach ($_FILES['files']['name'] as $i => $name) {
$type = pathinfo($name, PATHINFO_EXTENSION);
$superstring = $title . $count .".". $type;
//echo "SuperString = " . $superstring."<br />";
if (strlen($_FILES['files']['name'][$i]) > 1) {
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $superstring)) {
$count++;
}
}
}
}
function endsWith($haystack, $needle)
{
return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
if (isset($_POST['submit'])){
$curdir = getcwd();
//$exiftool = exec('exiftool -all= *.jpg');
//echo "exiftool = ".$exiftool."<br />";
$dir = new DirectoryIterator($curdir);
$count = 0;
foreach ($dir as $fileinfo){
if ($dir == '.' || $dir == '..' || endsWith($fileinfo, ".jpg_original")){}
else{
$count ++;
chmod($fileinfo, 0777);
$caption = $_POST['caption'];
$description = $_POST['description'];
$displayname = $_POST['displayname'];
$credit = $_POST['credits'];
$final_info = $curdir."/".$fileinfo;
$type = pathinfo($fileinfo, PATHINFO_EXTENSION);
$data = file_get_contents($final_info);
$mybase = base64url_encode($data);
echo "Function Worked";
$photo = photo($mybase, $caption, $description, $displayname, $credit);
$file_name = "data".$count.".txt";
$file = fopen($file_name, "w");
fwrite($file, $photo);
fclose($file);
$cwd = getcwd();
echo "REAL PATH: ".realpath($cwd);
}
}
$cwd = getcwd();
$realpath = realpath($cwd);
$test =exec("/usr/bin/python /var/www/html/helper_scripts/frankAPI.py '{$realpath}'");
echo $test;
}
?>
And here is the python script that takes the file path as argument, reads the written data that the PHP script wrote, and sends it to the API. Now im getting a 500 error, and its saying the base64 encoding that Im sending isnt recognized as base64.
#!/usr/bin/python
import sys
import os
import requests
if __name__ == "__main__":
try:
directory = str(sys.argv[1])
headers = {'Authorization':'usernameusername',
'Content-Type': 'application/xml'
}
os.chdir(directory)
dirs = os.listdir('.')
for file in dirs:
if file.endswith(".txt"):
print file
with open(file, 'r') as content_file:
content = content_file.read()
r = requests.post('https://cms.worldnow.com/v1.0/images',
headers=headers,
data=content)
print r.text[0:100]
except Exception, e:
print e

ftp_nlist ... how to know if it's a file or a folder?

I'm writing a script for download from FTP..
In the form I need to show files and folders..
With ftp_nlist, they come all togethers but I want to know who's who ..
I can't find an easy way to do this:
$contents = ftp_nlist($connection, $rep);
$dossiers =array();
$fichiers = array();
foreach($contents as $content){
//if folder
if (is_folder($content)) $dossiers[] = $content;
//si file
if(is_filex($content)) $fichiers[] = $content;
}
Of course is_file and is_dir don't work with distant files...
I've find something with ftp_rawlist and the size of each result..
like this:
if($result['size']== 0){ //is dir }
But in case of an empty file???
So what id the way to know what is a folder and what is a file??
Thanks!
I've had the same problem and this was my solution:
$conn = ftp_connect('my_ftp_host');
ftp_login($conn, 'my_user', 'my_password');
$path = '/';
// Get lists
$nlist = ftp_nlist($conn, $path);
$rawlist = ftp_rawlist($conn, $path);
$ftp_dirs = array();
for ($i = 0; $i < count($nlist) - 1; $i++)
{
if($rawlist[$i][0] == 'd')
{
$ftp_dirs[] = $nlist[$i];
}
}
I know the above code could be optimised and do just one FTP request instead of two but for my purposes this did the work.
For anyone looking for a cleaner solution, I've found a script to parse ftp_rawlist in this LINK:
Function
function parse_ftp_rawlist($List, $Win = FALSE)
{
$Output = array();
$i = 0;
if ($Win) {
foreach ($List as $Current) {
ereg('([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)', $Current, $Split);
if (is_array($Split)) {
if ($Split[3] < 70) {
$Split[3] += 2000;
}
else {
$Split[3] += 1900;
}
$Output[$i]['isdir'] = ($Split[7] == '');
$Output[$i]['size'] = $Split[7];
$Output[$i]['month'] = $Split[1];
$Output[$i]['day'] = $Split[2];
$Output[$i]['time/year'] = $Split[3];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : false;
}
else {
foreach ($List as $Current) {
$Split = preg_split('[ ]', $Current, 9, PREG_SPLIT_NO_EMPTY);
if ($Split[0] != 'total') {
$Output[$i]['isdir'] = ($Split[0] {0} === 'd');
$Output[$i]['perms'] = $Split[0];
$Output[$i]['number'] = $Split[1];
$Output[$i]['owner'] = $Split[2];
$Output[$i]['group'] = $Split[3];
$Output[$i]['size'] = $Split[4];
$Output[$i]['month'] = $Split[5];
$Output[$i]['day'] = $Split[6];
$Output[$i]['time/year'] = $Split[7];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : FALSE;
}
}
Usage
// connect to ftp server
$res_ftp_stream = ftp_connect('my_server_ip');
// login with username/password
$login_result = ftp_login($res_ftp_stream, 'my_user_name', 'my_password');
// get the file list for curent directory
$buff = ftp_rawlist($res_ftp_stream, '/');
// parse ftp_rawlist output
$result = parse_ftp_rawlist($buff, false);
// dump result
var_dump($result);
// close ftp connection
ftp_close($res_ftp_stream);

Creating thumbnail images while uploading multiple images with php

I'm using PHP/MySQL to upload multiple images for photo album. The information associated with the images (filenames, extensions, descriptions etc.) is stored in database as base64 encoded data. I'm also able to edit the album images. My problem now is that I also want to create thumbnails for each of the images when uploading them on insert and edit mode and also store the information for the thumbnails the same way I do for the images (base64 encoded). What's the best way to do that? Thanks
Here's my code:
<?php
//Code for the editing albums in database
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
//select photo album and get photos and descriptions to be merged with new.
$album_id = $_REQUEST['album_id'];
$old_photos = null;
$old_descriptions = null;
$getAlbumQ = mysql_query("select * from albums where id='$album_id'");
while ($old_album = mysql_fetch_array($getAlbumQ)) {
$old_photos = unserialize(base64_decode($old_album['photos']));
$old_descriptions = unserialize(base64_decode($old_album['descriptions']));
$old_timestamp=$old_album['timestamp'];
}
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = mysql_real_escape_string($_POST['album_name']);
$desc = mysql_real_escape_string($_POST['desc']);
$idesc = array();
$target_path = "/uploads/albums/";
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k === 'name' && $v !== '') {
break;
} else {
unset($_FILES[$key]);
}
}
//first upload photos
$path = $target_path . basename($old_timestamp.$value['name']);
if(move_uploaded_file($value['tmp_name'], $path)) {
$hasUpload = true;
}
}
for ($j = 1; $j < 21; $j++) {
$img_index = $j;
$img_desc = $_POST['desc_' . $img_index];
array_push($idesc, $img_desc);
}
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k=='name' && $v!='') {
break;
} else {
unset($_FILES[$key]);
}
}
}
function merge(&$a, &$b){
$keys = array_keys($a);
foreach($keys as $key){
if(isset($b[$key])){
if(is_array($a[$key]) and is_array($b[$key])){
merge($a[$key],$b[$key]);
}
else{
$a[$key] = $b[$key];
}
}
}
$keys = array_keys($b);
foreach($keys as $key){
if(!isset($a[$key])){
$a[$key] = $b[$key];
}
}
}
for ($i = 1; $i < 21; $i++) {
$file_index = $i;
$file_number = $_POST['image_' . $file_index];
if($_FILES['image_'.$i]['name']!= ''){
$hasUpload = true;
$presults = merge($old_photos, $_FILES);
$dresults = array_merge($old_descriptions, $idesc);
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
else {
$hasUpload = false;
$presults = $old_photos;
$dresults = $idesc;
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
}
}
if (mysql_query("update albums set description = '$desc', name = '$name', photos='$images', descriptions='$descriptions' where id='$album_id'")) {
$hasAlbums = true;
} else {
$hasErrors = true;
}
} else {
//Code for the inserting albums in database
if (isset($_POST['album_name'])) {
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = mysql_real_escape_string($_POST['album_name']);
$desc = mysql_real_escape_string($_POST['desc']);
$idesc = array();
$timestamp = time();
$target_path = "/uploads/albums/";
foreach ($_FILES as $k => $v) {
//first upload photos
$path = $target_path . basename($timestamp.$v['name']);
if(move_uploaded_file($v['tmp_name'], $path)) {
$img_index = explode('_', $k);
$img_index = $img_index[1];
$img_desc = $_POST['desc_' . $img_index];
array_push($idesc, $img_desc);
$file_name = $timestamp.$v['name'];
$hasUpload = true;
}
}
$images = base64_encode(serialize($_FILES));
$descriptions = base64_encode(serialize($idesc));
$posted = date("Y-m-d H:i:s");
$query = mysql_query("
INSERT INTO albums (description, posted, photos, name, descriptions, timestamp)
VALUES ('$desc', '$posted', '$images', '$name', '$descriptions', '$timestamp')
");
}
}
}
?>
I tried a simple thumbnail script found on this tutorial and it worked perfectly: http://net.tutsplus.com/articles/news/how-to-dynamically-create-thumbnails/
Thanks for your suggestions
You can use the Thumbnail class from
http://freecode.com/projects/easyphpthumbnailclass
You may use ImageMagick's resizeImage method.
explained in a tutorial here http://coffeeshopped.com/2009/01/creating-image-thumbnails-using-php-and-imagemagick
Also, you may try phpThumb() function and is available at sourceforge here http://phpthumb.sourceforge.net/
Hope this helps..

Select Random Distinct Images from a folder php

I want to select four random images from a folder which contains a number of images.
What i want to display is a table (2x2) where i can display 4 random distinct images.
Can someone tell me how can i select random distinct files from a folder so that i can store their path in a variable and then can use these variables to display images randomly in the table!
Is there any particular function which can select random files from a folder or something like that?
Use glob() to get all files from directory.
Use array_rand() to get random entries from an array.
<?php
function get_imagess($root) {
$r = array();
$r = array();
$k = glob("$root/*");
shuffle($k);
foreach($k as $n) {
if (is_dir($n)) {
break;
//$r = array_merge($r, get_imagesss($n));
print_r("xxx");
} else {
$r[] = $n;
//print_r($n + "yeah");
}
}
return $r;
}
function get_images($root) {
$r = array();
$k = glob("$root/*");
shuffle($k);
$n = $k[0];
// foreach($k as $n) {
if (is_dir($n)) {
$r = array_merge($r, get_imagess($n));
} else {
$r[] = $n;
}
// }
return $r;
}
$files = get_images('.');
//print_r($files);
//break;
shuffle($files);
$true=true;
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$ass=0;
while($true)
{
$ass=$ass+1;
if($ass>100){$true=false;}
$imageInfo = pathinfo($files[0]);
if (isset( $extList[ strtolower( $imageInfo['extension'] ) ] )){
$temp = substr($files[0], -5);
$temp = strtolower($temp);
if( $temp == "p.jpg"){shuffle($files);} // checking if jpg has a preview file
else{ // no preview found
$true=false;
//print_r($temp);
}}
else
{
shuffle($files);
//print_r('bad' + $temp);
}
}
//print_r($files[0]);
echo '<HTML><meta HTTP-EQUIV="Refresh" CONTENT="5; URL=./ImageRotateMaybe.php"><img src="';
echo $files[0];
echo ' " width=100%>';
?>

Categories