I have created an uploaded script to receive the file sent to it using the CKeditor 5 simple upload adapter build. I have tested it with a standard upload filetype, using $_POST from a filetype field that I've adapted and it generates the correct json response for the editor to receive.
However, I am unsure how I actually detect the input from editor itself as it's not coming from an input field.
<?php
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Methods: PUT,GET,POST");
$uploadOk = 1;
$err = 0;
//getting the file
$mentionFilename = basename($_FILES["fileToUpload"]["name"]);
if ($mentionFilename == ""){
$err = 1;
}else{
//setting the uploaddir
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".<BR>";
$uploadOk = 1;
} else {
//echo "File is not an image.<BR>";
$err = 2;
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$err = 3;
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
//echo "Sorry, your file is too large.<BR>";
$err = 4;
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "pdf" ) {
//echo "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.<BR>";
$err = 5;
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk > 0) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<BR>";
} else {
//echo "Sorry, there was an error uploading your file.<BR>";
$err = 6;
$uploadOk = 0;
}
}
}
switch ($err){
case "1":
//no fileneame in submissions
$errMsg = "There appeared to be no filename in the submission";
break;
case "2":
//the file is not an image
$errMsg = "The file submitted was not a permitted image type.";
case "3":
//file exists
$errMsg = "The file already exists.";
break;
case "4":
//file is too large
$errMsg = "The filesize of the upload is too large.";
case "5":
//Wrong filetype
$errMsg = "The file had the wrong filetype";
case "6":
//Problem uploading file
$errMsg = "There was a problem uploading the file.";
default:
//file was uplaoded succesfully
break;
}
if ($uploadOk > 0){
//return success message
$returnArr = array(
"url" => $target_file
);
}else{
//return error message
$returnArr = array(
"error" => array(
"message" => $errMsg
)
);
}
//sending back the response
echo json_encode($returnArr);
?>
Related
this is the example of signup page. the error is"Notice: Array to string conversion in
C:\xampp\htdocs\sample\signup.php on line 96" what are the possible solutions.
here is the code........
<?php
$con = mysqli_connect('localhost','root') or die(mysqli_error());
mysqli_select_db($con,'kms') or die (mysqli_error());
if (isset($_POST['techno']) && isset($_FILES['profile_picture']))
{
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$psw_repeat = $_POST['psw_repeat'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$occupation = $_POST['occupation'];
$address = $_POST['address'];
$about = $_POST['about'];
$phonenumber = $_POST['phonenumber'];
$profile_picture = $_FILES['profile_picture'];
$q = "INSERT INTO user (firstname,middlename,lastname,email,password,dob,gender,occupation,address,about,phonenumber,profile_picture) values ('$firstname','$middlename','$lastname','$email','$password',$dob,'$gender','$occupation','$address','$about',$phonenumber,'$profile_picture')";
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["profile_picture"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["profile_picture"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["profile_picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
if($psw_repeat != $password)
{
echo("Password does not match");
}
mysqli_query($con,$q) or die(mysqli_error($con));
mysqli_close($con);
}
?>
in line number 96...the code is for inserting data into database...
i have googled this error....ut there is no solution
I have an app the uses an SFTP connection to download files. It was working correctly in PHP 5.6, not so much in PHP 7. The error I get is as follows:
PHP Warning: filesize(): stat failed for ssh2.sftp ...
My code is as follows:
public function retrieveFiles($downloadTargetFolder,$remoteFolder = '.') {
$fileCount = 0;
echo "\nSftpFetcher retrieveFiles\n";
$con = ssh2_connect($this->host,$this->port) or die("Couldn't connect\n");
if($this->pubKeyFile){
$isAuth = ssh2_auth_pubkey_file($con, $this->user, $this->pubKeyFile, $this->privKeyFile);
} else {
$isAuth = ssh2_auth_password($con, $this->user, $this->pass);
};
if ($isAuth) {
$sftp = ssh2_sftp($con);
$rd = "ssh2.sftp://{$sftp}{$remoteFolder}";
if (!$dir = opendir($rd)) {
echo "\nCould not open the remote directory\n";
} else {
$files = array();
while (false != ($file = readdir($dir))) {
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
if (is_array($files)) {
foreach ($files as $remoteFile) {
echo "\ncheck file: $remoteFile vs filter: " . $this->filter."\n";
if ($this->filter !== null && strpos($remoteFile,$this->filter) === false) {
continue;
}
echo "file matched\n";
$localFile = $downloadTargetFolder . DIRECTORY_SEPARATOR . basename($remoteFile);
//$result = ftp_get($con,$localFile,$remoteFile,FTP_BINARY);
$result = true;
// Remote stream
if (!$remoteStream = #fopen($rd."/".$remoteFile, 'r')) {
echo "Unable to open the remote file $remoteFolder/$remoteFile\n";
$return = false;
} else {
// Local stream
if (!$localStream = #fopen($localFile, 'w')) {
echo "Unable to open the local file $localFile\n";
$return = false;
} else {
// Write from our remote stream to our local stream
$read = 0;
$fileSize = filesize($rd."/".$remoteFile);
while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read))) {
$read += strlen($buffer);
if (fwrite($localStream, $buffer) === FALSE) {
echo "Unable to write the local file $localFile\n";
$return = false;
break;
}
}
echo "File retrieved";
// Close
fclose($localStream);
fclose($remoteStream);
}
}
if ($result) {
$fileCount++;
}
}
}
ssh2_exec($con, 'exit');
unset($con);
}
} else {
echo "Error authenticating the user ".$this->user."\n";
}
return $fileCount;
}
}
After some research I found there was an issue with stat():
http://dougal.gunters.org/blog/2016/01/18/wordpress-php7-and-updates-via-php-ssh2/
https://bugs.php.net/bug.php?id=71376
My question
Is there a workaround to allow me to download via SFTP given my current code or is there another library someone can recommend to use instead?
My PHP version:
PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS )
Quoting PHP ssh2.sftp opendir/readdir fix,
Instead of using "ssh2.sftp://$sftp" as a stream path, convert $sftp to an integer like so: "ssh2.sftp://" . intval($sftp) . "/". Then it will work just fine.
The reason for the change is as follows:
PHP 5.6.28 (and apparently 7.0.13) introduced a security fix to URL parsing, that caused the string interpolation of the $sftp resource handle to no-longer be recognized as a valid URL. In turn, that causes opendir(), readdir(), etc. to fail when you use an $sftp resource in the path string, after an upgrade to one of those PHP versions.
As for other libraries... only other library I'm aware of is phpseclib, which has an emulator of sorts for libssh2:
https://github.com/phpseclib/libssh2-compatibility-layer
That "emulator" could certainly be improved upon tho. Like a composer.json file ought to be added, etc.
I had the same issue with php 8.0.
Try putting the filesize command before the fopens.
I know how can I get the video duration and views, like that
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=hqepb5hzuB0&key={YOUR-API-KEY}");
$json_data = json_decode($JSON, true);
echo $json_data['items'][0]['statistics']['viewCount'];
But how can I get the video upload date?
$vidkey = "Gsc7_E5HewM" ; //for example
$apikey = "xxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
//----- duration---
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
// Check if $VidDuration is ISO string so the video is ready
if (is_string($VidDuration)){
//convert duration from ISO to M:S
$date = new DateTime('2000-01-01');
$date->add(new DateInterval($VidDuration));
$vid_durH= $date->format('H') ;
if ($vid_durH=="00") {
$vid_dur= $date->format('i:s') ;
}
else {
$vid_dur= $date->format('H:i:s') ;
}
}
else {
$vid_dur ="error" ;
}
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json_data = json_decode($JSON, true);
$uploadDate = $json_data['items'][0]['snippet']['publishedAt'];
$uploadDate = strtotime($uploadDate);
$uploadDate= date("F j, Y", $uploadDate);
echo $vid_dur ;
I have an old image captcha generator written in PHP4 that i need to convert to PHP5
Any suggestions for what I need to change to get it to start working? The main error I'm getting reads "Resource interpreted as Image but transferred with MIME type text/html" Which I already told it to have a MIME type of image throough the code below when I said header('Content-type: image/jpeg');
<?php
extract($HTTP_GET_VARS);
extract($HTTP_POST_VARS);
session_start();
$alphanum = "ABGKLMNPRSTUXZ";
$rand = substr(str_shuffle($alphanum), 0, 5);
$image = imagecreatetruecolor(65,25);
$background = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 128, 128, 128);
$colors[] = imagecolorallocate($image, 128, 64, 192);
$colors[] = imagecolorallocate($image, 192, 64, 128);
$colors[] = imagecolorallocate($image, 108, 192, 64);
imagefilledrectangle($image, 1, 1, 65 - 2, 25 - 2, $background);
imagerectangle($image, 0, 0, 65 - 1, 25 - 1, $border);
for ($i = 0; $i < 5; $i++){
$x1 = rand(0, 65 - 5);
$y1 = rand(0, 25 - 5);
$x2 = $x1 - 4 + rand(2, 8);
$y2 = $y1 - 4 + rand(2, 8);
imageline($image, $x1, $y1, $x2, $y2,$colors[rand(0, count($colors) - 1)]);
}
$textColor = imagecolorallocate ($image, 30, 30, 30);
imagestring ($image, 8, rand(8,10), rand(1,8), $rand, $textColor);
$_SESSION['image_random_value'] = md5($rand);
header("Expires: Mon, 26 Jul 1998 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
?>
This image loads into the page here if its at all helpful:
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
else
countfield.value = maxlimit - field.value.length;
}
function form_visible(){
var el = document.getElementById('sf');
if(el.style.display == 'inline'){
el.style.display = 'none';
}else{
el.style.display = 'inline';
}
}
var shows = 0;
var lc;
var i;
var image;
var ny;
function show(star_img,rnid)
{
if (shows){
if(rnid==lc){
return;
}
}
for (i=1; i");
for (var i=1; i");
}
document.write("Please Select");
}
$value) {
${$key} = $value;
}
foreach($_POST AS $key => $value) {
${$key} = $value;
}
$db=mysql_connect($db_host,$database_user,$database_pass) or die("MySQL Error: Unable to connect to database please check that you have provided the correct Database Login usernameDatabase Login Password");
mysql_select_db($db_name,$db)or die("MySQL Error: Unable to select database please check that you have provided the correct Database name");
echo "";
$day =date("D d");
$month =date("M");
$year =date("Y");
$dt="$year-$month-$day";
$ent=mysql_query("SELECT * FROM ez_ccomment_opt");
$rowi=#mysql_fetch_array($ent);
if($do=="do_sign" && $id=="$mid"){
if ($comment !="" && $email !="" && $name !="" && $rating!=""){
if(md5($_POST['security']) == $_SESSION['image_random_value']){
$comment = str_replace ("",">", $comment);
$name = str_replace ("",">", $name);
$email = str_replace ("",">", $email);
$website = str_replace ("", $comment);
$comment = str_replace ("", "", $comment);
$name = stripslashes ($name);
$comment = stripslashes ($comment);
$lis="0";
if($rowi[filter]=="y"){
$user=file("badwords.txt");
for($x=0;$xPlease enter valid security image.";
}
}else{
$w="1";
echo "Please fill in the required fields.";}
}
ob_start();
echo "";
echo "Rating*";
?>
showform(1);
";
echo "Comments*
Name*
Email* (Will not be shown)
Security Image*make sure to type security image in ALL CAPITAL characters!
* = Required";
echo "";
ob_end_flush();
if($w=="1"){
?>
var el = document.getElementById('sf');
el.style.display = 'inline';
";
$list = ("SELECT * FROM ez_ccomment WHERE status='confirmed' AND ccid='$id' ORDER BY op DESC");
$row_num1= #mysql_num_rows(mysql_query($list));
$list_per_page=$rowi['limit_pp'];
if($row_num1>0){
echo "Comments";
}else{
echo "No ratings yet. Be the first to add a rating!";
}
if($start==""){
$start=1;
}
if($start==""||$start==1){
$sfrom=0;
}else{
$sfrom=(($start-1)*$list_per_page);
}
$end=$list_per_page;
$gr=0;
$list.= (" LIMIT $sfrom,$end");
$blist=(mysql_query($list));
while($row=#mysql_fetch_array($blist)){
if(substr_count($row[email],"#")==1){
$name="$row[name]";
}else{
$name="$row[name]";
}
$messag=$row[message];
$messag=wordwrap($messag, 55, "\n", 1);
$row[rating]=round($row[rating],2);
if ($row[rating] == 5)
{
$star = "images/5star.gif" ;
$pk="5 - Excellent!";
}
if ($row[rating]>=1 && $row[rating]=2 && $row[rating]=3 && $row[rating]= 4 && $row[rating]= 5)
{
$star = "images/5star.gif" ;
$pk="5 - Excellent!";
}
if ($row[rating] $messag$row[name], $row[date]";
$gr+=1;
}
$list_per_page=$rowi['limit_pp'];
echo "";
if($start==""){
$start=1;
}
if($start==""||$start==1){
$sfrom=0;
}else{
$sfrom=(($start-1)*$list_per_page);
}
$end=$list_per_page;
if ($row_num1>$list_per_page){
$no_of_page=$row_num1/$list_per_page;
$no_page=explode(".",$no_of_page);
if($no_page[1]>0){
$no_of_page+=1;
}
echo "";
echo "";
if($start > 1){
$s=$start-1;
echo "Previous";
}
echo "";
$last=round($no_of_page,0);
for($i=1;$i$i ";
}else{
echo " $i ";
}
}else{
if($i>$start+3){
if($once==""){
echo " ....... $last";
}
$once="yes";
}elseif($i0){
echo "1 ....... ";
}
$tonce="yes";
}else{
if($i!=$start){
echo " $i ";
}else{
echo " $i ";
}
}
}
}
echo "";
if($start Next";
}elseif($start>=$i){
$next = "";
}
echo "$next";
}
echo "";
?>
In that code, just change $HTTP_GET_VARS for $_GET and $HTTP_POST_VARS for $_POST
extract($_GET);
extract($_POST);
I tried it and it works.
I am able to upload my images ok, I am able to create thumbnails ok, but only the first thumbnail is being uploaded. I checked the error code for the resize function and they all say 'true' (Success). However, if I upload 4 files, only the first is being uploaded to the thumbnail folder. Here is my code:
function _upload_them_images($_FILES, $last_insert_id)
{
$error = '';
// for($i=0; $i<count($_FILES); $i++)
for($i=0; $i<count($_FILES['imagefile']['name']); $i++)
{
$_FILES['userfile']['name'] = $_FILES['imagefile']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['imagefile']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['imagefile']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['imagefile']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['imagefile']['size'][$i];
$config['file_name'] = $last_insert_id.'_'.time().rand(1000,9999).$i;
$config['upload_path'] = './images/vehicles/';
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = '1000';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
if($this->upload->do_upload())
{
$upload_result = $this->upload->data();
$rc = $this->_image_name_into_database(
$last_insert_id,
$upload_result['file_name']);
$image_config = array(
'source_image' =>$upload_result['full_path'],
'new_image' => './images/vehicles/thumbs/',
'create_thumb' => TRUE,
'maintain_ratio' => TRUE,
'width' => 75,
'height' => 50
);
$this->load->library('image_lib', $image_config);
$resize_rc = $this->image_lib->resize();
$error += 0;
}
else
{
//if the image was not uploaded successfully, try resizing
$error += 1;
}
}
if($error > 0)
{
return FALSE;
}
else
{
return TRUE;
}
}
Your image library parameters aren't being updated in the loop. When you call $this->load->...., duplicate items are ignored. You should instead re-initialize the image library with:
$this->image_lib->clear();
$this->image_lib->initialize($image_config);
Before each ->resize()