Barcode image storing in local folder not working - php

I used barcode generation in my site. When I used it within HTML tags it's working fine.
<div class="barcode_img"><img src="<?php echo AT::getUrl(); ?>/barcode/image.php?code=code39&o=1&dpi=150&t=30&r=1&rot=0&text=TEST NAME WITH SPACE&f1=Arial.ttf&f2=10&a1=&a2=&a3=" class="barcode fr"/></div>
I need to get that image to store it in local folder called "media/barcode/". For that, I used the code below:
$valid_barcodename="testimage";
$barcodeurl = AT::getUrl() . "barcode/image.php?code=code39&o=1&dpi=150&t=30&r=1&rot=0&text=TEST NAME WITH SPACE&f1=Arial.ttf&f2=10&a1=&a2=&a3=";
$barcode_img = 'media/barcode/testing_' .$valid_barcodename . '.png';
file_put_contents($barcode_img, file_get_contents($barcodeurl));
The image stored in that folder is not empty. When I analyzed it I found, if I give the name "TEST NAME WITH SPACE" without space (TESTNAMEWITHSPACE), it works.
However if I give it with space it won't work. What is the issue?
Note: AT::getUrl() - used for get my base url.

Spaces have special meaning in URLs, so you have to encode them:
$text = urlencode("TEST NAME WITH SPACE")
$barcodeurl = AT::getUrl() . "barcode/image.php?code=code39&o=1&dpi=150&t=30&r=1&rot=0&text=". $text ."&f1=Arial.ttf&f2=10&a1=&a2=&a3=";
In the above code, $text now contains your text, encoded and ready to be used in your URL (you will notice the spaces have been replaced with %20 codes).

Note: If you're opening a URI with special characters, such as spaces,
you need to encode the URI with urlencode().
http://docs.php.net/file_get_contents
Alternatively, you can use cURL if enabled on your server.
function curl($url, $setopt = array(), $post = array())
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
if( ! empty($post))
{
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
if( ! empty($setopt))
{
foreach($setopt as $key => $value)
{
curl_setopt($curl, constant($key), $value);
}
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
Usage:
file_put_contents($barcode_img, curl($barcodeurl));

Related

File uploads using CURLFile fails in PHP7.4

I query an API to which I upload files but no files are uploaded when I post using PHP7.4, however, it works fine with PHP7.3.
Here's a snippet of my code:
public function upload($opts = array())
{
$files = array();
foreach($opts['files'] as $i => $file)
{
$files['files[' . $i . ']'] = new CURLFile($file);
}
unset($opts['files']);
$data = array_merge($files, array( "data" => json_encode($opts)));
$response = self::curlRequest( "https://api.example.com/", $data);
return $response;
}
public static function curlRequest($url, $data)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
curl_setopt($curl, CURLOPT_TIMEOUT, 300);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 300);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
So the upload function accepts a multidimensional array of values including an array of files with index 'files'. It iterates through the files, creating CURLFile objects then posts these along with the rest of the data to the API.
Using PHP7.4, the global variables $_REQUEST and $_FILES on the API server are always empty. With PHP7.3 these variables are populated with the sent data as expected.
On https://www.php.net/manual/en/migration74.new-features.php it states:
CURLFile now supports stream wrappers in addition to plain file names, if the extension has been built against libcurl >= 7.56.0.
Libcurl version is 7.58.
A related bug report has been submitted here https://bugs.php.net/bug.php?id=79013 regarding the Content-Length header missing resulting in no file uploads but it seems the PHP team thinks the problem is with the server, not PHP.
Does anyone has any idea how to upload files using PHP7.4?
Version PHP 7.4.4 fixed this issue. Seems it was indeed a bug.

curl, how to download files with special characters?

my downloading function:
public static function download($a)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $a);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
$a= curl_exec($curl);
curl_close($curl);
return $a;
}
and given this link:
http://example.com/x.txt
is works well. But with a special case:
http://example.com/fájl/név/with ékezetek.txt
then its a "400 - bad request." curl_errno is 22 then. How to download it then? urlencode is not OK since it encode the hostname itself.
EDIT: those url are given "outside", I have no influence of it!
cURL and file_get_contents does not work with URL containing special character (accented letters, quotes, ...)
Solution:
$data = file_get_contents(urlEncode('http://www.test.com/file/file_planta_1ª.jpg'));
function urlEncode($url)
{
$parts = parse_url($url);
$parts['path'] = implode('/', array_map('urlencode', explode('/', $parts['path'])));
return $parts['scheme'].'://'.$parts['host'].$parts['path'];
}
try to make a
base64_encode
of the data, and a
base64_decode
to get original data
Improved Andrey's answer.
One will get a better result using rawurlencode() function.
function fileUrlEncode($url)
{
$parts = parse_url($url);
$parts['path'] = implode('/', array_map('rawurlencode', explode('/', $parts['path'])));
return $parts['scheme'].'://'.$parts['host'].$parts['path'];
}

String replace data retrieved by curl

I have created a curl function that returns all the html on a page (along with cookies)
I want to strip out the information (will also be needing to remove scripts a links brought in)
Here is the code i have
<?php
/* gets the data from a URL */
function get_data($url) {
$ch = curl_init();
$timeout = 5;
$cookie_data =
implode(
"; ",
array_map(
function($k, $v) {
return "$k=$v";
},
array_keys($_COOKIE),
array_values($_COOKIE)
)
);
curl_setopt($ch, CURLOPT_COOKIE, $cookie_data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
preg_replace('/<meta (.*) \/>/i','', $data);
return $data;
}
echo get_data('http://go.etracc.net/l/25492/2013-12-04/374rh');
}
?>
Any help would be awesome!
You can use strip_tags with second parameter specifying which all tags you wish to keep.
http://www.php.net/strip_tags
Example from the doc: to keep a and p tags
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');

How to pass data containing special characters through curl

I cannot able to post data its contain the special characters through curl ,Any solution ?
first code is my curl function ,second code is my data need to pass
$communication_data_string = 'token='.json_encode(array(
"activityTypeId"=>12,
"activityId"=>5,
"userID"=> 10,
"partyID"=>20,
"message_area_name"=>("this is my test data with special cheractors&&!###$%$%%*)++")
)
);
echo(datPostingCURL($url, $communication_data_string));
?>
this seems to not returning anything if the messageData contains the special character's
Try urlencode
or
How about using the entity codes...
# = %40
& = %26
change the line
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
to
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($data_string));
the receive it in following way as you are not using any specific post variable
$data = urldecode(file_get_contents('php://input'));
Check the following code. I tested it in my local system. In my www director I created a folder named "test" for keeping the code. Then I created 2 files in that "test" folder. One file for sending the request and one for processing the request.
1. curl.php
<?php
function datPostingCURL($url, $data_string)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
$url = "http://localhost/test/curl_post.php";
$communication_data_string = 'token='.json_encode(array(
"activityTypeId"=>12,
"activityId"=>5,
"userID"=> 10,
"partyID"=>20,
"message_area_name"=>base64_encode("hai ..this is my test data .!###$%$%%*)++")
)
);
echo(datPostingCURL($url, $communication_data_string));
?>
2. curl_post.php
<?php
print_r(json_decode($_POST['token']));
$details = json_decode($_POST['token']); var_dump($details);
echo base64_decode($details->message_area_name);
?>
Note : While using special characters you should encode that string. I tried to convert it with htmlspecialchars(). But it didn't worked. So I used base64 encoding method here.

How can I upload a file that has spaces is its name with curl + php?

I'm using this code for uploading a file to my server, using HTTP POST:
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
"upload" => '#' . $filepath
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$curl_result = curl_exec($ch);
This code works when $filepath does not contain spaces. However, it is possible that it might. When I test a path with spaces, I get the curl error "failed creating formpost data".
The curl manual does not tell me what to do, all it gives me are unix filenames without spaces. I tried following http://curl.haxx.se/mail/archive-2006-01/0079.html like so, but it didn't help me either:
"upload" => '"#' . $filepath . '"'
"upload" => '#"' . $filepath . '"'
Anyone have an idea?
Current versions of cURL (and PHP-cURL) handle spaces in filenames with no problems. Older versions may have had bugs, I'm not sure. Check you're using reasonably recent versions.
I can confirm spaces in filenames are no problem at all under PHP 5.2.13 and libcurl/7.19.4 on Linux.
The error message you're getting is the same one as when PHP/cURL can't find a file. Odds are the problems are somewhere else in your code. Probably an issue of having under- or over-escaped the spaces in the filename but probably not an issue with cURL itself.
I'd suggest looking elsewhere in your code for the problem or producing a hard-coded example of the problem occurring (where $filename is being set in the PHP directly rather than read from elsewhere).
You need the realpath
$filepath = 'D:\7 habits copy.txt';
$url = 'http://www.speedyshare.com/upload.php?'.rand(10000000, 99999999);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
"upload" => '#' . realpath($filepath)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$curl_result = curl_exec($ch);
echo $curl_result;
Worked even on Windows. I'm pretty sure it will work on *NIX systems
I faced the same problem and I couldn't upgrade CURL on the system.
So I wrote a simple escape function that iterated on the string to replace the space character for the + sign, which is the traditional way to represent URLs with spaces.
For my surprise, it worked. :)
C++ code:
#include <algorithm>
#include <string>
std::string s = "";
std::replace(s.begin(), s.end(), ' ', '+');
You will need to escape the spaces. Not sure of the syntax you would use but maybe something like this:
'This is the file name with spaces.txt'
to
'This\ is\ the\ file\ name\ with\ spaces.txt'
again I'm not sure of the syntax it's just an example
or you might just need to add quotes to the file name, like this:
'This is the file name with spaces.txt'
Put the target file in a variable, such as 'while read', and pass the variable in the curl the command. Be sure the variable is in double quotes and curl will handle it.
For example:
curl -T /PATH/TO/YOUR/FILE/DIRECTORY/"$f"

Categories