PHP / Laravel - Tesseract OCR - Full path to file - php

I have successfully installed tesseract OCR and Imagick on my Forge server. However when I try to read an image, I get below error:
This is the error:
Error! The image "/home/forge/domain.com/storage/app/temp_files/ocrtotext_ijP1II9th2.jpeg" was not found.
The current __DIR__ is /home/forge/domain.com/vendor/thiagoalessio/tesseract_ocr/src
This is my code:
$text = (new TesseractOCR(storage_path() . '/app/temp_files/'.$imageName.'.jpeg'))
->lang('eng')
->psm($psm)
->run();
return $text;
What am I doing wrong? Why is tesseract looking in the /vendor/ folder and not in my storage/.. folder?

If you check the code at https://github.com/thiagoalessio/tesseract-ocr-for-php/blob/ea31d13143683c1b76e622f2b76be4c3e2e6c1af/src/FriendlyErrors.php
You'll see:
public static function checkImagePath($image)
{
if (file_exists($image)) return;
$currentDir = __DIR__;
$msg = array();
$msg[] = "Error! The image \"$image\" was not found.";
$msg[] = '';
$msg[] = "The current __DIR__ is $currentDir";
$msg = join(PHP_EOL, $msg);
throw new ImageNotFoundException($msg);
}
As you can see, TesseractOCR use the function file_exists
This function is returning false, which means that you setted the wrong filepath, or it's a broken symlink, or the user (Apache?) doesn't have access to the file, or other reason.

Related

PHP SSH move file to another directory [duplicate]

I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'

uploading binary file to server

I'm converting an image to a binary file in IOS, which works just fine. This will be handled by my php script which is suppose to upload this image to my ubuntu server. The problem is i keep getting file=unsuccessful. i've tried different directory paths, but cant seem to solve this issue.
This $directory will return this: /var/www/User/core/ios/
<?
if(!empty($_POST))
{
$message = $_POST['message'];
$directory = $_SERVER['DOCUMENT_ROOT'] . '/User/core/ios/';
$file = basename($_FILES['userfle']['upload']);
$uploadfile = $directory . $file;
var_dump($_FILES);
$randomPhotoID = md5(rand() * time());
echo 'file='.$file;
echo $file;
if (move_uploaded_file($_FILES['userfle']['tmp_name'], $uploadfile)) {
echo 'successful';
}
else
{
echo 'unsuccessful';
}
}
else
{
echo('Empty post data');
}
?>
Check the error file of your php(you can make sure if you enabled the error log in php.ini),
if you don't have the permission or for some other reasons it can't move the file ,there will be a record in that file.
Some time you can try the command setenforce 0 if you confirm you(I means the user of apache) have the permission to move the file but it not work.
By the way if the file you want to move is not upload by post, there is no error log and the move function will return false.

PHP image wrong mimetype

I'm uploading images from my Android app to my server. The app uses the android camera intent and upload via PHP script is ok.
I want to verify if the uploaded files are real images, I'm not checking the extension but the mimetype (I suppose this is the best way to do it, tell me if I'm wrong).
I'm using a Slackware Linux Apache server and I'm trying this code:
....
$finfo = finfo_open(FILEINFO_MIME, '/etc/httpd/magic');
....
fwrite($fp, finfo_file($finfo, "file.jpg"));
....
But I'm getting "application/octet-stream; charset=binary" instead of "image/jpeg; charset=binary" which is given from "file -i file.jpg" (shell command).
What's the problem?
Solved using $finfo = finfo_open(FILEINFO_MIME); instead of the other line. I think the default magic file is not the same that I was specifing.
As refered on www.php.net/manual/en/ref.fileinfo.php:
<?php
function is_jpg($fullpathtoimage){
if(file_exists($fullpathtoimage)){
exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
//using system() echos STDOUT automatically
if(!empty($out)){
//identify returns an empty result to php
//if the file is not an image
if($out == 'JPEG'){
return true;
}
}
}
return false;
}
?>
Alternately, if you've got execution rights and want to use a "hacky" solution, you can simply do what you've already done (using file -i path with shell_exec):
<?php
function shell_get_mime_type($path) {
if (is_readable($path)) {
$command = 'file -i "' . realpath($path) . '"';
$shellOutput = trim(shell_exec($command));
//eg. "nav_item.png: image/png; charset=binary"
if (!empty($shellOutput)) {
$colonPosition = strpos($shellOutput, ':');
if ($colonPosition !== false) {
return rtrim(substr($shellOutput, $colonPosition + 1));
}
return $shellOutput;
}
}
return false;
}
?>
Try to use function mime_content_type().

PHP error on file upload

I keep recieving a PHP error, "Call to undefined function getallheaders() in /home/jbird11/public_html/grids/upload.php on line 8"
The upload script basically takes an image that is dragged into an area, and uploads it. When I drag the image, I get this message.
Here is the first 40 or so lines of the php file:
<?php
// Maximum file size
$maxsize = 1024; //Kb
// Supporting image file types
$types = Array('image/png','images/gif','image/jpeg');
$headers = getallheaders();
// LOG
$log = '=== '. #date('Y-m-d H:i:s') . ' ========================================'."\n"
.'HEADER:'.print_r($headers,1)."\n"
.'GET:'.print_r($_GET,1)."\n"
.'POST:'.print_r($_POST,1)."\n"
.'REQUEST:'.print_r($_REQUEST,1)."\n"
.'FILES:'.print_r($_FILES,1)."\n";
$fp = fopen('log.txt','a');
fwrite($fp, $log);
fclose($fp);
header('content-type: plain/text');
// File size control
if($headers['X-File-Size'] > ($maxsize *1024)) {
die("Max file size: $maxsize Kb");
}
// File type control
if(in_array($headers['X-File-Type'],$types)){
// Create an unique file name
$filename = sha1(#date('U').'-'.$headers['X-File-Name']).'.'.$_GET['type'];
// Uploaded file source
$source = file_get_contents('php://input');
// Image resize
imageresize($source, $filename, $_GET['width'], $_GET['height'], $_GET['crop'], $_GET['quality']);
} else die("Unsupported file type: ".$headers['X-File-Type']);
// File path
$path = str_replace('upload.php','',$_SERVER['SCRIPT_NAME']);
// Image tag
echo '<img src="'.$path.$filename.'" alt="image" />';
Any idea what is causing this error? Permissions perhaps? Permission are set to 755. You can see a working demo of this here: http://pixelcakecreative.com/grids/
Any idea how to fix this? Thanks in advance
From the docs:
This function is an alias for apache_request_headers(). Please read the apache_request_headers() documentation for more information on how this function works.
If you're not using apache (with php as a module), this function is not available.
It's an apache related function. Maybe You don't have needed extensions installed?
from the hosting company: It appears that that function is only supported when PHP is run as an Apache module. Our Shared and Reseller servers run PHP as CGI, and unfortunately this cannot be changed. We apologize for any inconvenience.
If that function is absolutely required for your site, you will need to consider upgrading to a VPS, in which case PHP can be installed however you like.
you can use this code to be sure you have such a function not depending on server software configuration:
if (!function_exists("getallheaders"))
{
function getallheaders()
{
$headers = "";
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == "HTTP_")
{
$headers[str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($name, 5)))))] = $value;
}
}
return $headers;
}
}

MootoolsFancy Upload

i have just come across what i think i need for my front end multi uploader script in joomla.
Mootools fancy upload looks great! but i am having trouble when i uncomment the script that uploads the images inside the uploads folder?
All i have done is uncommented the default script inside the test file and created a folder called uploads which i set to 757 and also tried 777
But for some reason the uploader now returns some strange error about md 5 hash stuff?
eastern_beach_jetty.jpgAn error occured:
Warning: md5_file(/tmp/phpUjHol4) [function.md5-file]: failed to open stream: No such file or directory in /home/user/www.mydomain.com.au/test/server/script.php on line 133
{"status":"1","name":"eastern_beach_jetty.jpg","hash":false}
The fancy uploader website from where i got the script is here http://digitarald.de/project/fancyupload/
Any help on this would be so greatly apprecited,
thank you.
John
Coincidentally, I did the same mistake as you, the reason is that the first move tmp file to the destination folder, and then referring to the tmp file, which no longer exists, because it is in the target folder. I know that the late response, but it was as if someone had the same problem.
Not:
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
Yes:
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];

Categories