I'm trying to implement reCAPTCHA in my website, everything seems working fine, except the return from file_get_contents().
Here is my code:
if ($_REQUEST["send"] == 1){
// access
$secretKey = 'my_key';
$captcha = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
echo ($responseKeys);exit;
if(intval($responseKeys["success"]) !== 1) {
$message = 'Invalid reCAPTCHA';
} else {
$msg = 'content';
send_mail('send_to',"Subject",$msg);
header("location:index.php?send=1");exit;
}
}
My variable response is returning empty.
I tried to open https://www.google.com/recaptcha/api/siteverify? inserting manually the variables and it seems to work fine.
Am I forgeting something?
Thanks
Their API waiting for a POST request. Your code send GET request.
See answer here How to post data in PHP using file_get_contents?
My wrappers were disabled, reason why I couldn't reach the URL and get the return.
As I don't have access to php.ini the workaround was send the request with curl, here is the code:
$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$response = '';
} else {
curl_close($ch);
}
if (!is_string($response) || !strlen($response)) {
echo "Failed to get contents.";
$contents = '';
}
$responseKeys = json_decode($response,true);
i am totaly new to CURL thing . i have a problem .
i have the below script which supposed to get remote files using a proxy , i am trying this code on my local host machine and it is working great "done successfully part: .
when i run it from server , it just keep going to the "invalid proxy" although it is same proxy as used in the local host ..
<?php
$dots = '';
include($dots.'classes/config.php');
$wordsLimitPerCall = 1;
$maxAttemptsTrials = 3;
$timeout = 10; // Seconds
$proxy = sqlSelectRow('proxy', array(
'condition'=>'not_valid=0',
'order'=>'rand()'
));
echo '<ul>';
if($proxy)
echo '<li>Using proxy: '.$proxy['proxy'].':'.$proxy['port'].'</li>';
$wordsRes = sqlSelectRows('words', array(
'condition'=>'is_done=0 and trials<'.$maxAttemptsTrials,
'limit'=>$wordsLimitPerCall,
'order'=>'created asc'
));
while($arr = $wordsRes->fetch_assoc()) {
$word = urlencode($arr['word']);
$url = 'http://example.com'.$word;
$callSettings = array(
'method'=>'curl',
'timeout'=>$timeout
);
if($proxy)
$callSettings['proxy'] = $proxy['proxy'].':'.$proxy['port'];
$result = callRemoteURL($url, $callSettings);
$filename = urldecode($word);
$filename = 'file/'.$arr['id'].' - '.$filename.'.mp3';
echo '<li>Getting the word: '.$word.'</li>';
if($result && strpos($result, '<html')===false) {
if(file_exists($dots.$filename))
unlink($dots.$filename);
fileWrite($filename, $result);
$is_done = 1;
echo '<li>done successfully</li>';
}
else {
$is_done = 0;
if($proxy) {
sqlUpdate('proxy', array(
'not_valid'=>0
), array(
'condition'=>'id='.$proxy['id']
));
echo '<li>Proxy is not valid</li>';
}
}
sqlUpdate('words', array(
'trials'=>$arr['trials']+1,
'path'=>$url,
'last_call_date'=>date('Y-m-d H:i:s'),
'is_done'=>$is_done
), array(
'condition'=>'id='.$arr['id']
));
}
echo '</ul>'; ?>
below the function called from utils
<? php
if($set['method']=='curl' && extension_loaded('curl'))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, $set['timeout']); // Seconds
if($set['proxy'])
curl_setopt($ch, CURLOPT_PROXY, $set['proxy']);
ob_start();
if(curl_exec($ch) === false)
{
$errorNo = curl_errno($ch);
if($errorNo==28)
print_r('The connection took time more than '. $set['timeout'].' seconds, so we disconnected the process');
else
if($errorNo!=7)
print_r(curl_error($ch));
$result=false;
}
else
{
$result = ob_get_contents();
}
ob_end_clean();
return $result;
}
?>
sorry if its too long ... but i've spent the last couple days tryng to find out . any idea or what shall i do ?
i am trying to get data from a url using curl. i've made a recursive function for this. i get the data successfully , but the problem what i am facing is that when no result is found against curl call, then the page show me nothing, only a blank page is shown.. no error at all. i've used var_dump() too for testing the response. but found nothing.
here is my recursive function
function recursive_get_scrap($offset, $page_size, $urls, $original_array){
ini_set('max_execution_time', 1800);
$of_set = $offset;
$pg_size = $page_size;
$off_sets = 'offset='.$of_set.'&page_size='.$pg_size.'';
$url = $urls.$off_sets;
$last_correct_array = $original_array;
$ch1 = curl_init();
// Disable SSL verification
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch1, CURLOPT_URL,$url);
// Execute
$result2 = curl_exec($ch1);
$info = curl_getinfo($ch1);
if(curl_errno($ch1))
{
echo 'error:' . curl_error($ch1);
//return $last_correct_array;
}
// Closing
curl_close($ch1);
if(!$result2 || strlen(trim($result2)) == 0 || $result2 == false){
echo 'no array';
}
if(isset($result2) && !empty($result2)){
echo 'in recursive function <br>';
$a1 = json_decode( $original_array, true );
$a2 = json_decode( $result2, true );
$temp_array = array_merge_recursive($a1, $a2 );
$last_correct_array = $temp_array;
$offset += 100;
$page_size = 100;
recursive_get_scrap($offset, $page_size, $urls, json_encode($last_correct_array));
}
}
now what i only want it that if noting is get against curl call then no array message should be displayed.
Use this option to curl_setopt():
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This will make curl_exec return the data instead of outputting it.
To see if it was successful you can then check $result and also
curl_error().
I am pulling some content in to a text file and than using curl or file_get_contents to display it
Here it works perfectly fine
http://www.dev.phosting.eu/
but here
it returns 404
http://dev5.gozenhost.com/index.php/shortcodes/114-testing
and the file is accessible
http://dev5.gozenhost.com/media/plg_system_yjsg/yjsgparsed/raw-githubusercontent-com/yjsgframework/demo-docs/master/shortcodes/Icons.txt
$getContent returns the accessible link above , and this is curl.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getContent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (empty($data)) {
$content = 'Error processing url. ' . $httpCode;
} else if ($httpCode >= 200 && $httpCode < 300) {
if ($local) {
$content = $data;
} else {
$content = yjsg_clean_html($data);
JFile::write($filepath, $content);
}
} else {
$content = 'Error processing url.' . $httpCode;
}
I mean all files are in the right places , and accessible
Funny thing is if I use curl or file_get_contents to access someone else site it works fine , if I am accessing file on my own domain it fails. Again only on cloudlinux.
Does anyone know what the issue is and possible fix .
Thank you!
i'm buidling a php script to upload larges files from a local php server to a distant ftp server with log of progress in a mysql base. Evrything work fine, but i get problem with the resume function and i can't find any clear information of the process to follow to resume an ftp upload with curl. my code bellow :
$fp = fopen($localfile, 'r');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_NOPROGRESS, false);
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, 'curlProgressCallback'); // lof progress to base
curl_setopt($curl, CURLOPT_READFUNCTION, 'curlAbortCallback'); // check if user request abort
curl_setopt($curl, CURLOPT_URL, $ftp);
curl_setopt($curl, CURLOPT_PORT, FTPPort);
curl_setopt($curl, CURLOPT_LOW_SPEED_LIMIT, 1000);
curl_setopt($curl, CURLOPT_LOW_SPEED_TIME, 20);
curl_setopt($curl, CURLOPT_USERPWD, FTPLog . ":" . FTPPass);
curl_setopt($curl, CURLOPT_FTP_CREATE_MISSING_DIRS, true);
curl_setopt($curl, CURLOPT_UPLOAD, 1);
if($resume){
$startFrom=ftpFileSize($dest); // return the actual file size on the ftp server
}else{
$startFrom=false;
}
if($startFrom){
curl_setopt ($curl, CURLOPT_FTPAPPEND, 1);
curl_setopt($curl, CURLOPT_RESUME_FROM, $startFrom);
fseek($fp, $startFrom, SEEK_SET);
$sizeToUp=filesize($localfile);//-$startFrom;
}else{
$sizeToUp=filesize($localfile);
}
curl_setopt($curl, CURLOPT_INFILE, $fp);
curl_setopt($curl, CURLOPT_INFILESIZE, $sizeToUp);
curl_exec($curl);
If someone call help me on this or redirect me on a valid example it will be very helfull and appreciate.
Tks for your feedback
Mr
I do not think cURL & PHP can do this.
Are you using Linux? If so look at aria2. It supports resumable connections and supports FTP. I am not sure if it will do exactly what you want.
So i've abort my research to make resume with curl, not enought help or documentation on it,
And it's really more easy to do it with ftp_nb_put. So i f its can help someone, you can find a exemple of my final code bellow :
define("FTPAdd","your serveur ftp address");
define("FTPPort",21);
define("FTPTimeout",120);
define("FTPLog","your login");
define("FTPPass","your password");
function ftpUp_checkForAndMakeDirs($ftpThread, $file) {
$parts = explode("/", dirname($file));
foreach ($parts as $curDir) {
if (#ftp_chdir($ftpThread, $curDir) === false) { // Attempt to change directory, suppress errors
ftp_mkdir($ftpThread, $curDir); //directory doesn't exist - so make it
ftp_chdir($ftpThread, $curDir); //go into the new directory
}
}
}
function ftpUp_progressCallBack($uploadedData){
global $abortRequested;
//you can do any action you want while file upload progress, personaly, il log progress in to data base
//and i request DB to know if user request a file transfert abort and set the var $abortRequested to true or false
}
function ftpUp($src,$file,$dest,$resume){
global $abortRequested;
$conn_id = ftp_connect(FTPAdd,FTPPort,FTPTimeout);
if ($conn_id==false){
echo "FTP Connection problem";return false;
}else{
$login_res = ftp_login($conn_id, FTPLog, FTPPass);
if ($login_res){
$ftpThread=$conn_id;
}else{
echo "FTP Authentification error";return false;
}
}
$fp = fopen($src, 'r');
ftpUp_checkForAndMakeDirs($ftpThread, $dest); //verif et creation de l'arborescence sur le serveur ftp
ftp_set_option ($ftpThread, FTP_AUTOSEEK, TRUE); // indispensable pour pouvoir faire du resume
if($resume){
$upload = ftp_nb_fput ($ftpThread, $file, $fp ,FTPUpMode, FTP_AUTORESUME);
}else{
$upload = ftp_nb_fput ($ftpThread, $file, $fp ,FTPUpMode);
}
///////////////////////////////////////////////////////////////////////////////////
//uploading process
while ($upload == FTP_MOREDATA) {
//progress of upload
ftpUp_progressCallBack(ftell ($fp));
//continue or abort
if(!$abortRequested){
$upload = ftp_nb_continue($ftpThread);
}else{
$upload = "userAbort";
}
}
///////////////////////////////////////////////////////////////////////////////////
//end and result
ftpUp_progressCallBack(ftell ($fp));
if ($upload != FTP_FINISHED) {
#fclose($fp);
#ftp_close ($ftpThread);
if ($abortRequested){
echo "FTP Abort by user : resume needed";
}else{
echo "FTP upload error : ".$upload." (try resume)";
}
}else{
#fclose($fp);
#ftp_close ($ftpThread);
echo "upload sucess";
}
}
$file="test.zip";
$src = "FilesToUp/" . $file;
$destDir = "www/data/upFiles/";
$dest = $destDir . $file;
$abortRequested=false;
ftpUp($src,$file,$dest,true);
I was searching for a viable answer using CURL + PHP to resume a transfer that was broken and could not find clear, viable solution on the internet. This is an OLD question but I figured it did need a proper answer. This is the result of a day or two of research. See functions below and quick usage example.
Connect function:
function ftp_getconnect($uName, $pWord, $uHost)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "$uName:$pWord");
curl_setopt($ch, CURLOPT_URL, $uHost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
if($return === false)
{
print_r(curl_getinfo($ch));
echo curl_error($ch);
curl_close($ch);
die('Could not connect');
}
else
{
return $ch;
}
}
Disconnect function:
function ftp_disconnect($ch)
{
$return = curl_close($ch);
if($return === false)
{
return "Error: Could not close connection".PHP_EOL;
}
else
{
return $return;
}
}
Function to get the remote file size (in bytes):
function get_rem_file_size($ch, $rem_file)
{
curl_setopt($ch, CURLOPT_INFILE, STDIN);
curl_setopt($ch, CURLOPT_URL, $rem_file);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FTP_CREATE_MISSING_DIRS, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FTPLISTONLY, false);
$return = curl_exec($ch);
if($return === false)
{
print_r(curl_getinfo($ch));
echo curl_error($ch);
curl_close($ch);
die('Could not connect');
}
else
{
$file_header = curl_getinfo($ch);
return $file_header['download_content_length'];
}
}
Upload file function:
function upload_file($ch,$local_file,$remote_file,$resume)
{
echo "attempting to upload $local_file to $remote_file".PHP_EOL;
$file = fopen($local_file, 'rb');
if($resume)
{
curl_setopt($ch, CURLOPT_RESUME_FROM, get_rem_file_size($ch, $remote_file));
}
curl_setopt($ch, CURLOPT_URL, $remote_file);
curl_setopt($ch, CURLOPT_UPLOAD, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FTP_CREATE_MISSING_DIRS, true);
curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($local_file));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
if($return === false)
{
fclose($file);
return curl_error($ch).PHP_EOL;
}
else
{
fclose($file);
echo $local_file.' uploaded'.PHP_EOL;
return true;
}
}
Quick usage example:
$ftp = ftp_getconnect($uName, $pWord, 'ftp://'.$uHost);
$rem_file = 'ftp://'.$uHost.'/path/to/remote/file.ext';
$loc_file = 'path/to/local/file.ext';
$resume = 'true';
$success = upload_file($ftp, $loc_file, $rem_file, $resume);
if($success !== true)
{
//failure
echo $success;
curl_close($ch);
}
print_r(ftp_disconnect($ftp));
Quick note, if there is a large set of files, you can loop through them and upload_file without connecting/disconnecting each time.