PHP calling Python with Base64 image data fails - php

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

Related

file_put_contents multiple image upload through API in 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;

PHP file unable to extract and split image from database after made changes to the file

I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.

I want to write a function that opens a series of files and copies some of the data into an array

I want to write a function as a lot of this code is repeated but I am having trouble passing the name of the file and the mode as a parameter to the function.
name = array();
dob = array();
address = array();
data = array();
#get name data
$handle = fopen('data/name.txt', 'r');
while (!feof($handle)) {
$data = explode(':',fgets($handle, 1024));
$name[] = $data[1];
}
fclose($handle);
#get dob data
$handle = fopen('data/dob.txt', 'r');
while (!feof($handle)) {
$data = explode(':',fgets($handle, 1024));
$dob[] = $data[1];
}
fclose($handle);
#get address data
$handle = fopen('data/address.txt', 'r');
while (!feof($handle)) {
$data = explode(':',fgets($handle, 1024));
$address[] = $data[1];
}
fclose($handle);
This is what I've written so far as a function.
function get_data($file, $mode, $array) {
$handle = fopen("'" . $file . "'", "'" . $mode . "'");
while (!feof($handle)) {
$data = explode(':',fgets($handle, 1024));
$array[] = $data[0];
}
So I want to be able to call the function on each file, such as;
get_data ('data/name.txt' , 'r', $name);
Your function is almost correct :) Just two mistakes
You didn't call fclose() inside your function
You tried to enclose a string twice, where one is enough
function get_data($file, $mode, $array) {
$handle = fopen("'" . $file . "'", "'" . $mode . "'");
# /\ these /\ and these are unnecessary
while (!feof($handle)) {
$data = explode(':',fgets($handle, 1024));
$array[] = $data[0];
}
Just calling fopen($file, $mode) is ok :)
If you would like to use your $array variable outside of your function, please remember to return it. If you add return $array; to the end of your function, you will be able to go:
$result = get_data('file.txt', 'r');
PS: There is already a similar function in PHP, file_get_contents(), perhaps you could use it? :)

find the last created image file with remote or external link

HI guys i have some jpeg files with this format:
123-1.jpeg ,123-2.jpeg ,123-3.jpeg ,123-4.jpeg ....
This files located on my VPS and i need to find and show the lasted file by remote (my means external web link ).
i have problem how i can read files with such name format i tried this is not work:
$screnshot_url = "http://8.7.6.5/screenshots/123-*.jpeg ";
$filemtime = filemtime_remote($screnshot_url);
$files = $screnshot_url;
$files = array_combine($files, array_map($filemtime, $files));
arsort($files);
$img = key($files);
function filemtime_remote($uri)
{
$uri = parse_url($uri);
$handle = #fsockopen($uri['host'],80);
if(!$handle)
return 0;
fputs($handle,"GET $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
$result = 0;
while(!feof($handle))
{
$line = fgets($handle,1024);
if(!trim($line))
break;
$col = strpos($line,':');
if($col !== false)
{
$header = trim(substr($line,0,$col));
$value = trim(substr($line,$col+1));
if(strtolower($header) == 'last-modified')
{
$result = strtotime($value);
break;
}
}
}
fclose($handle);
return $result;
}

PHP program will run and echo out nothing

I made a script that reads data from a .xls file and converts it into a .csv, then I have a script that takes the .csv and puts it in an array, and then I have a script with a foreach loop and at the end should echo out the end variable, but it echos out nothing, just a blank page. The file writes okay, and that's for sure, but I don't know if the script read the csv, because if I put an echo after it reads, it just returns blank.
Here my code:
<?php
ini_set('memory_limit', '300M');
$username = 'test';
function convert($in) {
require_once 'Excel/reader.php';
$excel = new Spreadsheet_Excel_Reader();
$excel->setOutputEncoding('CP1251');
$excel->read($in);
$x=1;
$sep = ",";
ob_start();
while($x<=$excel->sheets[0]['numRows']) {
$y=1;
$row="";
while($y<=$excel->sheets[0]['numCols']) {
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
$row.=($row=="")?"\"".$cell."\"":"".$sep."\"".$cell."\"";
$y++;
}
echo $row."\n";
$x++;
}
return ob_get_contents();
ob_end_clean();
}
$csv = convert('usage.xls');
$file = $username . '.csv';
$fh = fopen($file, 'w') or die("Can't open the file");
$stringData = $csv;
fwrite($fh, $stringData);
fclose($fh);
$maxlinelength = 1000;
$fh = fopen($file);
$firstline = fgetcsv($fh, $maxlinelength);
$cols = count($firstline);
$row = 0;
$inventory = array();
while (($nextline = fgetcsv($fh, $maxlinelength)) !== FALSE )
{
for ( $i = 0; $i < $cols; ++$i )
{
$inventory[$firstline[$i]][$row] = $nextline[$i];
}
++$row;
}
fclose($fh);
$arr = $inventory['Category'];
$texts = 0;
$num2 = 0;
foreach($inventory['Category'] as $key => $value) {
$val = $value;
if (is_object($value)) { echo 'true'; }
if ($value == 'Messages ') {
$texts++;
}
}
echo 'You have used ' . $texts . ' text messages';
?>
Once you return. you cannot do anything else in the function:
return ob_get_contents();
ob_end_clean();//THIS NEVER HAPPENS
Therefore the ob what never flushed and won't have any output.
I see a lot of repetitive useless operations there. Why not simply build an array with the data you're pulling out of the Excel file? You can then write out that array with fputcsv(), instead of building the CSV string yourself.
You then write the csv out to a file, then read the file back in and process it back into an array. Which begs the question... why? You've already got the raw individual bits of data at the moment you read from the excel file, so why all the fancy-ish giftwrapping only to tear it all apart again?

Categories